Archives of the Sphere Online Judge

classical problemset

 

 

 

Last updated: 2014-10-12 21:50:59

Preface

This electronic material contains a set of algorithmic problems, forming the archives of the Sphere Online Judge (http://www.spoj.com/), classical problemset. The document can be accessed at the following URLs:

These resources are constantly updated to synchronise with the ever-changing hypertext version of the problems, and to include newly added problems. If you have obtained this document from another source, it is strongly recommended that you should download the current version from one of the aforementioned URLs.

 

Enjoy problem-solving at the Sphere Online Judge!

 

 

 

 

 

 

 

 

 

 

Disclaimer from the Editors. Despite our best efforts, it is possible that this document contains errors or that some of the content differs slightly from its original hypertext form. We take no responsibility for any such faults and their consequences. We neither authorise nor approve use of this material for any purpose other than facilitating problem solving at the Sphere Online Judge site; nor do we guarantee its fitness for any purpose whatsoever.

The layout of the problems in this document is the copyright of the Editors named on the cover (as determined by the appropriate footers in the problem description). The content is the copyright of the respective Editor unless the copyright holder is otherwise stated in the 'resource' section. The document as a whole is not protected by copyright, and fragments of it are to be regarded independently. No responsibility is taken by the Editors if use or redistribution of this document violates either their or third party copyright laws. When referring to or citing the whole or a fragment of this document, please state clearly the aforementioned URLs at which the document is to be found, as well as the resources from which the problems you are referring to originally came.

Remarks concerning this document should be sent to the following e-mail address: contact@spoj.com.

Table of Contents

  1. Problem TEST (1. Life, the Universe, and Everything)
  2. Problem PRIME1 (2. Prime Generator)
  3. Problem SBSTR1 (3. Substring Check (Bug Funny))
  4. Problem ONP (4. Transform the Expression)
  5. Problem PALIN (5. The Next Palindrome)
  6. Problem ARITH (6. Simple Arithmetics)
  7. Problem BULK (7. The Bulk!)
  8. Problem CMPLS (8. Complete the Sequence!)
  9. Problem DIRVS (9. Direct Visibility)
  10. Problem CMEXPR (10. Complicated Expressions)
  11. Problem FCTRL (11. Factorial)
  12. Problem MMIND (12. The Game of Master-Mind)
  13. Problem HOTLINE (13. Hotline)
  14. Problem IKEYB (14. I-Keyboard)
  15. Problem SHPATH (15. The Shortest Path)
  16. Problem TETRA (16. Sphere in a tetrahedron)
  17. Problem CRYPTO1 (17. The Bytelandian Cryptographer (Act I))
  18. Problem CRYPTO2 (18. The Bytelandian Cryptographer (Act II))
  19. Problem CRYPTO3 (19. The Bytelandian Cryptographer (Act III))
  20. Problem CRYPTO4 (20. The Bytelandian Cryptographer (Act IV))
  21. Problem TRICENTR (22. Triangle From Centroid)
  22. Problem PIR (23. Pyramids)
  23. Problem FCTRL2 (24. Small factorials)
  24. Problem POUR1 (25. Pouring water)
  25. Problem BSHEEP (26. Build the Fence)
  26. Problem SBANK (27. Sorting Bank Accounts)
  27. Problem HMRO (28. Help the Military Recruitment Office!)
  28. Problem HASHIT (29. Hash it!)
  29. Problem BLINNET (30. Bytelandian Blingors Network)
  30. Problem MUL (31. Fast Multiplication)
  31. Problem NHAY (32. A Needle in the Haystack)
  32. Problem TRIP (33. Trip)
  33. Problem RUNAWAY (34. Run Away)
  34. Problem EQBOX (35. Equipment Box)
  35. Problem CODE1 (36. Secret Code)
  36. Problem PROPKEY (37. The Proper Key)
  37. Problem LABYR1 (38. Labyrinth)
  38. Problem PIGBANK (39. Piggy-Bank)
  39. Problem STONE (40. Lifting the Stone)
  40. Problem WORDS1 (41. Play on Words)
  41. Problem ADDREV (42. Adding Reversed Numbers)
  42. Problem BOOKS1 (43. Copying Books)
  43. Problem SCYPHER (44. Substitution Cipher)
  44. Problem COMMEDIA (45. Commedia dell Arte)
  45. Problem SCRAPER (47. Skyscraper Floors)
  46. Problem BEADS (48. Glass Beads)
  47. Problem HAREFOX (49. Hares and Foxes)
  48. Problem INCARDS (50. Invitation Cards)
  49. Problem TOUR (51. Fake tournament)
  50. Problem JULKA (54. Julka)
  51. Problem JASIEK (55. Jasiek)
  52. Problem DYZIO (56. Dyzio)
  53. Problem SUPPER (57. Supernumbers in a permutation)
  54. Problem PICAD (58. Crime at Piccadily Circus)
  55. Problem BIA (59. Bytelandian Information Agency)
  56. Problem DANCE (60. The Gordian Dance)
  57. Problem BRCKTS (61. Brackets)
  58. Problem IMP (62. The Imp)
  59. Problem SQRBR (63. Square Brackets)
  60. Problem PERMUT1 (64. Permutations)
  61. Problem BALL1 (65. Ball)
  62. Problem CRSCNTRY (66. Cross-country)
  63. Problem CUTOUT (67. Cutting out)
  64. Problem EXPR1 (68. Expression)
  65. Problem MOULDS (69. Moulds)
  66. Problem RELATS1 (70. Relations)
  67. Problem TREE1 (71. Tree)
  68. Problem BAC (73. Bacterial)
  69. Problem EDIT1 (75. Editor)
  70. Problem EDIT2 (76. Editor Inverse)
  71. Problem BRICKS (77. New bricks disorder)
  72. Problem MARBLES (78. Marbles)
  73. Problem EASYPIE (82. Easy Problem)
  74. Problem BUNDLE (83. Bundling)
  75. Problem SHORTCUT (84. Shortcut)
  76. Problem DICE1 (85. Dice Contest)
  77. Problem RAIN1 (86. November Rain)
  78. Problem FOOTBALL (87. Football)
  79. Problem TREE2 (88. Which is Next)
  80. Problem HANGLET (89. Hang or not to hang)
  81. Problem MINIMAX (90. Minimizing maximizer)
  82. Problem TWOSQRS (91. Two squares or not two squares)
  83. Problem CUTSQRS (92. Cutting off Squares)
  84. Problem MAYA (94. Numeral System of the Maya)
  85. Problem STPAR (95. Street Parade)
  86. Problem SHOP (96. Shopping)
  87. Problem PARTY (97. Party Schedule)
  88. Problem DFLOOR (98. Dance Floor)
  89. Problem BUS (99. Bus)
  90. Problem BABTWR (100. Tower of Babylon)
  91. Problem FISHER (101. Fishmonger)
  92. Problem LITEPIPE (102. GX Light Pipeline Inc)
  93. Problem HIGH (104. Highways)
  94. Problem ALICEBOB (105. Alice and Bob)
  95. Problem BINSTIRL (106. Binary Stirling Numbers)
  96. Problem MAYACAL (107. Calendar of the Maya)
  97. Problem MORSE (108. Decoding Morse Sequences)
  98. Problem EXCHNG (109. Exchanges)
  99. Problem CISTFILL (110. Fill the Cisterns)
  100. Problem SEGVIS (112. Horizontally Visible Segments)
  101. Problem FAMILY (115. Family)
  102. Problem INTERVAL (116. Intervals)
  103. Problem RHOMBS (118. Rhombs)
  104. Problem SERVERS (119. Servers)
  105. Problem SOLIT (120. Solitaire)
  106. Problem TTABLE (121. Timetable)
  107. Problem STEVE (122. Voracious Steve)
  108. Problem PAYING (123. Paying in Byteland)
  109. Problem RENT (130. Rent your airplane and make money)
  110. Problem SQDANCE (131. Square dance)
  111. Problem HELPR2D2 (132. Help R2-D2!)
  112. Problem PHONY (134. Phony Primes)
  113. Problem MAWORK (135. Men at work)
  114. Problem TRANS (136. Transformation)
  115. Problem PARTIT (137. Partition)
  116. Problem POSTERS (138. Election Posters)
  117. Problem MAZE (139. The Long and Narrow Maze)
  118. Problem LONER (140. The Loner)
  119. Problem GLUE (142. Johnny and the Glue)
  120. Problem ALIENS (145. Aliens)
  121. Problem MULTIPLY (146. Fast Multiplication Again)
  122. Problem TAUT (147. Tautology)
  123. Problem MLAND (148. Land for Motorways)
  124. Problem FSHEEP (149. Fencing in the Sheep)
  125. Problem PLONK (150. Where to Drink the Plonk?)
  126. Problem COURIER (151. The Courier)
  127. Problem SCALES (153. Balancing the Stone)
  128. Problem ROCK (154. Sweet and Sour Rock)
  129. Problem PALSEC (160. Choosing a Palindromic Sequence)
  130. Problem PAINTTMP (174. Paint templates)
  131. Problem POLY1 (175. Polygon)
  132. Problem SUM1SEQ (176. Sum of one-sequence)
  133. Problem ABWORDS (177. AB-words)
  134. Problem ROADNET (178. Road net)
  135. Problem WORDEQ (179. Word equations)
  136. Problem CONTPACK (180. How to pack containers)
  137. Problem SCUBADIV (181. Scuba diver)
  138. Problem WINDOW1 (182. Window)
  139. Problem ASCIRC (183. Assembler circuits)
  140. Problem ATMS (184. Automatic Teller Machines)
  141. Problem CHASE1 (185. Chase)
  142. Problem LITELANG (186. The lightest language)
  143. Problem FLBRKLIN (187. Flat broken lines)
  144. Problem RECTNG1 (188. Rectangles)
  145. Problem MUSKET (196. Musketeers)
  146. Problem EMPTY (199. Empty Cuboids)
  147. Problem MONODIG (200. Monodigital Representations)
  148. Problem POLYGAME (201. The Game of Polygons)
  149. Problem ROCKETS (202. Rockets)
  150. Problem POTHOLE (203. Potholers)
  151. Problem SLEEP (204. Sleepwalker)
  152. Problem ICERINK (205. Icerink)
  153. Problem BITMAP (206. Bitmap)
  154. Problem THREECOL (207. Three-coloring of binary trees)
  155. Problem STORE (208. Store-keeper)
  156. Problem MAP (209. The Map)
  157. Problem ALTARS (210. The Altars)
  158. Problem PRIMIT (211. Primitivus recurencis)
  159. Problem WATER (212. Water among Cubes)
  160. Problem PANIC (215. Panic in the Plazas)
  161. Problem SOPARADE (217. Soldiers on Parade)
  162. Problem PHRASES (220. Relevant Phrases of Annihilation)
  163. Problem VONNY (224. Vonny and her dominos)
  164. Problem JEWELS (226. Jewelry and Fashion)
  165. Problem ORDERS (227. Ordering the Soldiers)
  166. Problem SHAMAN (228. Shamans)
  167. Problem SORTING (229. Sorting is easy)
  168. Problem ZEBRA (231. The Zebra Crossing)
  169. Problem HOLIDAY1 (234. Getting Rid of the Holidays (Act I))
  170. Problem VFMUL (235. Very Fast Multiplication)
  171. Problem ROMAN (236. Converting number formats)
  172. Problem SUMITR (237. Sums in a Triangle)
  173. Problem HOLIDAY2 (238. Getting Rid of the Holidays (Act II))
  174. Problem BTOUR (239. Tour de Byteland)
  175. Problem BLOCKS (241. Arranging the Blocks)
  176. Problem STABLEMP (243. Stable Marriage Problem)
  177. Problem SQRROOT (245. Square Root)
  178. Problem CHOCOLA (247. Chocolate)
  179. Problem CTAIN (260. Containers)
  180. Problem TRIPART (261. Triangle Partitioning)
  181. Problem CONNECT (262. Connections)
  182. Problem PERIOD (263. Period)
  183. Problem CORNET (264. Corporative Network)
  184. Problem CAVE (272. Cave Exploration)
  185. Problem WMELON (274. Johnny and the Watermelon Plantation)
  186. Problem WATERWAY (275. The Water Ringroad)
  187. Problem CTGAME (277. City Game)
  188. Problem BICYCLE (278. Bicycle)
  189. Problem INUMBER (279. Interesting number)
  190. Problem LIFTS (280. Lifts)
  191. Problem MUDDY (282. Muddy Fields)
  192. Problem NAPTIME (283. Naptime)
  193. Problem SCITIES (286. Selfish Cities)
  194. Problem NETADMIN (287. Smart Network Administrator)
  195. Problem PON (288. Prime or Not)
  196. Problem POLYEQ (290. Polynomial Equations)
  197. Problem CUBERT (291. Cube Root)
  198. Problem ALIBB (292. Alibaba)
  199. Problem OFBEAT (293. Officers on the Beat)
  200. Problem TWORK (296. Teamwork is Crucial)
  201. Problem AGGRCOW (297. Aggressive cows)
  202. Problem CABLETV (300. Cable TV Network)
  203. Problem BOOK (301. Booklets)
  204. Problem CANTON (302. Count on Cantor)
  205. Problem UCUBE (303. The Unstable Cube)
  206. Problem RATTERN (309. The Room Pattern)
  207. Problem PITPAIR (318. Pythagorean Legacy)
  208. Problem WINDMILL (325. The Tall Windmills)
  209. Problem PLATON (327. Platon and Socrates)
  210. Problem BISHOPS (328. Bishops)
  211. Problem CALLS (329. Calls)
  212. Problem HARDQ (332. Hard Question)
  213. Problem PHDISP (334. The Philosophical Dispute)
  214. Problem EOPERA (336. Exchange Operations)
  215. Problem SEQ (339. Recursive Sequence)
  216. Problem POKER (344. Poker)
  217. Problem MIXTURES (345. Mixtures)
  218. Problem COINS (346. Bytelandian gold coins)
  219. Problem EXPEDI (348. Expedition)
  220. Problem AROUND (349. Around the world)
  221. Problem LANDSCAP (350. Landscaping)
  222. Problem HAN01 (351. Ha-noi!)
  223. Problem ACT (359. Alpha Centauri Tennis)
  224. Problem IGARB (362. Ignore the Garbage)
  225. Problem LISA (364. Pocket Money)
  226. Problem PHIDIAS (365. Phidias)
  227. Problem FARMER (366. Farmer)
  228. Problem EMPODIA (367. Empodia)
  229. Problem CSTREET (368. Cobbled streets)
  230. Problem MATH1 (369. Math I)
  231. Problem ONEZERO (370. Ones and zeros)
  232. Problem BENEFACT (372. The Benefactor)
  233. Problem GREED (373. Greedy island)
  234. Problem MATRIX (374. Count maximum matrices)
  235. Problem QTREE (375. Query on a tree)
  236. Problem ACS (376. A concrete simulation)
  237. Problem TAXI (377. Taxi)
  238. Problem PERMUT2 (379. Ambiguous Permutations)
  239. Problem BINGO (380. Bullshit Bingo)
  240. Problem CHICAGO (381. 106 miles to Chicago)
  241. Problem DECORATE (382. Decorate the wall)
  242. Problem EUROPEAN (383. European railroad tracks)
  243. Problem FOOL (384. Any fool can do it)
  244. Problem GAME (385. Game schedule required)
  245. Problem HELP (386. Help the problem setter)
  246. Problem TOURS (387. Travelling tours)
  247. Problem MENU (388. Menu)
  248. Problem HOSPITAL (389. Use of Hospital Facilities)
  249. Problem BILLIARD (390. Billiard)
  250. Problem RAILROAD (391. Railroads)
  251. Problem SPIN (392. Spin)
  252. Problem HEXAGON (393. Hexagon)
  253. Problem ACODE (394. Alphacode)
  254. Problem APRIME (395. Anti-prime Sequences)
  255. Problem HITOMISS (396. Hit or Miss)
  256. Problem CONDUIT (397. I Conduit)
  257. Problem RPGAMES (398. Roll Playing Games)
  258. Problem TRANK (399. Team Rankings)
  259. Problem TOANDFRO (400. To and Fro)
  260. Problem TRANSL (401. Translations)
  261. Problem HIKE (402. Hike on a Graph)
  262. Problem FRACTION (403. Sort fractions)
  263. Problem SCANNER (404. Scanner)
  264. Problem TCUTTER (405. Tin Cutter)
  265. Problem LOGIC (406. Logic)
  266. Problem RNUMBER (407. Random Number)
  267. Problem JRIDE (408. Jill Rides Again)
  268. Problem DELCOMM (409. DEL Command)
  269. Problem VHUFFM (410. Variable Radix Huffman Encoding)
  270. Problem NUMQDW (411. Number of quite different words)
  271. Problem COVER (412. K-path cover)
  272. Problem WPUZZLES (413. Word Puzzles)
  273. Problem BONFIRE (414. Equatorial Bonfire)
  274. Problem DIV15 (416. Divisibility by 15)
  275. Problem LAZYPROG (417. The lazy programmer)
  276. Problem NECKLACE (418. Necklace)
  277. Problem TRANSP (419. Transposing is Fun)
  278. Problem AROAD (421. Another Road Problem)
  279. Problem TRANSP2 (422. Transposing is Even More Fun)
  280. Problem ASSIGN (423. Assignments)
  281. Problem PARTPALI (428. Particular Palindromes)
  282. Problem TCNUMFL (449. Simple Numbers with Fractions Conversion)
  283. Problem TFOSS (484. Fossil in the Ice)
  284. Problem CLTZ (515. Collatz)
  285. Problem ZZPERM (518. Zig-Zag Permutation)
  286. Problem DIV (526. Divisors)
  287. Problem DIV2 (530. Divisors 2)
  288. Problem INCR (598. Increasing Subsequences)
  289. Problem QUEST4 (660. Dungeon of Death)
  290. Problem QUEST5 (661. Nail Them)
  291. Problem SUBS (665. String it out)
  292. Problem VOCV (666. Con-Junctions)
  293. Problem LSORT (676. Sorting is not easy)
  294. Problem BROW (677. A place for the brewery)
  295. Problem HANOI07 (681. Building the Tower)
  296. Problem PAIRINT (682. Pairs of Integers)
  297. Problem ASSIGN4 (684. Another Assignment Problem)
  298. Problem SEQPAR (685. Partition the sequence)
  299. Problem REPEATS (687. Repeats)
  300. Problem SAM (688. Toy Cars)
  301. Problem LWAR (693. Lethal Warfare)
  302. Problem DISUBSTR (694. Distinct Substrings)
  303. Problem UFAST (695. Unite Fast)
  304. Problem LIAR (696. Liar Liar)
  305. Problem MWORDS (697. Matrix Words)
  306. Problem PLHOP (698. Plane Hopping)
  307. Problem HKNAP (699. Huge Knap Sack)
  308. Problem BPRED (700. Branch Prediction)
  309. Problem EXPAND (702. Barn Expansion)
  310. Problem SERVICE (703. Mobile Service)
  311. Problem PSTRING (704. Remove The String)
  312. Problem SUBST1 (705. New Distinct Substrings)
  313. Problem TFSETS (707. Triple-Free Sets)
  314. Problem NICEDAY (709. The day of the competitors)
  315. Problem PRO (726. Promotion)
  316. Problem MAXIMUS (729. Move your armies)
  317. Problem IVAN (734. Ivan and his interesting game)
  318. Problem MDST (735. Minimum Diameter Spanning Tree)
  319. Problem TREE (738. Another Counting Problem)
  320. Problem NEG2 (739. The Moronic Cowmpouter)
  321. Problem TRT (740. Treats for the Cows)
  322. Problem STEAD (741. Steady Cow Assignment)
  323. Problem LPERMUT (744. Longest Permutation)
  324. Problem TEM (757. Thermal Luminescence)
  325. Problem CH3D (760. Convex Hull 3D)
  326. Problem ARCHPLG (780. The Archipelago)
  327. Problem TRIOPT (827. Trigonometric optimization)
  328. Problem OPTM (839. Optimal Marks)
  329. Problem WM06 (850. Soccer Choreography)
  330. Problem SWAPS (861. Counting inversions)
  331. Problem DNA (866. DNA Translation)
  332. Problem CUBES (867. Perfect Cubes)
  333. Problem IMPORT (869. Galactic Import)
  334. Problem BASE (870. Basically Speaking)
  335. Problem SEQUENCE (871. Letter Sequence Analysis)
  336. Problem MARKUP (872. Mark-up)
  337. Problem TRANSMIT (898. Transmitters)
  338. Problem WSCIPHER (899. Ws Cipher)
  339. Problem SPLIT (900. Split Windows)
  340. Problem INDEXGEN (901. Index Generation)
  341. Problem HANGOVER (902. Hangover)
  342. Problem DOUBLEVI (903. Double Vision)
  343. Problem IMAGE (904. Image Perimeters)
  344. Problem MATRIX2 (912. Submatrix of submatrix)
  345. Problem QTREE2 (913. Query on a tree II)
  346. Problem FTOUR (944. Free Tour)
  347. Problem IM (962. Intergalactic Map)
  348. Problem EN (964. Entrapment)
  349. Problem PB (967. Parking Bay)
  350. Problem BIRTHDAY (972. Birthday)
  351. Problem MOBILE (987. Mobile)
  352. Problem CFRAC (996. Continuous Fractions)
  353. Problem MATRIOSH (999. Generalized Matrioshkas)
  354. Problem EQDIV (1000. Equidivisions)
  355. Problem BROUL (1001. Babylonian Roulette)
  356. Problem UJ (1002. Uncle Jack)
  357. Problem QUILT (1003. Little Quilt)
  358. Problem POLYCODE (1004. Polygon Encoder)
  359. Problem AIBOHP (1021. Aibohphobia)
  360. Problem ANGELS (1022. Angels and Devils)
  361. Problem COMCB (1024. Complete Chess Boards)
  362. Problem FASHION (1025. Fashion Shows)
  363. Problem FAVDICE (1026. Favorite Dice)
  364. Problem FPOLICE (1027. Fool the Police)
  365. Problem HUBULLU (1028. Hubulullu)
  366. Problem MATSUM (1029. Matrix Summation)
  367. Problem EIGHTS (1030. Triple Fat Ladies)
  368. Problem UPSUB (1031. Up Subsequence)
  369. Problem GSS1 (1043. Can you answer these queries I)
  370. Problem CTRICK (1108. Card Trick)
  371. Problem SUDOKU (1110. Sudoku)
  372. Problem NSTEPS (1112. Number Steps)
  373. Problem TOE1 (1161. Tic-Tac-Toe ( I ))
  374. Problem TOE2 (1162. Tic-Tac-Toe ( II ))
  375. Problem JAVAC (1163. Java vs C ++)
  376. Problem DEADFR (1166. Dead Fraction)
  377. Problem MINCOUNT (1167. Move To Invert)
  378. Problem SORTBIT (1182. Sorted bit squence)
  379. Problem PALACE (1183. Accomodate the palace)
  380. Problem ORIGLIFE (1267. Origin of Life)
  381. Problem CNEASY (1268. CN Tower (Easy))
  382. Problem CNHARD (1269. CN Tower (Hard))
  383. Problem PNTBYNUM (1270. Paint By Numbers)
  384. Problem CFRAC2 (1285. Continuous Fractions Again)
  385. Problem SUMFOUR (1296. 4 values whose sum is 0)
  386. Problem PARTSUM (1325. Partial Sums)
  387. Problem CHASE (1326. A Chase In WonderLand)
  388. Problem KPMATRIX (1329. Matrix)
  389. Problem KPMAZE (1335. Maze)
  390. Problem CZ_PROB1 (1391. Summing to a Square Prime)
  391. Problem CATM (1418. The Cats and the Mouse)
  392. Problem NGM (1419. A Game with Numbers)
  393. Problem GEOM (1420. Geometry and a Square)
  394. Problem FIRM (1421. Goods)
  395. Problem KPPOLY (1431. Projections Of A Polygon)
  396. Problem KPSUM (1433. The Sum)
  397. Problem KPEQU (1434. Equation)
  398. Problem PT07X (1435. Vertex Cover)
  399. Problem PT07Y (1436. Is it a tree)
  400. Problem PT07Z (1437. Longest path in a tree)
  401. Problem ARCTAN (1440. Use of Function Arctan)
  402. Problem CLEVER (1441. The Clever Typist)
  403. Problem CHAIN (1442. Strange Food Chain)
  404. Problem DELCOMM2 (1444. DEL Command II)
  405. Problem BRCKGAME (1447. A Game of Toy Bricks)
  406. Problem COVER2 (1448. 3D Cover)
  407. Problem SEQ1 (1451. 01 Sequence)
  408. Problem CAKE (1452. Birthday Cake)
  409. Problem OPTSUB (1453. Optimal Connected Subset)
  410. Problem MEMDIS (1454. Memory Distribution)
  411. Problem ANALYSER (1455. Program Analyser)
  412. Problem BLUEEQ (1457. Help Blue Mary Please! (Act I))
  413. Problem BLUEEQ2 (1458. Help Blue Mary Please! (Act II))
  414. Problem AEROLITE (1459. The Secret of an Aerolite)
  415. Problem GALAXY (1460. A Simple Calculator in the Galaxy)
  416. Problem DRAGON (1461. Greedy Hydra)
  417. Problem BARB (1462. Barbarians)
  418. Problem ROBOT (1463. Robot Number M)
  419. Problem EDIT3 (1464. Editor II)
  420. Problem CHRIS (1465. On the Way to Find Chris)
  421. Problem CASHIER (1466. Blue Mary Needs Help Again)
  422. Problem RAIN2 (1468. Outside it is now raining)
  423. Problem SEQ2 (1470. Another Sequence Problem)
  424. Problem PRLGAME (1471. A Game of Pearls)
  425. Problem TOMJERRY (1472. Tom and Jerry)
  426. Problem LEMON (1473. Lemon Tree in the Moonlight)
  427. Problem WORMS (1475. VII - Act IV)
  428. Problem PROFIT (1476. Maximum Profit)
  429. Problem PT07A (1477. Play with a Tree)
  430. Problem PT07B (1478. The Easiest Problem)
  431. Problem PT07C (1479. The GbAaY Kingdom)
  432. Problem PT07D (1480. Let us count 1 2 3)
  433. Problem PT07F (1482. A short vacation in Disneyland)
  434. Problem PT07G (1483. Colorful Lights Party)
  435. Problem PT07H (1484. Search in XML)
  436. Problem PT07J (1487. Query on a tree III)
  437. Problem MOLE (1505. Whac-a-Mole)
  438. Problem RSORTING (1526. Ranklist Sorting)
  439. Problem BLUEEQ3 (1536. Help Blue Mary Please! (Act III))
  440. Problem MKJUMPS (1538. Making Jumps)
  441. Problem MOBILE2 (1552. Mobiles)
  442. Problem BACKUP (1553. Backup Files)
  443. Problem ZOO (1554. Zoo)
  444. Problem GSS2 (1557. Can you answer these queries II)
  445. Problem TREEOI14 (1644. Trees)
  446. Problem AMATH (1671. Another Mathematical Problem)
  447. Problem GIWED (1672. The Great Indian Wedding)
  448. Problem AMBM (1673. Ambitious Manager)
  449. Problem EXPLOSN (1674. The Explosion)
  450. Problem FUSION (1675. Fusion Cube)
  451. Problem GEN (1676. Text Generator)
  452. Problem HALLOW (1677. Halloween treats)
  453. Problem TREASURY (1678. Royal Treasury)
  454. Problem CYLINDER (1681. Cylinder)
  455. Problem EXPRESS (1683. Expressions)
  456. Problem FREQUENT (1684. Frequent values)
  457. Problem GROCERY (1685. Grocery store)
  458. Problem LOGIC2 (1687. Logic II)
  459. Problem EASYPROB (1688. A Very Easy Problem!)
  460. Problem HARDP (1689. Hard Problem)
  461. Problem COCONUTS (1693. Coconuts)
  462. Problem GRC (1695. Grandpa’s Rubik Cube)
  463. Problem WIJGT (1696. Will Indiana Jones Get There)
  464. Problem OFORTUNE (1697. Ohgas' Fortune)
  465. Problem PLSEARCH (1698. Polygonal Line Search)
  466. Problem NSYSTEM (1699. Numeral System)
  467. Problem TRSTAGE (1700. Traveling by Stagecoach)
  468. Problem EOWAMRT (1701. Earth Observation with a Mobile Robot Team)
  469. Problem CLEANRBT (1702. Cleaning Robot)
  470. Problem ACMAKER (1703. ACM (ACronymMaker))
  471. Problem CDOWN (1704. Countdown)
  472. Problem GAMEFIL (1705. The Game of Efil)
  473. Problem QKP (1706. Queens, Knights and Pawns)
  474. Problem RELINETS (1707. Reliable Nets)
  475. Problem SQCOUNT (1708. Square Count)
  476. Problem SWTHIN (1709. Swamp Things)
  477. Problem TWENDS (1710. Two Ends)
  478. Problem PRMLX (1712. Permalex)
  479. Problem SCALE (1713. Funny scales)
  480. Problem NCKLCE (1715. Another Necklace Problem)
  481. Problem GSS3 (1716. Can you answer these queries III)
  482. Problem RP (1722. Life, the Universe, and Everything II)
  483. Problem BMJ (1723. Bee Maja)
  484. Problem TRICOUNT (1724. Counting Triangles)
  485. Problem IMPORT1 (1725. The Importance)
  486. Problem EXCHANGE (1726. Exchange)
  487. Problem CPRMT (1728. Common Permutation)
  488. Problem TCOUNT2 (1730. Counting Triangles II)
  489. Problem TCOUNT3 (1731. Counting Triangles III)
  490. Problem EQU2 (1739. Yet Another Equation)
  491. Problem TETRIS3D (1741. Tetris 3D)
  492. Problem POLEVAL (1744. Evaluate the polynomial)
  493. Problem SEQPAR2 (1748. Sequence Partitioning II)
  494. Problem DIVSUM2 (1754. Divisor Summation (Hard))
  495. Problem NQUEEN (1771. Yet Another N-Queen Problem)
  496. Problem DETER2 (1772. Find The Determinant II)
  497. Problem ALL (1774. All Discs Considered)
  498. Problem BOOLE (1775. Boolean Logic)
  499. Problem DNALAB (1776. DNA Laboratory)
  500. Problem ICAMPSEQ (1784. IOICamp Sequence)
  501. Problem CODE (1785. Code)
  502. Problem DANGER (1786. In Danger)
  503. Problem ENCONDIN (1787. Run Length Encoding)
  504. Problem FRACTAN (1788. Fractan)
  505. Problem GREEDULM (1789. Huffman´s Greed)
  506. Problem HEAPULM (1790. Binary Search Heap Construction)
  507. Problem GEN2 (1793. Text Generater II)
  508. Problem DRAGON2 (1794. Greedy Hydra II)
  509. Problem CARD (1797. Cardsharper)
  510. Problem ASSIST (1798. Assistance Required)
  511. Problem BOTTOM (1799. The Bottom of a Graph)
  512. Problem CONTEST (1800. Fixed Partition Contest Management)
  513. Problem DRINK (1801. Drink, on Ice)
  514. Problem EDGE (1802. Edge)
  515. Problem FOLD (1803. Fold)
  516. Problem GENETIC (1804. Genetic Code)
  517. Problem HISTOGRA (1805. Largest Rectangle in a Histogram)
  518. Problem ORZ (1810. Nuclear Plants)
  519. Problem LCS (1811. Longest Common Substring)
  520. Problem LCS2 (1812. Longest Common Substring II )
  521. Problem WA (1815. Problems Collection (Volume X))
  522. Problem FTOUR2 (1825. Free tour II)
  523. Problem SUDOKU2 (1833. Sudoku)
  524. Problem SETSTACK (1835. The SetStack Computer)
  525. Problem PIE (1837. Pie)
  526. Problem TICKET (1838. Ticket to Ride)
  527. Problem BOOKCASE (1839. The Bookcase)
  528. Problem PQUEUE (1840. Printer Queue)
  529. Problem PPATH (1841. Prime Path)
  530. Problem LINELAND (1842. Lineland Airport)
  531. Problem LEONARDO (1843. Leonardo Notebook)
  532. Problem MICEMAZE (1845. Mice and Maze)
  533. Problem PFDEP (1846. Project File Dependencies)
  534. Problem NOCHANGE (1847. No Change)
  535. Problem MKWAVES (1865. Making Waves)
  536. Problem MKPALS (1866. Making Pals)
  537. Problem MKMONEY (1868. Making Money)
  538. Problem MKMOOM (1869. Making Mountains Out Of Molehills)
  539. Problem MKLABELS (1870. Making Labels)
  540. Problem MKBUDGET (1871. Making A Budget)
  541. Problem ACARGO (1873. Accumulate Cargo)
  542. Problem BWHEELER (1874. Burrows Wheeler Precompression)
  543. Problem COOLNUMS (1875. Cool Numbers)
  544. Problem DRAGONCU (1876. Dragon Curves)
  545. Problem EPURSE (1877. Enrich my purse)
  546. Problem FCATTLE (1878. Farmers Cattle)
  547. Problem GAMETIME (1879. Game Time)
  548. Problem HANOICAL (1880. Hanoi Calls)
  549. Problem ICODER (1881. Instruction Decoder)
  550. Problem RECTANGL (1960. Rectangles)
  551. Problem ROMANRDS (1961. Roman Roads)
  552. Problem CIRCLES (1962. Circles)
  553. Problem IMGPROJ (1963. Image Projections)
  554. Problem MMCUT (1964. Tree cut)
  555. Problem SETCOV (1965. Set Cover)
  556. Problem SKIVALL (1966. Ski Valley)
  557. Problem ACFRAC (1991. Another Continuous Fractions Problem)
  558. Problem BOX (2000. Boxes (Hard))
  559. Problem RNG (2002. Random Number Generator)
  560. Problem MINUS (2005. Minus Operation)
  561. Problem BALIFE (2006. Load Balancing)
  562. Problem COUNT (2007. Another Very Easy Problem! WOW!!!)
  563. Problem BACKPACK (2008. Dab of Backpack)
  564. Problem CRYPTO (2009. Cryptography)
  565. Problem ROLLBALL (2019. The Rolling Ball)
  566. Problem PEBBMOV (2021. Moving Pebbles)
  567. Problem TRUTHORL (2022. Truth Or Lie)
  568. Problem ONEINSTR (2023. One Instruction Computer Simulator)
  569. Problem YKH (2031. Please help You-Know-Who)
  570. Problem TILING (2038. Rectangle Tiling)
  571. Problem REMGAME (2047. Stone Removing Game)
  572. Problem CERC07B (2050. Strange Billboard)
  573. Problem CERC07C (2051. Cell Phone)
  574. Problem CERC07H (2052. Hexagonal Parcels)
  575. Problem CERC07K (2053. Key Task)
  576. Problem CERC07L (2054. Gates of Logic)
  577. Problem CERC07N (2055. Weird Numbers)
  578. Problem CERC07P (2056. Rectangular Polygon)
  579. Problem CERC07R (2058. Reaux! Sham! Beaux!)
  580. Problem CERC07S (2059. Robotic Sort)
  581. Problem CERC07W (2060. Tough Water Level)
  582. Problem MINDIST (2070. Minimum Distance)
  583. Problem CANDY (2123. Candy I)
  584. Problem FCTRL4 (2124. Last Non-Zero Digit of Factorials)
  585. Problem LABYR2 (2125. Number Labyrinth)
  586. Problem RAIN3 (2127. Rain)
  587. Problem KROW (2128. K-In-A-Row)
  588. Problem CAKE2 (2129. Cake)
  589. Problem TROLLS (2130. Trolls)
  590. Problem GETBACK (2131. Get Back!)
  591. Problem PUZZLE2 (2132. Puzzle)
  592. Problem CANDY2 (2136. Candy II)
  593. Problem PIB (2138. Pibonacci)
  594. Problem GOSSIPER (2139. Gossipers)
  595. Problem FAIRONOT (2140. (un)Fair Play)
  596. Problem GARDEN (2141. Golden Garden)
  597. Problem FLOWERS (2142. Arranging Flowers)
  598. Problem DEPEND (2143. Dependency Problems)
  599. Problem FOREST (2144. K Edge-disjoint Branchings)
  600. Problem ROOT (2147. Root of a Linear Equation)
  601. Problem CANDY3 (2148. Candy III)
  602. Problem BAISED (2149. Biased Standings)
  603. Problem SUBSEQ (2150. Counting Subsequences)
  604. Problem CALCULAT (2151. Digital Calculator)
  605. Problem FRACTAL (2152. Hilbert Curve)
  606. Problem IMATCH (2153. Internet is Faulty)
  607. Problem KRUSKAL (2154. Kruskal)
  608. Problem ABSYS (2157. Anti-Blot System)
  609. Problem CAKE3 (2159. Delicious Cake)
  610. Problem HERE (2160. Here-There)
  611. Problem JPIX (2161. Pixel Shuffle)
  612. Problem TOWER (2162. Towers of Powers)
  613. Problem AMCODES (2171. Ambiguous Codes)
  614. Problem EMOTICON (2175. Emoticons)
  615. Problem MUSIC (2185. Musical Optimization)
  616. Problem MKPAIRS (2189. Making Pairs)
  617. Problem TAN1 (2202. Tan and His Interesting Game)
  618. Problem BALLOON (2270. Balloons in a Box)
  619. Problem UCODES (2271. Undecodable Codes)
  620. Problem DESERT (2272. Crossing the Desert)
  621. Problem FERRY (2273. Ferries)
  622. Problem ISLHOP (2274. Island Hopping)
  623. Problem OIL (2275. Toil for Oil)
  624. Problem RECTNG2 (2276. Partitions)
  625. Problem SSORT (2277. Silly Sort)
  626. Problem LEXBRAC (2317. Bracket Sequence)
  627. Problem WORDS (2318. Overlapping Words)
  628. Problem BIGSEQ (2319. Sequence)
  629. Problem DISTANCE (2320. Manhattan)
  630. Problem SEGMENTS (2321. Segments)
  631. Problem TREEGAME (2322. Tree Game)
  632. Problem COMPASS (2323. Broken Compass)
  633. Problem MARIOGAM (2324. Mario)
  634. Problem STRDIST (2325. String Distance)
  635. Problem LIS2 (2371. Another Longest Increasing Subsequence Problem)
  636. Problem ARRANGE (2412. Arranging Amplifiers)
  637. Problem BUILD (2413. Building Beacons)
  638. Problem CCOST (2414. Calculate The Cost)
  639. Problem RESIST (2415. Kirchhof Law)
  640. Problem DSUBSEQ (2416. Distinct Subsequences)
  641. Problem ENEMY (2417. Eliminate The Enemies)
  642. Problem FFROG (2418. Flying Frogs)
  643. Problem GLGRID (2419. G-Line Grid)
  644. Problem HHAND (2420. Hospital at Hands)
  645. Problem ININT (2421. Incrementing The Integer)
  646. Problem JAZZYJOB (2422. Jazzy Job)
  647. Problem MINTRIAN (2423. Minimal Triangulations of Graphs)
  648. Problem PLD (2426. Palindromes)
  649. Problem RABBIT1 (2450. Counting Rabbits)
  650. Problem PHONELIN (2485. Phone Lines)
  651. Problem MAGIC4 (2511. Magic Program IV)
  652. Problem GNY07C (2525. Encoding)
  653. Problem GNY07D (2526. Decoding)
  654. Problem GNY07E (2527. Flipping Burned Pancakes)
  655. Problem GNY07F (2528. Monkey Vines)
  656. Problem GNY07G (2529. Model Rocket Height)
  657. Problem GNY07H (2530. Tiling a Grid With Dominoes)
  658. Problem GNY07I (2531. Spatial Concepts Test)
  659. Problem PERMUT3 (2565. Another Permutation Problem)
  660. Problem CLK (2631. Chomp)
  661. Problem SC1 (2643. Starcraft I)
  662. Problem KPARCH (2648. Archiver)
  663. Problem KPSORT (2649. Weird sorting)
  664. Problem WAR (2658. Art of War)
  665. Problem EXAMPLE (2660. Example)
  666. Problem ILLUM (2661. Illumination)
  667. Problem PUTIN (2662. Put a Point in a Hyperspace)
  668. Problem QTREE4 (2666. Query on a tree IV)
  669. Problem POLYSSQ (2668. Polygon)
  670. Problem MSTS (2670. Count Minimum Spanning Trees)
  671. Problem SPP (2699. Recursive Sequence (Version II))
  672. Problem UNTITLED (2709. Untitled Problem)
  673. Problem GSS4 (2713. Can you answer these queries IV)
  674. Problem COWCAR (2714. Cow Cars)
  675. Problem GLASNICI (2715. Glasnici)
  676. Problem QUADAREA (2716. Maximal Quadrilateral Area)
  677. Problem ARMY (2727. Army Strength)
  678. Problem BREAK (2728. Breaking in)
  679. Problem INVENT (2731. Inventing Test Data)
  680. Problem KEQ (2733. K Equal Digits)
  681. Problem LARGE (2734. Large party)
  682. Problem RAIL (2735. Simplify the Railroad System)
  683. Problem PRHYME (2737. Perfect Rhyme)
  684. Problem SUMSUMS (2742. Summing Sums)
  685. Problem PRETILE (2743. Prefix Tiling)
  686. Problem INCSEQ (2815. Increasing Subsequences)
  687. Problem CSUBSEQS (2816. Common Subsequences)
  688. Problem INCDSEQ (2817. Distinct Increasing Subsequences)
  689. Problem RRSCHED (2826. Round-Robin Scheduling)
  690. Problem TLE (2829. Time Limit Exceeded)
  691. Problem DETER3 (2832. Find The Determinant III)
  692. Problem SDGAME (2833. Super Dice Game)
  693. Problem MLE (2835. Memory Limit Exceeded)
  694. Problem BROKEN (2852. Broken Keyboard)
  695. Problem PDECODE (2853. Decode the Strings)
  696. Problem FOREST2 (2855. Forest)
  697. Problem HELPBOB (2856. Help Bob)
  698. Problem SDGAME2 (2877. Another understanding of Super Dice Game)
  699. Problem KNIGHTS (2878. Knights of the Round Table)
  700. Problem DOCTOR (2879. The Cow Doctor)
  701. Problem WILD (2880. Wild West)
  702. Problem CLONE (2881. Find the Clones)
  703. Problem WARE (2882. The Warehouse)
  704. Problem WIDGET (2883. Widget Factory)
  705. Problem MARTIAN (2884. Martian Mining)
  706. Problem WORDRING (2885. Word Rings)
  707. Problem PARTY2 (2898. Party of Cloaked Killers)
  708. Problem VOL (2899. Volunteers)
  709. Problem GEOPROB (2901. One Geometry Problem)
  710. Problem CANDY4 (2902. Candy IV)
  711. Problem TRANSP1 (2903. Transportation)
  712. Problem NOTATRI (2905. Not a Triangle)
  713. Problem GCD2 (2906. GCD2)
  714. Problem GSS5 (2916. Can you answer these queries V)
  715. Problem QTREE5 (2939. Query on a tree V)
  716. Problem UNTITLE1 (2940. Untitled Problem II)
  717. Problem SHOOTING (2944. Emmons)
  718. Problem ECLIPSE (2946. Eclipse)
  719. Problem PAINTBLK (2962. Painting Blocks (Act I))
  720. Problem PAINTBLC (2963. Painting Blocks (Act II))
  721. Problem ELECTRO (3002. Electrophoretic)
  722. Problem FILTER (3003. Median Filter)
  723. Problem LIFEGAME (3004. Life Game)
  724. Problem LAND (3005. Subdividing a Land)
  725. Problem LINE (3006. Connect Line Segments)
  726. Problem OILCOMP (3007. Oil Company)
  727. Problem RPS (3008. Finding the Top RPS Player)
  728. Problem VORONOI (3009. Revenge of Voronoi)
  729. Problem WALL (3010. Castle Wall)
  730. Problem SOLDIER (3033. Help the soldier)
  731. Problem SEQ5 (3070. How many subsequences)
  732. Problem MOD (3105. Power Modulo Inverted)
  733. Problem DICTSUB (3106. Dictionary Subsequences)
  734. Problem ODDDIV (3107. Odd Numbers of Divisors)
  735. Problem GRAPHGAM (3108. Charlesbert and Merangelou)
  736. Problem STRLCP (3109. Longest Common Prefix)
  737. Problem PALNUM (3110. Palindromic Number)
  738. Problem STABARDS (3111. Stabards)
  739. Problem STSTRING (3112. Strings)
  740. Problem GORELIAN (3133. Here We Go(relians) Again)
  741. Problem PERMSG (3166. Permutation Exponentiation)
  742. Problem LINES (3184. Game of Lines)
  743. Problem DOORSPEN (3195. Doors and Penguins)
  744. Problem PALIM (3208. Yet Another Longest Palindrome Problem)
  745. Problem TYPESET (3249. Typesettin)
  746. Problem SLINK (3251. Slink)
  747. Problem EDS (3253. Electronic Document Security)
  748. Problem GUARD (3254. Guard)
  749. Problem RACETIME (3261. Race Against Time)
  750. Problem SA04C (3305. Roman Patrollers)
  751. Problem SA04D (3306. Very Special Boxes )
  752. Problem HEXTILE (3307. Hex Tile Equations)
  753. Problem BRIDGES2 (3308. The Bridges of San Mochti)
  754. Problem BULLETIN (3309. Bulletin Board)
  755. Problem SERIALN (3310. Serial Numbers)
  756. Problem UMNOZAK (3314. Umnozak)
  757. Problem DOUBLE (3322. Doubled Numbers)
  758. Problem HIGHWAY (3347. Cestarine)
  759. Problem STACK (3359. Stack)
  760. Problem IMGREC2 (3360. Digital Image Recognition)
  761. Problem SVADA (3363. Svada)
  762. Problem ROUNDT (3372. Round Table)
  763. Problem PERMCODE (3373. Permutation Code)
  764. Problem SCAVHUNT (3374. Scavenger Hunt)
  765. Problem STAMPS (3375. Stamps)
  766. Problem PARKINGL (3376. Parking Lot)
  767. Problem BUGLIFE (3377. A Bug’s Life)
  768. Problem SSHUFFLE (3379. String Shuffle)
  769. Problem TOURIST (3380. Tourist)
  770. Problem HIGHWAYS (3381. Highways)
  771. Problem MONSTER (3382. Monster Trap)
  772. Problem YODA (3385. Yoda Goes Palindromic !)
  773. Problem CHMAZE (3387. Changing Maze)
  774. Problem DNPALIN (3388. Double Near Palindromes)
  775. Problem KNIGHTSR (3389. The Knights of the Round Circle)
  776. Problem TRIBE2 (3390. Tribe Council)
  777. Problem NOTOKNOT (3393. Knot or Not)
  778. Problem LAGRANGE (3394. Lagrange’s Four-Square Theorem)
  779. Problem SAMER08A (3405. Almost Shortest Path)
  780. Problem SAMER08B (3406. Bases)
  781. Problem SAMER08C (3407. Candy)
  782. Problem SAMER08D (3408. DNA Sequences)
  783. Problem SAMER08E (3409. Electricity)
  784. Problem SAMER08F (3410. Feynman)
  785. Problem SAMER08G (3411. Pole Position)
  786. Problem SAMER08H (3412. Higgs Boson)
  787. Problem SAMER08I (3413. Traveling Shoemaker Problem)
  788. Problem SAMER08J (3414. Bora Bora)
  789. Problem SAMER08K (3415. Shrinking Polygons)
  790. Problem FALLINGI (3420. Falling Ice)
  791. Problem OROSNAKE (3426. Ouroboros Snake)
  792. Problem HIST2 (3436. Histogram)
  793. Problem LASTDIG (3442. The last digit)
  794. Problem CEPC08B (3459. SkyScrapers)
  795. Problem SONG (3461. Song Contest)
  796. Problem RAMP (3462. The Skatepark´s New Ramps)
  797. Problem ROBIN (3463. Robintron)
  798. Problem DRIVE (3465. Drive through MegaCity)
  799. Problem DEPOSIT (3476. Deposit)
  800. Problem BABY (3477. Baby)
  801. Problem BEGIN (3483. Begin)
  802. Problem CROSSBIT (3484. Crossbits)
  803. Problem ELIM (3486. Elimination)
  804. Problem TOPCODE (3488. The Top-Code)
  805. Problem HIDTRI (3490. Hidden Triangle)
  806. Problem BRAILLE (3492. Braille Transcription)
  807. Problem NBLTHIEF (3495. The Nobel Thief)
  808. Problem MATRICA (3543. Matrica)
  809. Problem BST (3544. Binary Search Tree)
  810. Problem NAJKRACI (3545. Najkraci)
  811. Problem BOYSCOUT (3576. Boy Scouts)
  812. Problem PARITY (3577. Parity)
  813. Problem HASH (3578. Hashing)
  814. Problem DISJPATH (3579. Disjoint Paths)
  815. Problem TREESIM (3581. Tree Similarity)
  816. Problem RSTAURNT (3582. Restaurant Tab)
  817. Problem PATHEADS (3591. Patting Heads)
  818. Problem CATTLEB (3678. Cattle Bruisers)
  819. Problem MOOPIZZA (3679. Moo University - Emergency Pizza Order)
  820. Problem KGSS (3693. Maximum Sum)
  821. Problem PROOT (3713. Primitive Root)
  822. Problem SNOOKER (3723. Snooker)
  823. Problem RAINBOW (3724. Rainbow Ride)
  824. Problem TREX (3725. Taming a T-REX)
  825. Problem SUBSUMS (3749. Subset Sums)
  826. Problem GEORGE (3763. George)
  827. Problem STREET (3791. Street)
  828. Problem LUBEN (3831. Lubenica)
  829. Problem KRUS (3832. Kruska)
  830. Problem TRES (3833. Tresnja)
  831. Problem VCIRCLES (3863. Area of circles)
  832. Problem RELJEF (3865. Reljef)
  833. Problem VPALIN (3866. Finding Palindromes)
  834. Problem VBOSS (3867. Who is The Boss)
  835. Problem VMILI (3870. Military Story)
  836. Problem GCDEX (3871. GCD Extreme)
  837. Problem VPARTY (3872. Party At School)
  838. Problem WHEN (3884. When (You Believe))
  839. Problem BOBALLS (3894. Bouncing Balls)
  840. Problem BYTESE1 (3920. Lucius Dungeon)
  841. Problem BYTESE2 (3921. The Great Ball)
  842. Problem BYTESM1 (3922. Mystical River)
  843. Problem BYTESM2 (3923. Philosophers Stone)
  844. Problem BYTESH1 (3924. Filchs Dilemna)
  845. Problem FROGGER (3999. FROGGER)
  846. Problem GALLUP (4000. GALLUP)
  847. Problem SUBWAYPL (4003. Subway planning)
  848. Problem CPU (4004. Exploding CPU)
  849. Problem PHONELST (4033. Phone List)
  850. Problem CUCKOO (4036. Cuckoo Hashing)
  851. Problem KPGAME (4060. A game with probability)
  852. Problem MORPH (4069. Morphing is Fun)
  853. Problem TWOPROF (4070. Two Professors)
  854. Problem EPALIN (4103. Extend to Palindrome)
  855. Problem FASTFLOW (4110. Fast Maximum Flow)
  856. Problem ELLIPSE (4142. Ellipse)
  857. Problem DOMINO2 (4157. Domino)
  858. Problem HS08PAUL (4164. A conjecture of Paul Erdõs)
  859. Problem HS08FOUR (4166. Four colors)
  860. Problem SQFREE (4168. Square-free integers)
  861. Problem DROOT (4172. Multiplicative digital root)
  862. Problem KPURSUIT (4176. A Knightly Pursuit)
  863. Problem HERDING (4177. Herding)
  864. Problem LATTICE (4178. Distance on a square lattice)
  865. Problem TEMPTISL (4179. Temptation Island)
  866. Problem FCANDY (4182. Candy (Again))
  867. Problem CCCCUBE (4185. Cube)
  868. Problem HS08CODE (4186. Break a New RSA system)
  869. Problem HS08EQ (4188. Amazing equality)
  870. Problem LANDING (4189. Landing)
  871. Problem DOMINOES (4197. Dominoes)
  872. Problem LEGO (4198. Lego)
  873. Problem HAMSTER1 (4200. Hamster flight)
  874. Problem RATING (4201. Coder Ratings)
  875. Problem BRPAR (4202. Brackets Parade)
  876. Problem MATCHING (4206. Fast Maximum Matching)
  877. Problem QUEEN (4235. Wandering Queen)
  878. Problem TTTABLE (4273. Train TimeTable)
  879. Problem BFROTATE (4275. rotate it)
  880. Problem AE3A (4305. Drilling)
  881. Problem EVERLAST (4324. The fate of the pineapple)
  882. Problem EBOXES (4343. Empty Boxes)
  883. Problem DAGCNT (4407. Counting Arborescence)
  884. Problem FENCE1 (4408. Build a Fence)
  885. Problem AREA1 (4409. Circle vs Triangle)
  886. Problem REPAIR1 (4410. Repair the Door)
  887. Problem EXPR3 (4411. Counting Expressions)
  888. Problem FACTOR1 (4412. Factorization, Factorization, Factorization)
  889. Problem GEM (4413. Gem)
  890. Problem HIGHWAY1 (4414. Highway)
  891. Problem INTEGER1 (4415. Power of Integer)
  892. Problem JUMP1 (4416. Jumping Hands)
  893. Problem KPGRAPHS (4420. Counting Graphs)
  894. Problem GF2 (4421. Irreducible polynomials over GF2)
  895. Problem MIB (4429. Spelling Lists)
  896. Problem ARITH2 (4452. Simple Arithmetics II)
  897. Problem BOBALLS2 (4453. Bouncing Balls II)
  898. Problem BRCKTS2 (4454. Brackets II)
  899. Problem MOVIE (4455. Going to the Movies)
  900. Problem AIRLINES (4456. Jumbo Airlines)
  901. Problem SHOP2 (4457. Shopping II)
  902. Problem AIRLINE2 (4461. A Famous Airport Manager)
  903. Problem ANTTT (4465. The Ant)
  904. Problem PLAYFAIR (4476. Playfair Cracker)
  905. Problem EXPR4 (4478. Counting Expressions II)
  906. Problem GSS6 (4487. Can you answer these queries VI)
  907. Problem PGCD (4491. Primes in GCD Table)
  908. Problem UCI2009B (4523. Binomial Coefficients)
  909. Problem UCI2009D (4525. Digger Octaves)
  910. Problem FROGS (4528. Frog Wrestling)
  911. Problem BANDMATR (4533. Determinant of Banded Matrices)
  912. Problem ANARC08A (4546. Tobo or not Tobo)
  913. Problem ANARC08B (4549. Adding Sevens)
  914. Problem ANARC08C (4551. Match Maker)
  915. Problem ANARC08D (4552. Adding up Triangles)
  916. Problem ANARC08F (4555. Einbahnstrasse)
  917. Problem ANARC08G (4556. Think I will Buy Me a Football Team)
  918. Problem ANARC08H (4557. Musical Chairs)
  919. Problem ANARC08I (4558. I Speak Whales)
  920. Problem ANARC08J (4559. A Day at the Races)
  921. Problem CYCLERUN (4574. Riding in cycles)
  922. Problem ABCDEF (4580. ABCDEF)
  923. Problem GCJ08C (4585. Star Wars)
  924. Problem WLOO0707 (4586. Texas Trip)
  925. Problem FENCE3 (4587. Electric Fences)
  926. Problem NWERC04H (4588. SETI)
  927. Problem PMATRIX (4644. Proving Equivalences)
  928. Problem CCROSS (4656. Cross Mountain Climb)
  929. Problem GASWARS (4657. Gas Wars)
  930. Problem HHEMANT (4658. Help Hemant Verma)
  931. Problem WIRELESS (4666. Wireless)
  932. Problem GREMLINS (4667. Gremlins)
  933. Problem CCROSSX (4669. Cross Mountain Climb Extreme)
  934. Problem FUNPROB (4672. Yanu in Movie theatre)
  935. Problem TWICE (4681. Twice)
  936. Problem GPINTRI (4717. Grid Points in a Triangle)
  937. Problem HS09EQ (4784. Diophantine equation)
  938. Problem HS09SHIP (4785. Starship)
  939. Problem ZSEQ (4828. ZSequence)
  940. Problem BRI (4871. Bridge)
  941. Problem AMBIG (4881. Words on graphs)
  942. Problem DAGCNT2 (4882. Counting in a DAG)
  943. Problem RLM (4908. Run-Length Mathematics)
  944. Problem FACT1 (4941. Integer Factorization (20 digits))
  945. Problem FACT0 (4942. Integer Factorization (15 digits))
  946. Problem FACT2 (4948. Integer Factorization (29 digits))
  947. Problem BRII (4951. Bridges! More bridges!)
  948. Problem GOALFR (4987. Goal for Raúl)
  949. Problem MOWS (4988. Madrids One Way Streets)
  950. Problem FAKETSP (4993. Traveling Salesman)
  951. Problem LIM (5010. Lost in Madrid)
  952. Problem LFM (5011. Library for Madrid)
  953. Problem CRAZYR (5014. Crazy Receptionist)
  954. Problem CASTANET (5015. Decode the Castanets)
  955. Problem GUERNICA (5016. Guernica)
  956. Problem STRGAMB (5018. Street Gambler)
  957. Problem GCD3 (5084. Discrete Math Problem)
  958. Problem MBALL (5091. Feline Olympics - Mouseball)
  959. Problem PRETTY (5093. Pretty Functions)
  960. Problem MYSTIC (5102. Mystic Craft)
  961. Problem TOP10 (5103. Top 10)
  962. Problem SPAMD (5104. Spam Detection)
  963. Problem TUTMRBL (5107. Playing with Marbles)
  964. Problem SPHIWAY (5115. Two "Ways")
  965. Problem GERGOVIA (5117. Wine trading in Gergovia)
  966. Problem MINSEQ (5120. Minimal Possible String)
  967. Problem BOMB (5128. Bomb the Bridge)
  968. Problem PAIRGRPH (5142. A Pair of Graphs)
  969. Problem BNYINT (5143. Binary Integer)
  970. Problem CRYPTO6 (5144. Cryptography Reloaded (Act I))
  971. Problem DEJAVU (5145. Déjà vu)
  972. Problem CABLEXPR (5146. Experiment on a … Cable)
  973. Problem FCSYS (5147. Fire-Control System)
  974. Problem STCKHOLM (5148. Get-Together at Stockholm)
  975. Problem HISTORY (5149. History of Languages)
  976. Problem JMFILTER (5150. Junk-Mail Filter)
  977. Problem ALICECUB (5151. Alice’s Cube)
  978. Problem BFALG (5152. Brute-force Algorithm EXTREME)
  979. Problem COMPRESS (5153. Compressed String)
  980. Problem CRYPTO7 (5154. Cryptography Reloaded (Act II))
  981. Problem TETRIS2D (5155. Exciting Time)
  982. Problem FLOWERS2 (5156. Flowers Placement)
  983. Problem TRACTOR (5157. Game Simulator)
  984. Problem HEROARR (5158. Heroes Arrangement)
  985. Problem IEXPOLRE (5159. Island Explorer)
  986. Problem O2JAM (5160. Jinyuetuan Puzzle)
  987. Problem FACVSPOW (5161. Factorial vs Power)
  988. Problem VIENTIAN (5163. Tower of Vientiane)
  989. Problem PAIRSORT (5182. Double Sorting)
  990. Problem MONONUM (5196. Monotonous numbers)
  991. Problem DIFFDIAG (5197. Differential Diagnosis)
  992. Problem GARDENAR (5240. Area of a Garden)
  993. Problem REC (5294. Recurrence)
  994. Problem GNYR09F (5295. Adjacent Bit Counts)
  995. Problem COMBAT (5296. Air Combat)
  996. Problem INTERVA2 (5298. Interval Challenge)
  997. Problem MEXICAN (5300. Mexican Standoff)
  998. Problem QUERYSTR (5301. Query Problem)
  999. Problem TETRAVEX (5317. Tetravex Puzzle)
  1000. Problem MINES4 (5373. Four Mines)
  1001. Problem FISHNET (5446. Fishing Net)
  1002. Problem ANARC09A (5449. Seinfeld)
  1003. Problem ANARC09B (5450. Tiles of Tetris, Not!)
  1004. Problem ANARC09C (5451. Not So Flat After All)
  1005. Problem ANARC09D (5452. Hop Do not Walk)
  1006. Problem ANARC09F (5453. Air Strike)
  1007. Problem BIRD (5463. Bird or not bird)
  1008. Problem CT (5464. Counting triangles)
  1009. Problem DP (5465. Deliver pizza)
  1010. Problem EQ (5466. Electronic queue)
  1011. Problem FP (5467. Finding password)
  1012. Problem GS (5468. Going to school)
  1013. Problem HOUSES2 (5469. Houses)
  1014. Problem HSEQ (5511. Heavy Sequences)
  1015. Problem PHU09H (5522. Buy Your House)
  1016. Problem PHU09K (5523. Highway Patrol)
  1017. Problem BSMATH1 (5530. Math with Bases (Easy))
  1018. Problem KUTH (5531. Kutevi Hard)
  1019. Problem SEQUOIA (5541. Sequoiadendron)
  1020. Problem CPAIR (5542. Counting pairs)
  1021. Problem BSMATH2 (5566. Math with Bases)
  1022. Problem KMOVES (5609. Knight Moves)
  1023. Problem ISUN1 (5637. LL and ErBao)
  1024. Problem SERVICEH (5638. Mobile Service Hard)
  1025. Problem NG0FRCTN (5640. Fractions on Tree)
  1026. Problem DTPOLY (5649. Divide Polygon)
  1027. Problem PATULJCI (5652. Snow White and the N dwarfs)
  1028. Problem NG1FRCTN (5673. Fractions on Tree ( reloaded !))
  1029. Problem LASTDIG2 (5699. The last digit re-visited)
  1030. Problem LPRIME (5703. Primes of Lambda)
  1031. Problem KSEQ (5725. 123 Sequence)
  1032. Problem PARADOX (5732. Paradox)
  1033. Problem ALTPERM (5830. Alternating Permutations)
  1034. Problem PERMJUMP (5831. Permutation Jumping)
  1035. Problem ANDROUND (5832. AND Rounds)
  1036. Problem XORROUND (5833. XOR Rounds)
  1037. Problem TROOPS (5885. Troops of Sand Monsters)
  1038. Problem CEOI09TR (5902. Tri)
  1039. Problem SQFFACT (5911. Square-free Integers Factorization)
  1040. Problem LENGFACT (5917. Factorial length)
  1041. Problem FINDMAX (5969. Finding Maximum)
  1042. Problem FINDPRM (5970. Finding Primes)
  1043. Problem LCMSUM (5971. LCM Sum)
  1044. Problem MAXSUMSQ (5972. Maximum Sum Sequences)
  1045. Problem SELTEAM (5973. Selecting Teams)
  1046. Problem TRKNIGHT (5975. Travelling Knight)
  1047. Problem TRGRID (5976. Traversing Grid)
  1048. Problem WEIRDFN (5977. Weird Function)
  1049. Problem FRQPRIME (5978. Frequent Prime Ranges)
  1050. Problem YAPP (5979. Yet Another Permutations Problem)
  1051. Problem MATGAME (5980. Matrix Game)
  1052. Problem DINGRP (6035. Dinner)
  1053. Problem QCJ1 (6041. Mountain Walking)
  1054. Problem QCJ2 (6042. Another Box Problem)
  1055. Problem QCJ3 (6043. The Game)
  1056. Problem QCJ4 (6044. Minimum Diameter Circle)
  1057. Problem PBCGAME (6052. PBCGAME)
  1058. Problem GCDSQF (6059. Another GCD problem)
  1059. Problem SOCOLA (6072. Chocolate)
  1060. Problem BRIDGE (6168. Building Bridges)
  1061. Problem SSEQ (6169. Standing Sequence)
  1062. Problem HOMEC (6170. Homecoming)
  1063. Problem MAJOR (6171. Majority)
  1064. Problem OAE (6172. OAE)
  1065. Problem JANE (6187. Jane and Tarzan)
  1066. Problem EDIST (6219. Edit distance)
  1067. Problem INCPOWK (6221. Increasing Powers of K)
  1068. Problem FERT21_0 (6236. Matches)
  1069. Problem INVCNT (6256. Inversion Count)
  1070. Problem FNRANK (6264. Rank of a Fraction)
  1071. Problem NGM2 (6285. Another Game With Numbers)
  1072. Problem SUMMUL (6286. Sum of products)
  1073. Problem PYRA (6288. Treeramids)
  1074. Problem BOMBER (6289. Bomberman)
  1075. Problem ROBBERY2 (6290. Robbery 2)
  1076. Problem SHMOOGLE (6292. Shmoogle Wave)
  1077. Problem YODANESS (6294. Yodaness Level)
  1078. Problem EXPER (6296. Experiment)
  1079. Problem ROOTCIPH (6297. Decipher)
  1080. Problem MOVMRBL (6299. Move Marbles)
  1081. Problem ARDA1 (6322. The hunt for Gollum)
  1082. Problem NGON (6325. Many polygons)
  1083. Problem ZUMA (6340. ZUMA)
  1084. Problem RPSSL (6356. Rock-Paper-Scissors-Lizard-Spock)
  1085. Problem SAMTWARR (6377. Two Array Problem)
  1086. Problem KKKCT2 (6408. Counting Triangles 2)
  1087. Problem MB1 (6450. PP numbers)
  1088. Problem TDKPRIME (6470. Finding the Kth Prime)
  1089. Problem TDPRIMES (6471. Printing some primes)
  1090. Problem BOWLING1 (6477. Bowling)
  1091. Problem HAMSTER2 (6478. Hamster Flight 2)
  1092. Problem VGCD (6479. The Very Greatest Common Divisor)
  1093. Problem PRIMES2 (6488. Printing some primes (Hard))
  1094. Problem KPRIMES2 (6489. Finding the Kth Prime (Hard))
  1095. Problem BCHOCO (6499. Breaking Chocolates)
  1096. Problem DCOUNT (6500. Counting Diameter)
  1097. Problem TSPAGAIN (6503. Travelling Salesman Again !)
  1098. Problem JOCHEF (6517. Farmer Sepp)
  1099. Problem NDIVPHI (6556. N DIV PHI_N)
  1100. Problem NDIVPHI2 (6560. N DIV PHI_N (Hard))
  1101. Problem PRUBALL (6562. Esferas)
  1102. Problem DIVCON (6576. Divide and Conquer)
  1103. Problem SEGTREE (6578. Segment Tree)
  1104. Problem HCHAINS (6622. Islands and Hotel Chains)
  1105. Problem SNOWGAME (6624. Snowball Game)
  1106. Problem SEQ6 (6650. Consecutive sequence)
  1107. Problem ELCS (6665. Easy Longest Common Substring)
  1108. Problem GCJ101C (6678. Load Testing )
  1109. Problem BOCOMP (6690. A - Comparison Expressions)
  1110. Problem GCJ101BB (6691. Picking Up Chicks)
  1111. Problem BOLESSON (6692. B - Esperanto Lessons)
  1112. Problem BOKO (6693. C - Karaoke)
  1113. Problem BOMARBLE (6694. D - Playing with Marbles)
  1114. Problem BOPERISH (6695. E - Publish of Perish)
  1115. Problem GCJ101AB (6700. Make it Smooth)
  1116. Problem CT101CC (6706. Making Chess Boards)
  1117. Problem MBR (6709. Multiplying by Rotation )
  1118. Problem BLOCK (6711. Transform a Sequence)
  1119. Problem TWOPATHS (6717. Two Paths)
  1120. Problem PFOLD (6720. Paper Fold)
  1121. Problem GOLDG (6726. Goldbach graphs)
  1122. Problem COEF (6731. Coeficientes)
  1123. Problem CT14E (6732. Camels)
  1124. Problem CHEFMAY (6738. Nice Quadrangles)
  1125. Problem SEQFUN (6767. Sequence Function)
  1126. Problem HC (6772. Happy Coins)
  1127. Problem DINONUM (6773. Dinostratus Numbers)
  1128. Problem GSS7 (6779. Can you answer these queries VII)
  1129. Problem ABSURD (6803. Absurd prices)
  1130. Problem CHEATING (6804. Cheating or Not)
  1131. Problem CATTACK (6805. Counter attack)
  1132. Problem CAPCITY (6818. Capital City)
  1133. Problem ASSIGN5 (6819. Yet Another Assignment Problem)
  1134. Problem CFJUN21 (6823. Seller Bob)
  1135. Problem CTFLAG (6824. Flag)
  1136. Problem FPLAN (6825. Field Plan)
  1137. Problem HACKING (6826. Hacking)
  1138. Problem LMCONSTR (6827. Last Minute Construction)
  1139. Problem LINEUP (6828. Lineup)
  1140. Problem POLYNOM (6829. Polynomial)
  1141. Problem SBETS (6830. Soccer Bets)
  1142. Problem TBGAME (6831. Two Ball Game)
  1143. Problem TOSCORE (6832. To Score or not to score)
  1144. Problem CT10R3B (6851. Fence)
  1145. Problem CT16E (6852. Fish)
  1146. Problem ASISTENT (6860. Asistent)
  1147. Problem WONKA1 (6885. Wonkas Oompa-Impa Dilemma)
  1148. Problem PWSUM (6893. Power Sums)
  1149. Problem MEPPERM (6895. Maximum Edge of Powers of Permutation)
  1150. Problem SUB_PROB (6898. Substring Problem)
  1151. Problem RPAR (6906. Raining Parabolas)
  1152. Problem XYYHHTT (6917. Catch Sheep)
  1153. Problem CT23E (6926. Tree game )
  1154. Problem CTOI10D2 (6949. PIN)
  1155. Problem CTOI10D3 (6950. A HUGE TOWER)
  1156. Problem CTOI10D1 (6951. MP3 Player)
  1157. Problem CTOI09_1 (6956. IOI2009 Mecho)
  1158. Problem PARTPAL (6957. Partial Palindrome)
  1159. Problem INDEPCNT (6977. Odd Independent Sets)
  1160. Problem PERMPATT (6978. Check 1324)
  1161. Problem RNDORDER (6981. The Least Number)
  1162. Problem ARRANGE2 (6985. Rearranging Digits)
  1163. Problem SUMSLOPE (6986. Summing Slopes)
  1164. Problem STJEPAN (6988. Beer Machines)
  1165. Problem AVOIDSOS (6999. Avoiding SOS Grids)
  1166. Problem VLATTICE (7001. Visible Lattice Points)
  1167. Problem BUILDING (7002. Buildings)
  1168. Problem ACAB (7010. Police Business)
  1169. Problem CFPARTY (7015. Party)
  1170. Problem ZIGZAG (7019. Zig-Zag rabbit)
  1171. Problem CPATTERN (7022. Cow Patterns)
  1172. Problem KOLACI (7023. Cookies)
  1173. Problem CT25C (7025. Roads in Berland)
  1174. Problem CROBOTS (7034. Crashing Robots)
  1175. Problem CRYPTON (7035. The Embarrassed Cryptographer)
  1176. Problem NECKDEC (7050. Necklace Decomposition)
  1177. Problem ADVEDIST (7099. Advanced Edit Distance)
  1178. Problem BACKTPOL (7100. Back To The Polygon)
  1179. Problem CANDN (7101. Charly And Nito)
  1180. Problem DTWW (7102. Doing The Word Wrap)
  1181. Problem EDDIST (7103. Edit Distance)
  1182. Problem FTHEELF (7104. Feanor The Elf)
  1183. Problem GK (7107. G Key)
  1184. Problem HEPNUM (7108. Heptadecimal Numbers)
  1185. Problem INDIPROG (7109. Indicator of progression)
  1186. Problem HEADSHOT (7132. Headshot)
  1187. Problem IOIGARD (7133. Garden 2005)
  1188. Problem IOIPALIN (7150. Palindrome 2000)
  1189. Problem IOIBOUND (7152. Boundary 2003)
  1190. Problem CF25E (7155. Test)
  1191. Problem EGYPIZZA (7169. Pizza)
  1192. Problem AXIS (7184. Axis of Symmetry)
  1193. Problem BYECAKES (7185. Bye Bye Cakes)
  1194. Problem COUNTPAS (7186. Counting Pascal)
  1195. Problem DINOSM (7187. Dinosaur Menace)
  1196. Problem ESJAIL (7188. Escape from Jail)
  1197. Problem FALTAENV (7189. Falta Envido)
  1198. Problem GUESSTHE (7190. Guess the Number)
  1199. Problem HEXBOARD (7191. Hexagonal Board)
  1200. Problem INTEGMAX (7192. Integral Maximization)
  1201. Problem CURSE (7193. The Pharaoh Curse)
  1202. Problem CAL (7200. Strange Calendar)
  1203. Problem BORW (7208. Black or White)
  1204. Problem CLOSEST (7209. Closest Triplet)
  1205. Problem DRAWM (7210. Draw Mountains)
  1206. Problem ELASTIC (7211. Elastic Bands)
  1207. Problem FINDSR (7212. Find String Roots)
  1208. Problem CLOCKS (7216. The Clocks)
  1209. Problem TRIKA (7217. Training for final)
  1210. Problem GARBAGE (7230. Garbage Collection)
  1211. Problem HOMEW (7231. Homework)
  1212. Problem INVESORT (7232. Inversion Sort)
  1213. Problem IPCELLS (7239. Cells)
  1214. Problem PLYGRND (7240. Playground)
  1215. Problem ROOKS (7248. Chess part1)
  1216. Problem PERFUME (7249. Perfume)
  1217. Problem PBOARD (7250. Blocks for kids)
  1218. Problem SUBLEX (7258. Lexicographical Substring Search)
  1219. Problem LITE (7259. Light Switching)
  1220. Problem NUMGAME (7260. Number Game)
  1221. Problem DIGNUM (7264. Digital LED Number)
  1222. Problem CNTTREE (7296. Trees Again)
  1223. Problem GRIDCOIN (7297. Placing Coins on a Grid)
  1224. Problem MULTQ3 (7299. Multiples of 3)
  1225. Problem LCKYCONT (7301. Lucky Controller)
  1226. Problem CHEFJUN (7322. Prime Pattern)
  1227. Problem CHEFJUL (7323. Happy Days)
  1228. Problem SHUFFLEN (7333. Shuffle Music)
  1229. Problem SHUFFLE1 (7337. Shuffling)
  1230. Problem ITERBIT (7356. Iterated Bitcount Function)
  1231. Problem TREESUM (7363. Tree Sum)
  1232. Problem MCOMP (7378. Manhattan Companies)
  1233. Problem FUNFACT (7380. Factorial challenge)
  1234. Problem ACTIV (7386. Activities)
  1235. Problem PKA (7387. Airplane Parking)
  1236. Problem PKD (7389. Rating Hazard)
  1237. Problem PC8H (7402. Repair Depots)
  1238. Problem MESS (7403. Messy Administration)
  1239. Problem ONTIME (7404. Just on Time)
  1240. Problem PANCAKES (7405. Delicious Pancakes)
  1241. Problem BEENUMS (7406. Beehive Numbers)
  1242. Problem CAMELOT (7408. Camelot)
  1243. Problem DRAWQUAD (7409. Drawing Quadrilaterals)
  1244. Problem ESCJAILA (7422. Escape from Jail Again)
  1245. Problem FILRTEST (7423. File Recover Testing)
  1246. Problem GIRLSNBS (7424. Girls and Boys)
  1247. Problem HACKERS (7425. Hackers)
  1248. Problem IMPUNITS (7426. Imperial Units)
  1249. Problem JARA (7427. Jara’s Legacy)
  1250. Problem RANJAN02 (7430. Tower Of Hanoi - Revisited)
  1251. Problem BIO1 (7486. Rooks)
  1252. Problem FLIB (7487. Flibonakki)
  1253. Problem LGLOVE (7488. LCM GCD Love)
  1254. Problem SBACT (7489. Slow Growing Bacteria)
  1255. Problem BIO (7490. Biology)
  1256. Problem CF33C (7507. Wonderful Randomized Sum)
  1257. Problem HAROWS (7555. A - Crazy Rows)
  1258. Problem HASTOCK (7556. B - Stock Charts)
  1259. Problem HAALPHA (7558. D - Alphabetomials)
  1260. Problem HATEAM (7559. E - Football Team)
  1261. Problem HARANGES (7560. F - Interesting Ranges)
  1262. Problem LEXIPOS (7561. Lexicographic position)
  1263. Problem HLP (7562. Help in organizing)
  1264. Problem HISIX (7563. Hi6)
  1265. Problem IITD1 (7565. Another Sorting Algorithm)
  1266. Problem IITD5 (7566. Expected Cycle Sums)
  1267. Problem IITD4 (7567. Divisor Summation Powered)
  1268. Problem YOKOF (7579. Power Calculus)
  1269. Problem YOKOH (7581. The Best Name for Your Baby)
  1270. Problem YOKOC (7583. Cubic Eight-Puzzle)
  1271. Problem NUMOFPAL (7586. Number of Palindromes)
  1272. Problem MISERMAN (7588. Wise And Miser)
  1273. Problem PC8C (7589. Cave Crisis)
  1274. Problem PC8F (7599. Optimal Strategy for the ICPC)
  1275. Problem MLK (7600. Milk Trading)
  1276. Problem CF36D (7602. New Game with a Chess Piece)
  1277. Problem FIBFACT (7603. Fibonacci Factor)
  1278. Problem DIVISER9 (7623. Divisors VI)
  1279. Problem NE06D (7627. Driving Direction)
  1280. Problem MATHS (7628. Mathematics)
  1281. Problem BPORT (7629. Building Ports)
  1282. Problem SHOPPERS (7630. SHOPPERS)
  1283. Problem ARCHI (7632. Architecture)
  1284. Problem RANJAN05 (7637. Road Map)
  1285. Problem TELECOM (7666. Telecommunications)
  1286. Problem PEBBLE (7668. Pebble Solver)
  1287. Problem CPCRC1C (7676. Sum of Digits)
  1288. Problem ELEC (7680. Electrical Engineering)
  1289. Problem CSQUARE (7683. Powered and Squared)
  1290. Problem FLWRS (7685. Flowers)
  1291. Problem HOMO (7691. Homo or Hetero)
  1292. Problem CHEM (7692. Chemistry)
  1293. Problem ENVIRON (7693. Environmental Engineering)
  1294. Problem CENCRY (7696. Encryption)
  1295. Problem CIVIL (7704. Civil Engineering)
  1296. Problem JZPCIR (7709. Jumping Zippy)
  1297. Problem COMDIV (7718. Number of common divisors)
  1298. Problem HPYNOS (7733. Happy Numbers I)
  1299. Problem BOI7ESC (7737. Escape)
  1300. Problem BOI7SOU (7739. Sound)
  1301. Problem BOI7FEN (7740. Fence)
  1302. Problem BOI7SEQ (7741. Sequence)
  1303. Problem OLOLO (7742. Onotole needs your help)
  1304. Problem HPYNOSII (7753. Happy Numbers II)
  1305. Problem HLPRSRCH (7772. Help a researcher)
  1306. Problem ANARC09I (7776. Kind of a blur)
  1307. Problem ANARC09J (7777. National Treasure)
  1308. Problem ANARC09H (7778. Land Division)
  1309. Problem ANARC09G (7779. Stock Chase)
  1310. Problem LLCA (7782. Largest Labeled Common Ancestor)
  1311. Problem COMFUNC (7783. Commuting Functions)
  1312. Problem DEFKIN (7804. Defense of a Kingdom)
  1313. Problem KITROB (7805. Kitchen Robot)
  1314. Problem LPRISON (7807. The Lucky Prisoner)
  1315. Problem COWPIC (7809. Cow Photographs )
  1316. Problem TREEISO (7826. Tree Isomorphism)
  1317. Problem JZPSTA (7851. Stacks of Zippy)
  1318. Problem ADV04A1 (7857. Tower Game (Hard))
  1319. Problem ADV04B1 (7859. Upper Right King (Hard))
  1320. Problem ADV04C (7860. Deal or No Deal)
  1321. Problem ADV04D (7861. UFO)
  1322. Problem ADV04E (7862. Prisoner of Benda)
  1323. Problem ADV04F1 (7864. Four Chips (Hard))
  1324. Problem ADV04G1 (7866. Regular expressions (Hard))
  1325. Problem ADV04H (7868. Join)
  1326. Problem ADV04J (7870. Invisible point)
  1327. Problem ADV04K (7874. Calculator)
  1328. Problem ADV04L (7875. Miles and kilometers)
  1329. Problem C1LJUTNJ (7881. Ljutnja)
  1330. Problem C1TABOVI (7882. Tabovi)
  1331. Problem C2CRNI (7884. Crni)
  1332. Problem ADV04I1 (7886. Boards (Hard))
  1333. Problem SPFIBO (7891. Fibonacci Sequence)
  1334. Problem SKYLINE (7897. Skyline)
  1335. Problem OSPROB1 (7934. Operating System Problems (Task Scheduling))
  1336. Problem MULPAL (7960. Multiplicative Palindrome)
  1337. Problem ACPC10G (7969. A Knights’ Tale)
  1338. Problem ACPC10H (7970. Jumping Beans)
  1339. Problem ACPC10I (7971. The Cyber Traveling Salesman)
  1340. Problem ACPC10F (7972. World of cubes)
  1341. Problem ACPC10E (7973. Sometimes, a penalty is good!)
  1342. Problem ACPC10A (7974. What’s Next)
  1343. Problem ACPC10D (7975. Tri graphs)
  1344. Problem ACPC10B (7976. Sum the Square)
  1345. Problem FIBOSUM (8001. Fibonacci Sum)
  1346. Problem HORRIBLE (8002. Horrible Queries)
  1347. Problem TTOP (8004. Tree Topology)
  1348. Problem SOCIALNE (8042. Possible Friends)
  1349. Problem IMMERSED (8044. Fantastic Discovery)
  1350. Problem AMR10A (8055. Playground)
  1351. Problem AMR10B (8056. Regex Edit Distance)
  1352. Problem AMR10C (8057. Square Free Factorization)
  1353. Problem AMR10D (8058. Soccer Teams)
  1354. Problem AMR10E (8059. Stocks Prediction)
  1355. Problem AMR10G (8061. Christmas Play)
  1356. Problem AMR10H (8062. Shopping Rush)
  1357. Problem AMR10I (8063. Dividing Stones)
  1358. Problem AMR10J (8064. Mixing Chemicals)
  1359. Problem CIRU (8073. The area of the union of circles)
  1360. Problem NUMG (8074. God of Number Theory)
  1361. Problem SEQN (8075. Sequence)
  1362. Problem JZPGYZ (8093. Sevenk Love Oimaster)
  1363. Problem SPQUEUE (8096. Queue)
  1364. Problem IOIISL08 (8097. Islands)
  1365. Problem TABLE (8099. Crash´s number table)
  1366. Problem SHLIGHTS (8100. Shifting Lights)
  1367. Problem KFRIENDS (8104. Friendly Knights)
  1368. Problem DPMAX (8105. Dot Product Maximization)
  1369. Problem ACPC10C (8106. Normalized Form)
  1370. Problem POLYU (8108. POLYU)
  1371. Problem CIRUT (8119. CIRU2)
  1372. Problem SKY (8129. Sky Lift)
  1373. Problem STREETR (8132. Street Trees)
  1374. Problem CHAIR (8139. Chairs)
  1375. Problem JZPEXT (8177. Beautiful numbers EXTREME)
  1376. Problem BUREAU (8184. Bureaucracy)
  1377. Problem CIRCSCR (8189. Circles On A Screen)
  1378. Problem XMAX (8217. XOR Maximization)
  1379. Problem NSUBSTR (8222. Substrings)
  1380. Problem NFACTOR (8238. N-Factorful)
  1381. Problem EMILABC (8263. Big Pyramid)
  1382. Problem ZEROCNT (8265. Zero Count)
  1383. Problem PSTR (8277. Number of Prime Strings)
  1384. Problem INTCOMB (8281. Combination Of Integers)
  1385. Problem DIST (8282. Distance)
  1386. Problem NONDEC (8283. Non-Decreasing Numbers)
  1387. Problem WEIGHT (8284. Weighted Sum)
  1388. Problem RECTMAT (8285. Rectangles in a Matrix)
  1389. Problem MATCH (8286. Perfect Matching)
  1390. Problem FASTFOOD (8288. Fast Food Restaurant)
  1391. Problem WINGOLD (8316. Win gold medal )
  1392. Problem SIGNGAME (8317. Red Balls)
  1393. Problem PLAYSIGN (8318. color the balls)
  1394. Problem GLJIVE (8319. GLJIVE)
  1395. Problem SCROLL (8320. Spreadsheet scrolling)
  1396. Problem CHOCDIST (8321. Chocolate distribution)
  1397. Problem TRIEQUAL (8323. Triangle equality)
  1398. Problem MILPATR (8324. Military patrol)
  1399. Problem PARTPLNE (8325. Partitioning the plane)
  1400. Problem LEAKCONT (8326. Leaky containers)
  1401. Problem PROGPROG (8327. Progressive progressions)
  1402. Problem MOVEBOOK (8328. Move the books)
  1403. Problem ROADTRIP (8329. Road trip)
  1404. Problem GNTFNTN (8330. Giant fountain)
  1405. Problem SSTRCITS (8331. Sister cities)
  1406. Problem SKISLOPE (8332. Ski slopes)
  1407. Problem PLCNMGME (8333. Place-name game)
  1408. Problem ENUMRTNL (8334. Enumeration of rationals)
  1409. Problem CNTTEAMS (8335. Counting the teams)
  1410. Problem BRODOVI (8349. BRODOVI)
  1411. Problem MIDO (8351. KOSARK)
  1412. Problem CCHESS (8363. COSTLY CHESS)
  1413. Problem PRISMSA (8371. TRIANGULAR PRISM)
  1414. Problem TSUM (8372. Triple Sums)
  1415. Problem PARKET1 (8374. PARKET)
  1416. Problem BALL (8391. The Ball)
  1417. Problem YOUTUBE (8392. Youtube)
  1418. Problem TEMPLEQ (8406. Temple Queues)
  1419. Problem CANDYSTN (8407. Candies and Milestones)
  1420. Problem MNMXPATH (8408. Min Max 01 Path)
  1421. Problem FAVSUBS (8409. Favorite Sub Hair)
  1422. Problem SNAKYNUM (8410. Snaky Numbers)
  1423. Problem SQUA_REV (8418. Revenge of the squares)
  1424. Problem BTCODE_A (8419. Traversing Grid)
  1425. Problem BTCODE_B (8420. Finding Minimum)
  1426. Problem BTCODE_C (8421. Fun With Inequalities)
  1427. Problem BTCODE_D (8422. Maximum Profit)
  1428. Problem BTCODE_E (8423. Recover Polynomials)
  1429. Problem BTCODE_F (8424. Life Game)
  1430. Problem BTCODE_G (8425. Coloring Trees)
  1431. Problem BTCODE_H (8426. Trie Expectation)
  1432. Problem BTCODE_I (8427. Permutation Game)
  1433. Problem BTCODE_J (8428. Grid Tiling)
  1434. Problem BTCODE_K (8429. Array Sorting)
  1435. Problem SQUAREV1 (8433. Revenge of the squares (variation))
  1436. Problem KOLICA (8434. Kolica)
  1437. Problem NOVICE43 (8442. Problem 3)
  1438. Problem PLOT1 (8449. Plotting functions (variation))
  1439. Problem PROBLEM4 (8456. PRIMITIVEROOTS)
  1440. Problem AVDM (8461. Adventure in Moving)
  1441. Problem BARN (8462. Barn Allocation)
  1442. Problem GPA1 (8467. GRADE POINT AVERAGE)
  1443. Problem POCALC1 (8478. Ancient Pocket Calculator)
  1444. Problem PHONMESS (8491. Messy Phone List)
  1445. Problem MAXSUB (8495. Maximum Subset of Array)
  1446. Problem NOSQ (8496. No Squares Numbers)
  1447. Problem NACCI (8505. Nacci Fear)
  1448. Problem PSWITCH (8507. Party Switching)
  1449. Problem POCALC2 (8542. Modern Pocket Calculator)
  1450. Problem MAIN72 (8545. Subset sum)
  1451. Problem MAIN73 (8546. Manoj and Pankaj )
  1452. Problem MAIN74 (8547. Euclids algorithm revisited )
  1453. Problem MAIN75 (8549. BST again)
  1454. Problem LSQF (8550. Longest Square Factor)
  1455. Problem ABCD (8551. Colours A, B, C, D)
  1456. Problem LINQSOLV (8558. Linear Equation Solver)
  1457. Problem FOUROW (8574. Four in a row)
  1458. Problem REVSEQ (8578. Reverse the Sequence)
  1459. Problem NPOWM (8583. Garden)
  1460. Problem PRIME (8586. Factorial factorisation)
  1461. Problem PRIMPERM (8591. Prime Permutations)
  1462. Problem TAILS (8594. Tails all the way )
  1463. Problem WAGE (8596. Wood, Axe and Grass)
  1464. Problem TRAVERSE (8598. Traverse through the board)
  1465. Problem NY10E (8611. Non-Decreasing Digits)
  1466. Problem NY10A (8612. Penney Game)
  1467. Problem NY10B (8624. Nim-B Sum)
  1468. Problem NY10C (8625. Just The Simple Fax)
  1469. Problem NY10D (8626. Show Me The Fax)
  1470. Problem NY10F (8627. I2C)
  1471. Problem NWERC10G (8628. Selling Land)
  1472. Problem NWERC10H (8629. Stock Prices)
  1473. Problem ALIENS1 (8651. Alien arithmetic)
  1474. Problem CHEFFEB (8661. Bogosort)
  1475. Problem CHEFMAR (8663. Squares Game)
  1476. Problem ITRIX_C (8666. Maximum - Profit -- Version II)
  1477. Problem ITRIX_D (8667. Board-Queries)
  1478. Problem ITRIX_E (8668. THE BLACK AND WHITE QUEENS)
  1479. Problem MAXLN (8670. THE MAX LINES)
  1480. Problem GAME2 (8720. Looks like Nim - but it is not)
  1481. Problem CLOPPAIR (8725. Closest Point Pair)
  1482. Problem MAKETREE (8728. Hierarchy)
  1483. Problem BFIT (8732. Best Fit)
  1484. Problem CHARLIE (8734. Charlie and the Chocolate Factory)
  1485. Problem CUBEND (8735. Suffix Of Cube)
  1486. Problem NSUBSTR2 (8747. Substrings II)
  1487. Problem WORD (8750. Wordplay)
  1488. Problem MAIN8_C (8756. Shake Shake Shaky)
  1489. Problem MAIN8_D (8757. Coing tossing )
  1490. Problem MAIN8_E (8758. Cover the string)
  1491. Problem SKIING (8759. Alpine Skiing)
  1492. Problem STRDIST2 (8769. String distance)
  1493. Problem SILVER (8785. Cut the Silver Bar)
  1494. Problem DOMINO1 (8786. The Longest Chain of Domino Tiles)
  1495. Problem DYNALCA (8791. Dynamic LCA)
  1496. Problem SPOINTS (8793. Separate Points)
  1497. Problem SWJAM (8794. Swimming Jam)
  1498. Problem TWENTYQ (8795. Twenty Questions)
  1499. Problem CUBARTWK (8796. Cubist Artwork)
  1500. Problem MRAVOGRA (8816. Mravograd)
  1501. Problem OKRET (8820. Okret)
  1502. Problem SEQ7 (8836. Yet Another Sequence Problem)
  1503. Problem LCDS (8839. Longest Common Difference Subsequence)
  1504. Problem AVARY (8841. Avaricious Maryanna)
  1505. Problem BWORK (8842. Boring Homework)
  1506. Problem COMPLETE (8843. Complete the Set)
  1507. Problem DETECT (8844. Detection of Extraterrestrial)
  1508. Problem TENNIS (8845. Entertainment)
  1509. Problem MAHJONG (8846. Fudan Extracurricular Lives)
  1510. Problem HERBICID (8848. Herbicide)
  1511. Problem IMITATE (8849. Imitation)
  1512. Problem JUICE (8850. Juice Extractor)
  1513. Problem PRATA (8869. Roti Prata)
  1514. Problem GNUM (8886. Guess number!)
  1515. Problem DOUTI (8894. Double Time)
  1516. Problem POCRI (8895. Power Crisis)
  1517. Problem PATT (8896. Pattern Matching)
  1518. Problem PROBOR (8910. Probablistic OR)
  1519. Problem VILLAGES (8916. Villages by the River)
  1520. Problem PLUSEVI (8917. How Many Plusses)
  1521. Problem PAAAARTY (8930. Party!)
  1522. Problem GRIDPNTS (8945. Grid points (speed variation))
  1523. Problem XIXO (8951. brownie)
  1524. Problem THRBL (8952. Catapult that ball)
  1525. Problem KOICOST (8980. Cost)
  1526. Problem KOIREP (8982. Representatives)
  1527. Problem KOILINE (8985. Line up)
  1528. Problem FUPRCO (8989. Funny programming contest)
  1529. Problem GUESSLNK (8991. Number Guessing Game 2)
  1530. Problem SALTOS (8992. A los saltos)
  1531. Problem LQDCANDY (8995. CANDY)
  1532. Problem KITEPRBL (9000. Bob and his new kite factory)
  1533. Problem MAXMATCH (9012. Maximum Self-Matching)
  1534. Problem KVALTWR (9030. Bob and his towers)
  1535. Problem CUBEFR (9032. Cube Free Numbers)
  1536. Problem TOHU (9034. Help Tohu)
  1537. Problem BISHOP2 (9038. Chessboard Billiard)
  1538. Problem TUG (9040. Tug of War)
  1539. Problem HQNP (9042. HQNP Incomputable)
  1540. Problem HANDS (9046. Clock Hands)
  1541. Problem TOHU2 (9050. Tohu again)
  1542. Problem FREQ2 (9055. Most Frequent Value)
  1543. Problem XXXXXXXX (9066. Sum of Distinct Numbers)
  1544. Problem LIGHTIN (9070. Lightning Conductor)
  1545. Problem HABLU (9076. Hablu and Bablu)
  1546. Problem INCEST (9081. Snail family problems)
  1547. Problem JRNTMRS (9084. Journey to Mars)
  1548. Problem JZPFOR (9086. Formula 3D)
  1549. Problem MGCSCLS (9096. Bob and magical scale)
  1550. Problem NOVICE65 (9097. Derangements HARD)
  1551. Problem LCS3 (9098. Long Common Subsequence)
  1552. Problem NOVICE63 (9103. Special Numbers)
  1553. Problem NOVICE62 (9104. Match the words)
  1554. Problem GCPC11A (9117. Faculty Dividing Powers)
  1555. Problem GCPC11B (9118. Genetic Fraud)
  1556. Problem GCPC11C (9119. Indiana Jones and the lost Soccer Cup)
  1557. Problem GCPC11D (9120. Magic Star)
  1558. Problem GCPC11E (9121. Magical Crafting)
  1559. Problem GCPC11F (9122. Diary)
  1560. Problem GCPC11G (9123. Security Zone)
  1561. Problem GCPC11H (9124. Sightseeing)
  1562. Problem GCPC11I (9125. Suiting Weavers)
  1563. Problem GCPC11J (9126. Time to live)
  1564. Problem PYRSUM (9137. Pyramid Sums)
  1565. Problem PYRSUM2 (9138. Pyramid Sums 2)
  1566. Problem LEGRENDS (9161. Legendre symbol)
  1567. Problem TORNJEVI (9185. TORNJEVI)
  1568. Problem TREEMAZE (9190. Perfect Maze)
  1569. Problem SPEED (9199. Circular Track)
  1570. Problem MAFBOI08 (9213. Mafia)
  1571. Problem BHAT007 (9219. Nikhil Problem)
  1572. Problem AHORCADO (9242. B Beware, the end of the world)
  1573. Problem PUBLICAT (9255. Publication)
  1574. Problem PERFECTR (9260. Perfect Road)
  1575. Problem DCD (9331. DCD)
  1576. Problem TETRAHED (9334. Point in tetrahedron)
  1577. Problem ARBITRAG (9340. Arbitrage)
  1578. Problem SFLIP (9367. Segment Flip)
  1579. Problem LANDFILL (9378. Landfill)
  1580. Problem CARNIVAL (9382. Complan Carnival)
  1581. Problem MAIN111 (9385. Strictly not a Prime)
  1582. Problem MAIN112 (9386. Re-Arrange II)
  1583. Problem MAIN113 (9387. Special String)
  1584. Problem PS11A (9392. Play With Sequence)
  1585. Problem GAME31 (9430. The game of 31)
  1586. Problem BUZZW (9433. Buzzwords)
  1587. Problem NEWH (9434. New Horizons)
  1588. Problem ADDMUL (9440. To Add or to Multiply)
  1589. Problem YALOP (9443. Trial of Doom)
  1590. Problem BLOCKDRO (9444. Block Drop)
  1591. Problem CLONES (9445. Attack of the Clones)
  1592. Problem SHORTCIR (9446. Shortest Circuit Evaluation)
  1593. Problem GENETICS (9447. Genetics)
  1594. Problem SWARM (9448. Swarm of Polygons)
  1595. Problem GHOSTS (9458. Ghosts having fun)
  1596. Problem THREETW1 (9459. Connecting three towns (variation))
  1597. Problem ANARC07J (9489. Johny Hates Math)
  1598. Problem ADFRUITS (9493. Advanced Fruits)
  1599. Problem ZSUM (9494. Just Add It)
  1600. Problem WORKB (9503. Working in Beijing)
  1601. Problem PAINTWAL (9504. Paint on a Wall)
  1602. Problem DSUBTREE (9505. Distinct Subtrees)
  1603. Problem DIST2 (9506. Jimmy´s Travel Plan)
  1604. Problem MARIO2 (9507. Mario and Mushrooms)
  1605. Problem AND (9508. Magic Bitwise AND Operation)
  1606. Problem CYLINDES (9509. Shortest Path on a Cylinder)
  1607. Problem ADSPROP (9510. Ads Proposal)
  1608. Problem PUZZLE24 (9511. 24-Puzzle)
  1609. Problem BOMB2 (9512. Bombing)
  1610. Problem TETRISGM (9513. Game)
  1611. Problem HUNT1 (9515. Dwarven Sniper´s Hunting)
  1612. Problem XOREQ (9516. XOR Equations)
  1613. Problem UNLOCK (9517. Unlock the Cellphone)
  1614. Problem LCM (9518. The Time of Day)
  1615. Problem DSUBMTR (9519. Distinct Submatrices)
  1616. Problem TANKS (9520. Tanks)
  1617. Problem CIPHERJ (9525. Cipher)
  1618. Problem DEPARTJ (9527. Department)
  1619. Problem JTRIP (9528. Johns Trip)
  1620. Problem MAYCA (9529. Maya Calendar)
  1621. Problem TRANSJ (9532. Transportation)
  1622. Problem JZPLIT (9534. Turn on the lights)
  1623. Problem JZPLIT2 (9535. Turn on the lights 2)
  1624. Problem DCES (9543. Dynamic Congruence Equation System)
  1625. Problem DPAIR (9547. Counting d-pairs)
  1626. Problem PAIRSUM (9569. Sum of Pairwise Products)
  1627. Problem STRCOUNT (9570. Counting binary strings)
  1628. Problem DYNACON2 (9576. Dynamic Graph Connectivity)
  1629. Problem DYNACON1 (9577. Dynamic Tree Connectivity)
  1630. Problem PRIMEZUK (9587. The Prime conjecture)
  1631. Problem ACANVAS (9636. A Canvas Building)
  1632. Problem BANDW (9637. Black and White)
  1633. Problem CIRCUITS (9638. Circuits)
  1634. Problem EQUI (9640. Equilibrium)
  1635. Problem FBRIDGES (9641. Factory of Bridges)
  1636. Problem GETFAST (9642. Getting There Fast)
  1637. Problem HEISLAZY (9643. He is Lazy)
  1638. Problem IMPER (9644. Imperialism)
  1639. Problem JOCTENIS (9645. Joy of CompuTenis)
  1640. Problem TRIPINV (9650. Mega Inversions)
  1641. Problem ROBOTGRI (9652. Robots on a grid)
  1642. Problem ELEVTRBL (9655. Elevator Trouble)
  1643. Problem ZTC (9685. Zombie’s Treasure Chest)
  1644. Problem YUMMY (9686. Yummy Triangular Pizza)
  1645. Problem XC (9687. Xavier is Learning to Count)
  1646. Problem VBWORK (9689. Very Boring Homework)
  1647. Problem UQAS (9690. Universal Question Answering System)
  1648. Problem TQ (9691. Triangles and Quadrangle)
  1649. Problem CAKE4 (9692. Share the Cakes)
  1650. Problem REVFIB (9693. Revenge of Fibonacci)
  1651. Problem QB (9694. Quelling Blade)
  1652. Problem CODESPTA (9721. 2s Complement)
  1653. Problem CODESPTB (9722. Insertion Sort)
  1654. Problem CODESPTC (9723. Card Shuffling)
  1655. Problem CODESPTD (9725. Queens on a Board)
  1656. Problem HACKRNDM (9734. Hacking the random number generator)
  1657. Problem CODESPTE (9746. Bytelandian Tours)
  1658. Problem CODESPTF (9748. Palindromes)
  1659. Problem CODESPTG (9749. Cliques)
  1660. Problem CODESPTH (9750. Polygon Diagonals)
  1661. Problem CODESPTI (9751. Repairing Roads)
  1662. Problem TUPLEDIV (9753. Tuple Division)
  1663. Problem SCPC11A (9755. Grey Area)
  1664. Problem SCPC11B (9756. Alaska)
  1665. Problem SCPC11F (9759. GO)
  1666. Problem SCPC11G (9760. Indomie)
  1667. Problem SCPC11H (9761. Dolls)
  1668. Problem FACEFRND (9788. Friends of Friends)
  1669. Problem BEHAPPY (9805. Be Awesome As Barney Stinson)
  1670. Problem WPC4C (9817. Shortcut)
  1671. Problem WPC4F (9820. Through the troops)
  1672. Problem MIFF (9832. Matrix inverse)
  1673. Problem GAME3 (9842. Yet Another Fancy Game)
  1674. Problem GLASS (9856. The Glazier)
  1675. Problem EIGHT (9857. Eight Directions Crossword)
  1676. Problem WALK1 (9858. ©tef and Barica)
  1677. Problem GLASS2 (9860. The Glazier 2)
  1678. Problem HOTELS (9861. Hotels Along the Croatian Coast)
  1679. Problem REMOVE (9862. Help the Airline Company)
  1680. Problem NWERC11A (9887. Binomial coefficients)
  1681. Problem NWERC11B (9888. Bird tree)
  1682. Problem NWERC11C (9889. Movie collection)
  1683. Problem NWERC11D (9890. Piece it together)
  1684. Problem NWERC11E (9891. Please, go first)
  1685. Problem NWERC11F (9892. Pool construction)
  1686. Problem NWERC11G (9893. Smoking gun)
  1687. Problem NWERC11H (9894. Tichu)
  1688. Problem NWERC11I (9895. Tracking RFIDs)
  1689. Problem NWERC11J (9896. Train delays)
  1690. Problem PONY1 (9916. Help Dr Whooves)
  1691. Problem ABCPATH (9921. ABC Path)
  1692. Problem ALICE (9934. Alice and Bob)
  1693. Problem BC (9935. Break the Chocolate)
  1694. Problem CGW (9936. Construct the Great Wall)
  1695. Problem DISNEY (9938. Disney Fastpass)
  1696. Problem EC (9939. Eliminate the Conflict)
  1697. Problem FNINJA (9940. Fruit Ninja)
  1698. Problem GRE (9941. GRE Words)
  1699. Problem HOLI (9942. Holiday Accommodation)
  1700. Problem ISAB (9943. Isabella Message)
  1701. Problem JITU (9944. Ji-Tu Problem)
  1702. Problem WILLITST (9948. Will it ever stop)
  1703. Problem IQTEAM (9950. IQ Team)
  1704. Problem GUANGGUN (9952. 111…1 Squared)
  1705. Problem PIBO (9964. Fibonacci vs Polynomial)
  1706. Problem PWORDS (9967. Playing with Words)
  1707. Problem MCLB (9968. Magic Crystals and Laser Beams)
  1708. Problem RDNWK (9969. Road Network)
  1709. Problem EGYPAR (9970. The Egyptian Parliament)
  1710. Problem ACHESS (9971. Adventurous Chess Masters)
  1711. Problem SKEY (9972. The SKey)
  1712. Problem PROSCORE (9973. Problem Set Score)
  1713. Problem MENMARS (9974. Men From Mars)
  1714. Problem FSEQ (9975. No Stories Any More!)
  1715. Problem DISTX (9985. Distance)
  1716. Problem POWTOW (10050. Power Tower City)
  1717. Problem KOMPICI (10069. Kompiæi)
  1718. Problem TRICKTRT (10070. Trick or Treat)
  1719. Problem RESTAURN (10071. Working at the Restaurant)
  1720. Problem LIGHTS2 (10072. Lights)
  1721. Problem DARTS (10073. Darts)
  1722. Problem GENETIC2 (10074. Genetics)
  1723. Problem GRAVEYRD (10075. Haunted Graveyard)
  1724. Problem SLALOM2 (10076. Slalom)
  1725. Problem ROUTING (10077. Routing)
  1726. Problem HAPPYTL (10078. Happy Telephones)
  1727. Problem STAMMER (10079. Stammering Aliens)
  1728. Problem LAWNMWR (10080. Lawn Mower)
  1729. Problem PERIODIC (10081. Periodic Points)
  1730. Problem CMPANS (10082. Comparing Answers)
  1731. Problem FAKESCOR (10084. Fake Scoreboard)
  1732. Problem PALINDNA (10085. Palindromic DNA)
  1733. Problem JMPMNKEY (10086. Jumping Monkey)
  1734. Problem SENSORNT (10087. Sensor Network)
  1735. Problem ASSEMBLY (10088. Assembly Line)
  1736. Problem LOCKKEY (10089. Locks and Keys)
  1737. Problem DICE (10091. Three-sided Dice)
  1738. Problem PRTYNGHT (10092. Party Night)
  1739. Problem CAPPIZZA (10095. Caper Pizza)
  1740. Problem LIGHTS3 (10096. Lights (Extreme))
  1741. Problem ALPHSOUP (10105. Alphabet Soup)
  1742. Problem COIN (10106. Coin Collecting)
  1743. Problem DONUT (10107. Cybercrime Donut Investigation)
  1744. Problem BALLOT (10108. Distributing Ballot Boxes)
  1745. Problem GSM (10109. Game, Set and Match)
  1746. Problem GUESSNM2 (10110. Guess the Numbers)
  1747. Problem PARSUMS (10111. Nonnegative Partial Sums)
  1748. Problem REVIEW (10112. Peer Review)
  1749. Problem REGPOLYG (10113. Regular Convex Polygon)
  1750. Problem RMTLAND (10114. Remoteland)
  1751. Problem TANDV (10128. Treasures and Vikings)
  1752. Problem STRAZA (10141. STRAZA)
  1753. Problem BCAKE (10145. Birthday Cake)
  1754. Problem PUCMM025 (10186. Divisor Digits)
  1755. Problem TRANSFER (10210. After Party Transfers)
  1756. Problem AMR11A (10228. Magic Grid)
  1757. Problem AMR11B (10229. Save the Students)
  1758. Problem AMR11C (10230. Robbing Gringotts)
  1759. Problem AMR11D (10231. Wizarding Duel)
  1760. Problem AMR11E (10232. Distinct Primes)
  1761. Problem AMR11F (10233. Magical Bridges)
  1762. Problem AMR11H (10235. Array Diversity)
  1763. Problem AMR11I (10236. Generations)
  1764. Problem AMR11J (10237. Goblin Wars)
  1765. Problem ACPC11B (10239. Between the Mountains)
  1766. Problem ACPC11C (10240. Circleland)
  1767. Problem ACPC11D (10242. Dice on a Board)
  1768. Problem METEORS (10264. Meteors)
  1769. Problem DIVIDEKR (10265. Subdivision of the kingdom)
  1770. Problem TEMPERAT (10270. Temperature)
  1771. Problem ALLIZWEL (10283. ALL IZZ WELL)
  1772. Problem WTK (10285. Why this kolaveri di)
  1773. Problem DOTAA (10286. DOTA HEROES)
  1774. Problem SHELL (10292. Shell game)
  1775. Problem FANCY (10293. FANCY NUMBERS)
  1776. Problem JUMPY (10301. A jumpy cycle)
  1777. Problem CONCAVE (10312. Concave quadrilaterals)
  1778. Problem TWOKINGS (10328. TRIVIADOR)
  1779. Problem SOLDIERS (10334. SOLDIERS)
  1780. Problem DISTO (10346. Streets of distortion)
  1781. Problem CTSTRING (10354. Count Strings)
  1782. Problem COINTOSS (10355. Coin Tosses)
  1783. Problem CODEIT03 (10366. Play with Dates)
  1784. Problem ABA12B (10376. String Factorization!)
  1785. Problem MECGROUP (10377. project groups)
  1786. Problem CAM5 (10380. prayatna PR)
  1787. Problem DICT (10381. Search in the dictionary!)
  1788. Problem ABA12C (10394. Buying Apples!)
  1789. Problem ABA12D (10395. Sum of divisors!)
  1790. Problem CONGA (10399. Conga line)
  1791. Problem ALIEN (10401. Aliens at the train)
  1792. Problem ABA12E (10405. Shooting the balloons!)
  1793. Problem DRACULA (10415. Dracula)
  1794. Problem VHELSING (10416. Van Helsings gun)
  1795. Problem POLISH (10419. Polish Language)
  1796. Problem IOPC1200 (10420. Hardware upgrade)
  1797. Problem SNIPE (10421. Run, Snipe, Run)
  1798. Problem IOPC1201 (10422. Rubiks cube)
  1799. Problem TOPOLAND (10424. To Poland)
  1800. Problem SECSYS (10425. Security System)
  1801. Problem IOPC1202 (10437. Quadrilaterals)
  1802. Problem IOPC1203 (10438. Crazy texting)
  1803. Problem WALKROBO (10439. Walking Robot)
  1804. Problem FRNDS (10440. Friends)
  1805. Problem CADYDIST (10442. Candy Distribution)
  1806. Problem BRDGS (10443. Bridges)
  1807. Problem CODING2 (10444. Coding)
  1808. Problem SICRANO (10446. Sicrano)
  1809. Problem CONTCITY (10447. Contaminated City)
  1810. Problem RESOURCE (10449. Resource Management)
  1811. Problem AMOEBA (10450. Amoeba)
  1812. Problem STUN (10451. Stun Boosting)
  1813. Problem CAPRICA (10452. Caprica Cities)
  1814. Problem SPRING (10453. Spring Loaded)
  1815. Problem GREENLAN (10454. Greens Land)
  1816. Problem IOPC1204 (10460. A function over factors)
  1817. Problem IOPC1205 (10461. The magical escape)
  1818. Problem PAREN (10463. COUNT PAREN)
  1819. Problem RE1 (10464. Reverse Engineering)
  1820. Problem OTOY1 (10465. One Theorem, One Year)
  1821. Problem EALP1 (10466. Enough of analyzing, let’s play)
  1822. Problem ALIEN2 (10471. Aliens at the train, again!)
  1823. Problem IOPC1206 (10476. Fair bases)
  1824. Problem IOPC1207 (10477. GM plants)
  1825. Problem HAYBALE (10500. Haybale stacking)
  1826. Problem VIDEO (10502. Video game combos)
  1827. Problem PRENDON (10506. Prendonians)
  1828. Problem CHEESE (10507. Cheese-rolling World Cup)
  1829. Problem BTTNS (10508. Buttons)
  1830. Problem CRDS (10509. Cards)
  1831. Problem SRTMACH (10510. Sorting Machine)
  1832. Problem KOPC12A (10514. K12 - Building Construction)
  1833. Problem KOPC12B (10515. K12-Combinations)
  1834. Problem KOPC12D (10517. K12-Generating Big Numbers II)
  1835. Problem KOPC12G (10519. K12-Bored of Suffixes and Prefixes)
  1836. Problem KOPC12H (10522. K12-OE Numbers)
  1837. Problem EDIT (10537. Edit Distance Again)
  1838. Problem DERP (10538. Derp)
  1839. Problem BUNNIES (10539. Bunnies)
  1840. Problem DELIVER (10547. Delivery Route)
  1841. Problem MINI (10557. MINI IN DANGER!!!)
  1842. Problem ALICESIE (10565. Alice Sieve)
  1843. Problem GRAPHCUT (10568. Graph Cut)
  1844. Problem LONGCS (10570. Longest Common Substring)
  1845. Problem SOCCERCH (10571. Soccer Challenge)
  1846. Problem CHEATCON (10572. Cheating on the contest)
  1847. Problem OFFSTRAT (10573. Problem Offensive Strategy)
  1848. Problem SCCCER (10574. Soccer Ceremony)
  1849. Problem YELBRICK (10575. The Yellow Brick Road)
  1850. Problem EXCLSEC (10576. Exclusive Security)
  1851. Problem DESRUG (10579. Desrugenstein)
  1852. Problem BALLSAG (10581. Ball Stacking Again)
  1853. Problem ARRAYSUB (10582. subarrays)
  1854. Problem SEAGOD (10585. Searching God)
  1855. Problem PROBMOR (10586. Problems in Moria)
  1856. Problem ENEM (10587. Enemies)
  1857. Problem PORTALUN (10588. Portal)
  1858. Problem KING (10589. King)
  1859. Problem PONY2 (10594. Decoding Number Stations with Dr Whooves)
  1860. Problem MON2012 (10596. Monkey and apples)
  1861. Problem FORMAT1 (10605. Counting Formations)
  1862. Problem BALNUM (10606. Balanced Numbers)
  1863. Problem TWODEL (10607. Delivery)
  1864. Problem UNICA (10608. Unique Strings)
  1865. Problem RRANGE (10611. Ranges)
  1866. Problem FUNAREA (10612. Funny Areas)
  1867. Problem KNJIGE (10620. KNJIGE)
  1868. Problem MONO (10621. MONO)
  1869. Problem DIFERENC (10622. DIFERENCIJA)
  1870. Problem ZNANSTVE (10623. ZNANSTVENIK)
  1871. Problem COT (10628. Count on a tree)
  1872. Problem MYQ1 (10639. The Blind Passenger)
  1873. Problem MYQ2 (10640. The Wild Wizard)
  1874. Problem MYQ3 (10641. The Dating Dress Problem)
  1875. Problem MYQ5 (10643. The Nerd Factor)
  1876. Problem MYQ6 (10644. Serve The Street)
  1877. Problem MYQ7 (10645. The Rail Network Renovation)
  1878. Problem MYQ8 (10646. The National Game)
  1879. Problem MYQ9 (10647. Divide And Conquer)
  1880. Problem DUGDUG (10648. DUGDUG)
  1881. Problem MYQ10 (10649. Mirror Number)
  1882. Problem FLLM (10667. PASIJANS)
  1883. Problem IWGBST (10675. GENIJALAC)
  1884. Problem IWGBS (10676. 0110SS)
  1885. Problem NAGAY (10677. Joseph’s Problem)
  1886. Problem BYTESB (10683. DRIVE)
  1887. Problem SYM12 (10699. Symmetry)
  1888. Problem MYQ11 (10701. The Lazy Gamer)
  1889. Problem MYQ12 (10704. The Great Escape)
  1890. Problem COT2 (10707. Count on a tree II)
  1891. Problem NAGAY1 (10711. VUK)
  1892. Problem TRIGALGE (10712. Easy Calculation)
  1893. Problem STRSEQ (10725. String Subsequence)
  1894. Problem CHAMPS (10730. Michel and the championship)
  1895. Problem TRAPEZBO (10732. Trapezoid)
  1896. Problem RAONE (10738. Ra-One Numbers)
  1897. Problem GONE (10790. G-One Numbers)
  1898. Problem WACHOVIA (10798. Wachovia Bank)
  1899. Problem RS2D (10799. Happiness at the lowest cost)
  1900. Problem GAMECG (10800. GAME)
  1901. Problem TETRAHRD (10802. Sum of Tetranacci numbers)
  1902. Problem DCEPC204 (10809. Unlock it !)
  1903. Problem DCEPC206 (10810. Its a Murder!)
  1904. Problem DCEPC202 (10814. Unique Paths)
  1905. Problem DCEPC207 (10815. Finally a Treat)
  1906. Problem FACTCG2 (10818. Medium Factorization)
  1907. Problem BFTAB (10819. BF Vector)
  1908. Problem DCEPC203 (10820. Obsession)
  1909. Problem DCEPC200 (10822. The Prime Minister)
  1910. Problem CONINT (10833. Counter-intelligence)
  1911. Problem SUPSUP (10841. Supplying the Suppliers)
  1912. Problem DECOY (10877. Decoys and Diversions)
  1913. Problem CUSTOMSL (10883. Customs)
  1914. Problem FERT21_1 (10919. I Hate Parenthesis)
  1915. Problem DIXDOOM (10930. Dixon Dominoes)
  1916. Problem DCEPC301 (10945. Foodie Golu)
  1917. Problem VERODOOM (10958. Vero Dominoes)
  1918. Problem AGS (10966. Aritho-geometric Series (AGS))
  1919. Problem LUCIFER (10968. LUCIFER Number)
  1920. Problem ITRIX12E (11050. R Numbers)
  1921. Problem PONY3 (11054. Discords Dilemma )
  1922. Problem AP2 (11063. AP - Complete The Series (Easy))
  1923. Problem AP3 (11066. AP - Complete The Series v2)
  1924. Problem BANNER (11090. Large banner)
  1925. Problem MAIN12A (11102. SelfDescribingSequenceProblem)
  1926. Problem MAIN12B (11103. PrimeFactorofLCM)
  1927. Problem MAIN12C (11105. Email ID)
  1928. Problem PONY4 (11116. Discord is Cornered)
  1929. Problem RESTACK (11117. Restacking haybales 2012)
  1930. Problem GREAT_E (11157. The Great Escape)
  1931. Problem STRAWB (11165. Magic Strawberries)
  1932. Problem IEEEBGAM (11175. The Ball Game)
  1933. Problem MONEYYTU (11178. Save money for YTU)
  1934. Problem SPWORLD (11179. Korra in the Spirit World)
  1935. Problem NUMTSN (11180. 369 Numbers)
  1936. Problem BUILDTOW (11181. Build the Tower)
  1937. Problem IPAD (11198. Ipad Testing)
  1938. Problem NUMTRY (11202. Number Theory)
  1939. Problem GP1 (11244. GP - Complete the Series v1 ())
  1940. Problem KL11B (11267. Arnook Defensive Line)
  1941. Problem TEAMNIM (11273. Team Nim)
  1942. Problem LIGHTPZ (11274. Lights and Switches)
  1943. Problem ADVNTURE (11276. Adventure)
  1944. Problem NUMPLAY (11300. Fun with numbers)
  1945. Problem GONESORT (11321. G-One Sort)
  1946. Problem ARTHEVAL (11326. Arithmetic Evaluation)
  1947. Problem LUCISORT (11334. Lucifer Sort)
  1948. Problem ADDLCM (11345. lcm addition)
  1949. Problem TSHOW1 (11354. Amusing numbers)
  1950. Problem SQ2SQ (11355. SQUARE TO SQUARE)
  1951. Problem RPLA (11371. Answer the boss!)
  1952. Problem RPLB (11372. Blueberries)
  1953. Problem RPLC (11373. Coke madness)
  1954. Problem RPLD (11374. Database)
  1955. Problem RPLE (11375. Espionage)
  1956. Problem FAST2 (11383. Fast Sum of two to an exponent)
  1957. Problem ZOOMOP2 (11384. Zoom Operation)
  1958. Problem GCJ2012C (11386. Recycled Numbers)
  1959. Problem EASYMATH (11391. EASY MATH)
  1960. Problem DCEPC505 (11401. Bazinga!)
  1961. Problem DCEPC504 (11402. The Indian Connection)
  1962. Problem DCEPC501 (11404. Save Thy Toys)
  1963. Problem DCEPC502 (11405. Just Like the Good Old Days)
  1964. Problem TDOWN (11407. Tied Down)
  1965. Problem FIBTWIST (11409. Fibonacci With a Twist)
  1966. Problem COT3 (11414. Combat on a tree)
  1967. Problem DCEPC604 (11440. Unlock it ! Part 2)
  1968. Problem DAVIDG (11443. Davids Greed)
  1969. Problem MAXOR (11444. MAXOR)
  1970. Problem VUDBOL5 (11458. Ninja)
  1971. Problem VUDBOL7 (11460. Planning Poker)
  1972. Problem SHELF (11461. Book Shelves)
  1973. Problem SUBSET (11469. Balanced Cow Subsets)
  1974. Problem TTM (11470. To the moon)
  1975. Problem DCEPC701 (11472. Amazing Maze)
  1976. Problem DCEPC702 (11473. NOS)
  1977. Problem DCEPC703 (11474. Totient Game)
  1978. Problem DCEPC705 (11476. Weird Points)
  1979. Problem DCEPC706 (11477. Meeting For Party)
  1980. Problem COT4 (11482. Count on a trie)
  1981. Problem RPLG (11493. Goto & labels)
  1982. Problem RPLH (11494. Hard Launching)
  1983. Problem RPLI (11495. Ignore the bounds)
  1984. Problem RPLJ (11496. Just the distance)
  1985. Problem IPL1 (11509. IPL - CRICKET TOURNAMENT)
  1986. Problem BUSYMAN (11515. I AM VERY BUSY)
  1987. Problem MAKEMAZE (11516. VALIDATE THE MAZE)
  1988. Problem GAMARENA (11517. GAMING ARENA)
  1989. Problem DOMINST (11521. Dominant Strings)
  1990. Problem TRAIN07 (11540. Training)
  1991. Problem PUCMM210 (11560. A Summatory)
  1992. Problem PUCMM215 (11564. E 23 Stairs pattern)
  1993. Problem TEAM2 (11573. A Famous ICPC Team)
  1994. Problem STONE2 (11574. A Famous Stone Collector)
  1995. Problem EQ2 (11575. A Famous Equation)
  1996. Problem TRIP2 (11576. A Famous King’s Trip)
  1997. Problem MEDIAN3 (11577. The Famous ICPC Team Again)
  1998. Problem CITY2 (11578. A Famous City)
  1999. Problem COMPANYS (11579. Two Famous Companies)
  2000. Problem PRLGAME2 (11580. A Famous Game)
  2001. Problem SPIRALGR (11582. A Famous Grid)
  2002. Problem DOJO (11601. With a Pit of Death)
  2003. Problem POLTOPOL (11603. Polynomial f(x) to Polynomial h(x))
  2004. Problem REBOUND (11604. The return of the Cake)
  2005. Problem AHOCUR (11613. Aho-Corasick Trie)
  2006. Problem MAKESUM (11642. MAKESUM)
  2007. Problem CPAIR2 (11676. Counting diff-pairs)
  2008. Problem ASUMHARD (11695. A Summatory (HARD))
  2009. Problem WRONG (11707. Wrong directions)
  2010. Problem REDCROSS (11712. Red Cross Hospital)
  2011. Problem ROIM (11718. Boa viagem, Roim)
  2012. Problem COMPLEX2 (11723. HELP ABHISHEK(version-II))
  2013. Problem ASTERRAN (11726. Asteriod Rangers)
  2014. Problem PTIME (11736. Prime Time)
  2015. Problem PONY5 (11756. Teaming up for the competition)
  2016. Problem RPLK (11769. Kind and gently)
  2017. Problem RPLL (11770. Lifesavers)
  2018. Problem RPLM (11771. Mountain Cave)
  2019. Problem RPLN (11772. Negative Score)
  2020. Problem SEQAGAIN (11777. Easy Sequence!)
  2021. Problem ALIEN3 (11789. Aliens at the subway)
  2022. Problem MAX2214 (11808. Max 2214)
  2023. Problem CNTPATHS (11813. Count weighted paths)
  2024. Problem EKO (11814. Eko)
  2025. Problem DOJ1 (11830. DOJO Corridor I)
  2026. Problem DOJ2 (11834. DOJO Corridor II)
  2027. Problem SEGSQRSS (11840. Sum of Squares with Segment Tree)
  2028. Problem BSPRIME (11844. Binary Sequence of Prime Number)
  2029. Problem POWPOW (11848. Power with Combinatorics)
  2030. Problem POWPOW2 (11851. Power with Combinatorics(HARD))
  2031. Problem POSAO (11875. Jobs)
  2032. Problem BFTRI (11885. Drawing Triangles with Brainf##k)
  2033. Problem DONALDO (11895. DONALDO)
  2034. Problem PK11F (11900. Spelling Suggestion)
  2035. Problem FLATAND (11904. A Classic Myth - Flatland Superhero)
  2036. Problem TRECOUNT (11905. Tree Count)
  2037. Problem ROT (11906. Rescue On Time)
  2038. Problem PUCMM223 (11909. C You and Me)
  2039. Problem BALLLSTA (11921. Ball Stack)
  2040. Problem AMZSEQ (11931. AMZ Word)
  2041. Problem AMZRCK (11932. Amz Rock)
  2042. Problem DIG (11933. DIAGONAL)
  2043. Problem DEC123 (11935. Decorating the Palace)
  2044. Problem ZZPERM2 (11946. Zig-Zag Permutation 2)
  2045. Problem GSWORDS (11947. Counting Words)
  2046. Problem DARKASLT (11948. Dark Assault)
  2047. Problem IGALAXY (11952. Intergalactic Highways)
  2048. Problem TLL237 (11956. Addicted)
  2049. Problem MNNITAR (11962. Arya Rage)
  2050. Problem PACKRECT (11963. Packing Rectangles)
  2051. Problem DOMECIR (11984. Dome of Circus)
  2052. Problem GOT (11985. Gao on a tree)
  2053. Problem ROMAN008 (11986. ROMAN NUMERALS)
  2054. Problem DCEPC803 (11997. Trip To London)
  2055. Problem DCEPC804 (11998. Totient Fever)
  2056. Problem DCEPC807 (12001. Bit by Bit)
  2057. Problem DCEPC810 (12004. Cousin Wars)
  2058. Problem GRASSPLA (12005. Grass Planting)
  2059. Problem FRS2 (12007. Fibonaccibonacci (easy))
  2060. Problem FRSKT (12008. Fibonacci recursive sequences (medium))
  2061. Problem FRSKH (12009. Fibonacci recursive sequences (hard))
  2062. Problem MTHUR (12012. grace marks)
  2063. Problem BLACKOUT (12030. Blackout)
  2064. Problem LCS0 (12076. Longest Common Subsequence)
  2065. Problem ALLBARN2 (12107. All Possible Barns)
  2066. Problem LINEGAR (12108. Linear Garden)
  2067. Problem FIBOSQRT (12125. Fibonacci With a Square Root)
  2068. Problem JNEXT (12150. Just Next !!!)
  2069. Problem OPCPIZZA (12151. Pizzamania)
  2070. Problem KFSTB (12183. Help the Commander in Chief)
  2071. Problem MORENA (12209. Morenas Candy Shop ( Easy ))
  2072. Problem HILO (12210. High and Low)
  2073. Problem CLOUDMG (12236. Cloud Computing)
  2074. Problem HS12MULT (12240. Multinomial numbers)
  2075. Problem HS12PRIM (12241. Classification from Erdõs and Selfridge)
  2076. Problem ROULETTD (12243. Natalia Spins The Roulette)
  2077. Problem NATALIAS (12244. Natalia Has Another Problem)
  2078. Problem NATALIAG (12245. Natalia Plays a Game)
  2079. Problem SPIDY (12249. Spiderman vs Sandman)
  2080. Problem BUZZOFF (12250. Buzz Trouble)
  2081. Problem MADHULK (12251. Mad Hulk)
  2082. Problem HARSHAD (12260. Devlali Numbers)
  2083. Problem MSUBSTR (12262. Mirror Strings !!!)
  2084. Problem OPCTRIP (12277. The Trip)
  2085. Problem INVPHI (12295. Smallest Inverse Euler Totient Function)
  2086. Problem INVDIV (12304. Smallest Inverse Sum of Divisors)
  2087. Problem NITT1 (12318. My Reaction when there is no internet connection)
  2088. Problem NITT2 (12319. hai jolly jolly jolly)
  2089. Problem NSQUARE (12321. NSquare Sum ( Easy ))
  2090. Problem NSQUARE2 (12322. NSquare Sum ( Medium ))
  2091. Problem NAKANJ (12323. Minimum Knight moves !!!)
  2092. Problem NITT4 (12324. Tiles)
  2093. Problem NITT8 (12326. Dating Rishi)
  2094. Problem HNUMBERS (12352. HNumbers)
  2095. Problem SUBSHARD (12357. Subset and upset (HARD))
  2096. Problem RANDG (12363. Red And Green)
  2097. Problem TAP2012A (12364. Awari 2)
  2098. Problem TAP2012B (12365. Ball of Reconciliation)
  2099. Problem TAP2012C (12366. Cantor)
  2100. Problem TAP2012D (12367. Designing T-Shirts)
  2101. Problem TAP2012E (12368. Emma s Domino)
  2102. Problem TAP2012F (12369. Fixture)
  2103. Problem TAP2012G (12370. Generating Alien DNA)
  2104. Problem TAP2012H (12371. High Mountains)
  2105. Problem LCPC12B (12397. Johnny plays with connect 4)
  2106. Problem LCPC12C (12398. Johnny Listens to Music)
  2107. Problem LCPC12D (12399. Johnny Hates Climbing)
  2108. Problem LCPC12E (12400. Johnnys Empire)
  2109. Problem LCPC12F (12407. Johnny The Gambler)
  2110. Problem LCPC12G (12408. Johnny Studies Genetics)
  2111. Problem LCPC12H (12409. Johnny at school)
  2112. Problem PONY6 (12413. Toward Infinity)
  2113. Problem KSELECT (12421. Chocolate Distribution)
  2114. Problem THEPOOL (12436. The One-Dimensional Pool Table)
  2115. Problem JUNL (12446. BHAAD MEI JAAO)
  2116. Problem GAMES (12448. HOW MANY GAMES)
  2117. Problem BOGGLE (12462. Boggle Scoring)
  2118. Problem DIEHARD (12471. DIE HARD)
  2119. Problem MAXWOODS (12474. MAXIMUM WOOD CUTTER)
  2120. Problem CDC12_A (12556. Another Traffic Problem)
  2121. Problem CDC12_B (12557. Basic Routines)
  2122. Problem CDC12_C (12558. Collision Issue)
  2123. Problem CDC12_D (12559. Drastic Race)
  2124. Problem CDC12_E (12560. External Falling Objects)
  2125. Problem CDC12_F (12561. Forbidden Machine)
  2126. Problem CDC12_G (12562. Glory War)
  2127. Problem CDC12_H (12563. Halt The War)
  2128. Problem SID (12579. Search Insert Delete)
  2129. Problem CAMPANA1 (12587. CAMPANADAS 1)
  2130. Problem BMASTER (12600. Blade Master)
  2131. Problem DIFFV (12609. Different Vectors )
  2132. Problem RIOI_2_3 (12612. Path of the righteous man)
  2133. Problem FISHES (12651. Finding Fishes)
  2134. Problem LCPC11B (12660. Co-Prime)
  2135. Problem STRSOCU (12713. Strings)
  2136. Problem FATAWY (12714. Fatawy)
  2137. Problem PELL2 (12721. Pell (Mid pelling))
  2138. Problem QN01 (12726. XOR Game)
  2139. Problem QN02 (12734. Seating Arrangement)
  2140. Problem CRCLE_UI (12746. Colorful Circle (EASY))
  2141. Problem DAP (12749. Dynamic Assignment Problem)
  2142. Problem SPP2 (12807. Recursive Sequence (Version X))
  2143. Problem MATHII (12809. Yet Another Mathematical Problem)
  2144. Problem MULTII (12810. Yet Another Multiple Problem)
  2145. Problem PBBN2 (12824. Print Big Binary Numbers)
  2146. Problem TPORT (12855. Teleport)
  2147. Problem NTICKETS (12866. Nlogonian Tickets)
  2148. Problem KOZE (12880. Sheep)
  2149. Problem DCEPCA02 (12887. Ant Colony Optimization)
  2150. Problem DCEPCA10 (12889. MAD)
  2151. Problem DCEPCA04 (12893. Short Select)
  2152. Problem DCEPCA01 (12902. Good Luck )
  2153. Problem DCEPCA08 (12903. Saving BOB - 2)
  2154. Problem BNMT (12908. Binary Matrix)
  2155. Problem DCEPCA06 (12912. Saving BOB)
  2156. Problem DCEPCA03 (12914. Totient Extreme)
  2157. Problem DCEPCA09 (12916. MMM)
  2158. Problem NDIV (12933. n-divisors)
  2159. Problem RIOI_3_2 (12943. Counting)
  2160. Problem VPL0_A (12958. Another Gift Problem)
  2161. Problem VPL0_B (12959. Basic Grapes Instinct)
  2162. Problem VPL0_C (12960. Collision on Christmas Eve)
  2163. Problem VPL0_D (12961. Drastic Grapes)
  2164. Problem BUZZ (12969. To inifinity and Beyond)
  2165. Problem SGAME (12978. SHAPE GAME)
  2166. Problem CEOI08A (12981. Fences)
  2167. Problem PFORLOOP (13002. For Loops Challenge)
  2168. Problem EPTT (13007. Easy Programming Tutorials)
  2169. Problem CNTPRIME (13015. Counting Primes )
  2170. Problem BEANGAME (13020. Help MR BEAN)
  2171. Problem VISION (13031. Vision Field)
  2172. Problem AMR12A (13041. The Black Riders)
  2173. Problem AMR12B (13042. Gandalf vs the Balrog)
  2174. Problem AMR12D (13043. The Mirror of Galadriel)
  2175. Problem AMR12E (13044. Dyslexic Gollum)
  2176. Problem AMR12F (13045. Denethors Decryption of Dequeue permutations)
  2177. Problem AMR12G (13046. The Glittering Caves of Aglarond)
  2178. Problem AMR12I (13047. Saruman of Many Colours)
  2179. Problem AMR12J (13048. Escape from the Mines)
  2180. Problem AMR12K (13049. The Loyalty of the Orcs)
  2181. Problem AMR12C (13050. Entmoot)
  2182. Problem AMR12H (13051. Wormtongues Mind)
  2183. Problem IZHONYT (13055. New Year Train)
  2184. Problem CSLIKAR (13076. Slikar)
  2185. Problem MADN (13078. The Mad Numerologist)
  2186. Problem PCPC12D (13090. New Strategy )
  2187. Problem PCPC12E (13091. Snakes and Ladders)
  2188. Problem PCPC12F (13092. Snakes and Ladders Again)
  2189. Problem PCPC12G (13093. Mosque)
  2190. Problem PCPC12H (13094. Beggars)
  2191. Problem PCPC12I (13095. peaks)
  2192. Problem PCPC12J (13096. Amr Samir)
  2193. Problem CONIC (13098. Yet Another Conic Section Problem)
  2194. Problem MUTDNA (13105. DNA)
  2195. Problem KOSARE (13106. KOSARE)
  2196. Problem PUCMM333 (13116. Dividing Xorland)
  2197. Problem PUCMM334 (13117. White Hats)
  2198. Problem PUCMM335 (13118. The Rook and The Rookette )
  2199. Problem ADITYA13 (13120. FizzBuzz Happy 2013)
  2200. Problem STICKS (13150. Magic Sticks)
  2201. Problem MAY99_1 (13156. Tom and Jerry )
  2202. Problem TIP1 (13165. Totient in permutation (easy))
  2203. Problem TIP2 (13166. Totient in permutation (medium))
  2204. Problem TIP3 (13167. Totient in permutation (hard))
  2205. Problem FAST_BF (13223. The BrainFast Processing! Classical version)
  2206. Problem OVOXO (13303. Tic-tac-toe 3)
  2207. Problem KMEDIAL (13362. Median of sub-sequences)
  2208. Problem WINDVANE (13363. WIND VANE)
  2209. Problem WITTY (13364. THE N WITTY FRIENDS)
  2210. Problem BOULDER (13365. Move the boulder)
  2211. Problem GEEKOUNT (13367. EVEN COUNT)
  2212. Problem PRESIDEN (13376. The new President)
  2213. Problem MAY99_2 (13381. Manku Word)
  2214. Problem KINDERPC (13382. Kindergarten Painting Competition )
  2215. Problem NICEBTRE (13384. Nice Binary Trees)
  2216. Problem MAY99_3 (13388. Easy Jug)
  2217. Problem CONHONPR (13398. Contest Hall Preparation)
  2218. Problem MAY99_4 (13399. Rachu )
  2219. Problem ICPC12C (13404. The Encrypted Password)
  2220. Problem APCER (13405. MayanCalendar)
  2221. Problem PISANO (13419. Modular Fibonacci Period)
  2222. Problem FMODF (13420. Fimodacci)
  2223. Problem CNT_LUCK (13444. Counting Lucky Numbers)
  2224. Problem CRAYON (13447. Crayon)
  2225. Problem ALONE (13469. FOREVER ALONE)
  2226. Problem PONY8 (13500. Discord is at it again)
  2227. Problem MDT1 (13508. Madotsuki Pattern)
  2228. Problem KOSPC13B (13511. Determine the vismin value !)
  2229. Problem GUMATH2 (13523. Card Meets (medium))
  2230. Problem SPECIALG (13529. Special Graph)
  2231. Problem CHGROOM (13545. Room Change)
  2232. Problem HC12 (13577. Card Game)
  2233. Problem ONEXLIS (13588. One X LIS)
  2234. Problem FCTRHELL (13591. Factor y Hell)
  2235. Problem PRLOVE (13592. Expected Time to Love)
  2236. Problem ASTDPROB (13595. A STANDARD PROBLEM)
  2237. Problem HC12II (13621. Security)
  2238. Problem HC12III (13622. Dead Pixels)
  2239. Problem CBANK (13626. Charu and Coin Distribution)
  2240. Problem BAT1 (13630. BATMAN1)
  2241. Problem BAT2 (13631. BATMAN2)
  2242. Problem BAT3 (13643. BATMAN3)
  2243. Problem BAT4 (13646. BATMAN4)
  2244. Problem TJANDRAS (13647. Tjandra 19th birthday (EASY))
  2245. Problem KNGCHECK (13651. Check)
  2246. Problem TRANCLS (13683. Transitive Closure)
  2247. Problem MAX_NUM (13686. finding maximum possible number)
  2248. Problem SHAHBG (13707. SHAHBAG)
  2249. Problem A_W_S_N (13738. Happy Valentine Day (Valentine Maze Game))
  2250. Problem SAFECRAC (13745. Crack the Safe)
  2251. Problem APS (13753. Amazing Prime Sequence)
  2252. Problem CRAN01 (13768. An Experiment by Penny)
  2253. Problem CRAN02 (13769. Roommate Agreement)
  2254. Problem CRAN04 (13780. Audition)
  2255. Problem NAIVELOK (13799. Naive Loki)
  2256. Problem DEXTER (13801. Dexter Rank)
  2257. Problem XMEN (13805. X-MEN)
  2258. Problem CHAOS_CC (13806. Chaos In Arkham)
  2259. Problem RDRUG (13807. Rage Drug)
  2260. Problem COLOR_CC (13808. Colors)
  2261. Problem ISRANK (13809. ISRANK)
  2262. Problem INBOX (13815. India in Box)
  2263. Problem PGAME (13816. Pheversos Game)
  2264. Problem WIMB (13826. The Grandslam of Grandslams!)
  2265. Problem TJANDRA2 (13829. Tjandra 19th birthday present (HARD))
  2266. Problem SBW (13833. Super Borboletas World)
  2267. Problem M_SEQ (13838. Mosty! Find Gn)
  2268. Problem NITTROAD (13868. Roads of NITT)
  2269. Problem JOKER1 (13875. Knifes Are Fun)
  2270. Problem FUNNUMS (13881. FUN WITH LETTERS)
  2271. Problem WITTYBOY (13882. THE WITTY BOY)
  2272. Problem FLING1 (13884. FLING1)
  2273. Problem BLOCK_D (13886. BLOCK_D SOLVER)
  2274. Problem PARTYTIM (13895. Party Time)
  2275. Problem MANGOES (13913. Real Mangoes for Ranjith)
  2276. Problem MEETUP (13917. EXPLORE TIME)
  2277. Problem STRINGQ (13918. String Queries)
  2278. Problem RANGZER2 (13925. ZEROES IN RANGE V2)
  2279. Problem GRIDFLIP (13926. Flipping Slipping of grids)
  2280. Problem PIBO2 (13940. Fibonacci vs Polynomial (HARD))
  2281. Problem AMSCO1 (13941. The AMSCO cipher)
  2282. Problem GHALIBC (13945. GHALIBS CHALLENGE)
  2283. Problem KAYKAY (13948. Disjoint Subtrees)
  2284. Problem DTPOLY2 (13953. Divide Polygon (HARD))
  2285. Problem TMB (13977. Thousands ByteMan March)
  2286. Problem BBM (13978. Billion ByteMan March)
  2287. Problem SUDOGOB (13980. Sudoku goblin)
  2288. Problem SUSY (13989. Helping Susy)
  2289. Problem WEBISL (13990. Web islands)
  2290. Problem VPL1_AA (14031. Spring Primality)
  2291. Problem VPL1_AB (14032. Summer Game)
  2292. Problem VPL1_AC (14033. Late Summer Searching)
  2293. Problem VPL1_AD (14034. Autumn Leaves)
  2294. Problem VPL1_AE (14035. Winter Crush)
  2295. Problem VOLNTEER (14049. Annual Day)
  2296. Problem WWAKER (14055. The Wind Waker)
  2297. Problem IRECSQRT (14122. Inverse of Recurrence Problem With a Square Root)
  2298. Problem AFS (14138. Amazing Factor Sequence)
  2299. Problem THEATRE (14156. Movie Theatre Madness)
  2300. Problem AFS2 (14168. Amazing Factor Sequence (medium))
  2301. Problem AFSK (14175. Power Factor Sum Sum (hard))
  2302. Problem LIFERACE (14181. LIFE IS A RACE)
  2303. Problem LOCKER (14329. Magic of the locker)
  2304. Problem POWERPHI (14330. Power of Phi(medium))
  2305. Problem DIXIE001 (14334. Evil Overlord Cypher)
  2306. Problem SCIENCE (14387. Science)
  2307. Problem AMSCO2 (14435. Decipher the AMSCO cipher)
  2308. Problem CIRCLE_E (14441. Three Circle Problem (EASY))
  2309. Problem CIRCLE_H (14443. Three Circle Problem (HARD))
  2310. Problem PYTRIP2 (14542. Pythagorean triples (medium))
  2311. Problem RANGESUM (14543. Range Sum)
  2312. Problem HAP01 (14629. Play with Binary Numbers)
  2313. Problem CATHETEN (14664. Shared cathetus (easy))
  2314. Problem DELTACAT (14665. Delta catheti (hard))
  2315. Problem LOOPEXP (14697. Loop Expectation)
  2316. Problem DELTACA2 (14700. Delta catheti II (Hard))
  2317. Problem BRDGHRD (14742. Building Bridges(HARD))
  2318. Problem SELFDESN (14751. Self Descriptive Number)
  2319. Problem ALMISPY (14761. Almost-isosceles Pythagorean triple (easy))
  2320. Problem PERMTGEN (14819. Permutation Generator)
  2321. Problem RETDIG (14820. Return of the Digger)
  2322. Problem TLIGHTS (14821. Traffic Lights)
  2323. Problem BSHIP (14822. Battleships)
  2324. Problem ABSHIP (14823. Advanced Battleships)
  2325. Problem CFATHER (14830. The Codefather)
  2326. Problem GCJPURE (14831. Your Rank is Pure)
  2327. Problem FOXWOLF (14833. The Fox and the Wolf)
  2328. Problem FOXLINGS (14834. Foxlings)
  2329. Problem BOXD (14839. Boxdropper)
  2330. Problem GCJ1C09A (14844. All Your Base)
  2331. Problem GCJ1C09B (14845. Center of Mass )
  2332. Problem GCJ1C09C (14846. Bribe the Prisoners)
  2333. Problem BOXLINGS (14848. Boxlings)
  2334. Problem CRAZYSK (14856. Crazy Shopkeeper)
  2335. Problem DIGCNT (14858. digit count)
  2336. Problem ULASER (14862. Union Laser)
  2337. Problem SALES (14864. Sales)
  2338. Problem AU7_5 (14871. STUDENTS)
  2339. Problem GCJ121CC (14883. Box Factory)
  2340. Problem MATT (14886. Matts Trip)
  2341. Problem GOODA (14887. Good Travels)
  2342. Problem GOODB (14888. Good Predictions)
  2343. Problem GOODC (14889. Good Strategy)
  2344. Problem GOODD (14890. Good Code)
  2345. Problem GOODE (14891. Good Debugging)
  2346. Problem GOODF (14892. Good Aim)
  2347. Problem GOODG (14893. Good Inflation)
  2348. Problem GOODH (14894. Good Celebration)
  2349. Problem ZIGZAG2 (14905. Zig when you zag)
  2350. Problem GRAFFDEF (14923. King Graffs Defense)
  2351. Problem GRAFFTOL (14924. King Graffs Tolls)
  2352. Problem GRAFFTRI (14925. King Graffs Trip)
  2353. Problem KIMO1 (14926. abdou set)
  2354. Problem PIRACON (14928. Pyramidal Constructions)
  2355. Problem SUBSN (14929. Subsequence)
  2356. Problem FARIDA (14930. Princess Farida)
  2357. Problem LCA (14932. Lowest Common Ancestor)
  2358. Problem CAC (14935. Cactus)
  2359. Problem DRTREE (14943. Dynamically-Rooted Tree)
  2360. Problem SANTA1 (14944. Reindeer Games)
  2361. Problem SANTA2 (14946. Travelling Santa)
  2362. Problem SANTA3 (14947. Breaking and Entering)
  2363. Problem HELPER (14949. HELPER)
  2364. Problem DCOWS (14955. Dancing Cows)
  2365. Problem SUBMERGE (14956. Submerging Islands)
  2366. Problem CHIGAME (14957. Chinese game)
  2367. Problem MAXGRITH (14961. Maximum Girth)
  2368. Problem UOFTAB (14971. The Foxens Treasure)
  2369. Problem UOFTAC (14972. Foxhole)
  2370. Problem UOFTAD (14973. Reverse Fox Hunt)
  2371. Problem UOFTAE (14974. Foxling Feeding Frenzy)
  2372. Problem UOFTAF (14975. Foxic Expressions)
  2373. Problem UOFTBB (14977. Attack of the Bloons)
  2374. Problem UOFTBC (14978. Homemade Asteroids)
  2375. Problem UOFTBD (14979. Diablo Bot)
  2376. Problem UOFTBE (14980. MVP)
  2377. Problem UOFTBF (14981. Light Cycling)
  2378. Problem EGCJPURE (14991. Your Rank is Pure (EXTREME ver))
  2379. Problem CLASSICO (15038. Yell Classico)
  2380. Problem GCJ102A (15060. Elegant Diamond)
  2381. Problem GCJ102B (15061. World Cup 2010)
  2382. Problem GCJ102C (15062. Bacteria)
  2383. Problem SLIDE (15073. Team Slide Treasure Hunt Race)
  2384. Problem TOURNEY (15074. Tourney)
  2385. Problem RDINNER (15075. A Romantic Dinner Outing)
  2386. Problem RMOVIE (15076. A Romantic Movie Outing)
  2387. Problem ACQUIRE (15086. Land Acquisition)
  2388. Problem BFDIV (15088. Ancient Aliens)
  2389. Problem BFMUL (15089. Farmer Joe)
  2390. Problem BFBASE (15091. One Good Base Deserves Another)
  2391. Problem BFREGEX1 (15092. A Kleene Implementation)
  2392. Problem POP1 (15143. play with prime numbers (I))
  2393. Problem POP2 (15148. play with prime numbers (II))
  2394. Problem POP3 (15149. play with prime numbers (III)(hard ))
  2395. Problem PTRI (15164. primes triangle (I))
  2396. Problem PTR2 (15165. primes triangle (II))
  2397. Problem SBO (15190. MAXIMUM RARITY)
  2398. Problem MC (15208. Minimum Cost)
  2399. Problem PUCMM009 (15215. David and his Obsession)
  2400. Problem VPL2_AA (15241. Luis Quest)
  2401. Problem VPL2_AB (15242. Betos Quest)
  2402. Problem VPL2_AC (15243. Primos Quest)
  2403. Problem VPL2_AD (15244. Davids Quest)
  2404. Problem SWAP_ESY (15248. Swap (Easy - Level 2))
  2405. Problem SWAP_MED (15249. Swap (Medium - Level 200))
  2406. Problem SWAP_HRD (15250. Swap (Hard - Level 1000))
  2407. Problem MOSTYCOD (15252. Humans Life Code)
  2408. Problem PARCARD1 (15256. Partition function (EASY))
  2409. Problem PARCARD2 (15257. Partition function (HARD))
  2410. Problem LKS (15259. Large Knapsack)
  2411. Problem FRNDCIRC (15267. FRIEND CIRCLE)
  2412. Problem ICKAPLSB (15270. A plus B)
  2413. Problem ROHAAN (15285. Defend The Rohan)
  2414. Problem VPL2_BC (15310. Peter Quest)
  2415. Problem VPL2_BE (15312. Annoying Coins Quest)
  2416. Problem HXH (15328. Hunter x Hunter)
  2417. Problem ICKHELLO (15336. Hello Intercal!)
  2418. Problem WRLUNCH (15360. World Record Lunch)
  2419. Problem RMID (15376. Running Median)
  2420. Problem BFGCD (15381. Cut The Rope)
  2421. Problem FCTRL5 (15382. Factorial (Again!))
  2422. Problem BFONP (15383. Transform the Expression (Again!))
  2423. Problem UCV2013A (15429. Counting Ids)
  2424. Problem UCV2013B (15430. Alice in Amsterdam, I mean Wonderland)
  2425. Problem UCV2013C (15431. Farmer Cream)
  2426. Problem UCV2013D (15432. Distributing V-Energy)
  2427. Problem UCV2013E (15433. Greedy Walking)
  2428. Problem UCV2013F (15434. Life on Fornax)
  2429. Problem UCV2013G (15435. Schedules)
  2430. Problem UCV2013H (15436. Slick)
  2431. Problem UCV2013I (15437. Tambourine)
  2432. Problem UCV2013J (15438. Valences)
  2433. Problem UCV2013K (15439. Zombie Outbreak)
  2434. Problem KCARRY (15453. Yet Another Electronic Device!!!)
  2435. Problem AKVQLD03 (15454. How to Handle the Fans)
  2436. Problem SELLINGA (15460. Selling Art)
  2437. Problem KIMO4 (15498. Kawigi quote)
  2438. Problem IGOR (15506. Helping Igor)
  2439. Problem SHANGUL (15541. Simplified Hangul)
  2440. Problem DYEL (15551. Do You Even Lift)
  2441. Problem STC00 (15553. Hamsters)
  2442. Problem IITKWPCA (15554. Niceness of the string)
  2443. Problem IITKWPCB (15555. Check the coprimeness)
  2444. Problem IITKWPCC (15556. Count right angle triangles)
  2445. Problem IITKWPCD (15557. Partition the sticks)
  2446. Problem IITKWPCE (15558. Let us play with strings)
  2447. Problem IITKWPCF (15559. Help Feluda with mathematical equations)
  2448. Problem IITKWPCG (15560. Help the old King)
  2449. Problem IITKWPCH (15561. Find Number Of Pair of Friends )
  2450. Problem IITKWPCI (15562. Find Lexicographically Smallest Permutation)
  2451. Problem IITKWPCJ (15563. Check the string Powers)
  2452. Problem IITKWPCL (15565. Find Distances In A Plane)
  2453. Problem IITKWPCM (15566. Coprime Again)
  2454. Problem IITKWPCN (15567. Playing With Balls)
  2455. Problem STC01 (15568. Fire Extinguishers)
  2456. Problem STC02 (15569. Antisymmetry)
  2457. Problem STC04 (15571. Difference)
  2458. Problem STC05 (15572. Garden)
  2459. Problem STC06 (15573. Keyboard)
  2460. Problem STC07 (15574. Railway)
  2461. Problem STC08 (15575. Kangaroos)
  2462. Problem STC09 (15576. Aesthetic Text)
  2463. Problem STC10 (15577. Blockade)
  2464. Problem SPIKES (15609. Spiky Mazes)
  2465. Problem POSTERIN (15620. Postering)
  2466. Problem TIEROPE (15621. Tie the Rope)
  2467. Problem IITKWPCO (15627. Create Collections)
  2468. Problem PLUS (15631. On the Plus Side)
  2469. Problem GNYR04C (15634. Lennys Lucky Lotto Lists)
  2470. Problem GNYR04I (15636. Histology Assistant)
  2471. Problem GNYR04H (15637. Mr Youngs Picture Permutations)
  2472. Problem APIO10A (15648. Commando)
  2473. Problem NWERC05 (15649. Unequalled Consumption)
  2474. Problem ULM09 (15650. Dark roads)
  2475. Problem FACTMUL (15655. Product of factorials)
  2476. Problem FACTMULM (15671. Product of factorials (medium))
  2477. Problem ULM02 (15728. The Sierpinski Fractal)
  2478. Problem ULM2H (15733. Hall of Fountains)
  2479. Problem ULM02C (15734. California Jones and the Gate to Freedom)
  2480. Problem ULM02B (15735. Balanced Food)
  2481. Problem BRKSTRNG (15736. Breaking String)
  2482. Problem SUMSUM (15766. Enjoy Sum with Operations)
  2483. Problem ADDGP (15769. Enjoy Adding GP to Series)
  2484. Problem CODERE3 (15783. Coder Express 3!!)
  2485. Problem AUT (15827. Vending Machine)
  2486. Problem SECTORS (15847. Equalize the Sectors)
  2487. Problem DIGOKEYS (15849. Find the Treasure)
  2488. Problem DGAME (15850. Game)
  2489. Problem PSERVICE (15851. Permutations)
  2490. Problem CRAZY (15863. Crazy Tank)
  2491. Problem SUMMING (15864. SUMMING)
  2492. Problem SNGGW (15867. Great Warrior)
  2493. Problem SNGPG (15891. Prime Generator The Easiest Question Ever)
  2494. Problem CAVE2 (15892. Cave)
  2495. Problem USUBQSUB (15914. Update Sub-Matrix & Query Sub-Matrix)
  2496. Problem MAXSET (15961. MAXSET)
  2497. Problem HELPDONN (15963. Help Donn)
  2498. Problem ENIGMATH (15965. PLAY WITH MATH)
  2499. Problem ASCDFIB (15980. Ascending Fibonacci Numbers)
  2500. Problem BOXSCHOC (15994. Boxes of Chocolate)
  2501. Problem MCUR98 (15995. Self Numbers)
  2502. Problem SNGNM2 (15996. Number Magic II)
  2503. Problem QUE1 (16015. Queue (Rookie))
  2504. Problem QUE2 (16016. Queue (Pro))
  2505. Problem MCU20A (16017. The Triangle Game)
  2506. Problem MCU20E (16018. Edge Detection)
  2507. Problem PSYCHON (16030. Psycho)
  2508. Problem TIPTOP (16033. Tip Top Game)
  2509. Problem MINNUM (16034. Minimum Number)
  2510. Problem OU7 (16035. Fone Frequencies)
  2511. Problem HPPROF (16046. Help Professor)
  2512. Problem PONY9 (16048. Help Rarity Collect Crystals)
  2513. Problem SNGCP (16062. Count Primes)
  2514. Problem TREEBA (16063. Hackers)
  2515. Problem CARRHIM (16102. Can you play carrom !!!)
  2516. Problem SUBTLEBA (16113. Trucks Transportation)
  2517. Problem NITK06 (16121. MODIFY SEQUENCE)
  2518. Problem NITK07 (16128. THE INDIAN OCEAN)
  2519. Problem COD1 (16134. Save the cows!)
  2520. Problem CODGRF (16138. Deconnecting)
  2521. Problem CODCHESS (16139. Naya Shatranj (New Chess))
  2522. Problem CODHASH (16177. Hashcodes and primes)
  2523. Problem TPC07 (16178. Change)
  2524. Problem PTRELIC (16179. Platinum Relic!)
  2525. Problem RATAR (16180. Ratar)
  2526. Problem CODFURY (16184. Megatron and his rage)
  2527. Problem BUSINESS (16185. Mining your own business)
  2528. Problem DCEPC11F (16207. Football Fever)
  2529. Problem DCEPC11C (16208. Challenge Accepted)
  2530. Problem DCEPC11I (16210. Impossible Boss)
  2531. Problem DCEPC11B (16211. Boring Factorials)
  2532. Problem DCEPC11J (16212. Jailbreak)
  2533. Problem CODPABBU (16214. Pabbu-pneumonia)
  2534. Problem DCEPC11E (16240. Easy Password)
  2535. Problem DTRAP (16242. Dexters Trampoline)
  2536. Problem ANAGR (16243. Anagrams)
  2537. Problem KUSAC (16244. Kusac)
  2538. Problem COURAGE (16245. Living with Courage)
  2539. Problem NCLNE (16248. Clones)
  2540. Problem GDIL (16250. Dilemma)
  2541. Problem RMID2 (16254. Running Median Again)
  2542. Problem SKSTF (16266. Simplifying the Farm)
  2543. Problem REALNO (16267. Real Numbers)
  2544. Problem NANO (16272. Nanoworld)
  2545. Problem TAP2013A (16275. On the side of the road)
  2546. Problem TAP2013C (16277. Little Red-Cap)
  2547. Problem TAP2013D (16278. Watching the game)
  2548. Problem TAP2013E (16279. Escaping from escaping)
  2549. Problem TAP2013F (16280. Flowers of Babylon)
  2550. Problem TAP2013G (16281. War)
  2551. Problem TAP2013H (16282. Horace and his primes)
  2552. Problem TAP2013I (16283. Treasure Island)
  2553. Problem TAP2013J (16284. Game of stones)
  2554. Problem ICC (16297. Sir and The ICC Ratings)
  2555. Problem TRIISO (16300. Playing with isosceles triangle)
  2556. Problem GOSTONES (16307. Game of stones II)
  2557. Problem RUMMY (16381. Help Vishnu with his points)
  2558. Problem MY02 (16389. Play with Strings)
  2559. Problem LOPOV (16409. Lopov)
  2560. Problem ORGNZ (16410. Organizator)
  2561. Problem SLAST (16411. Slasticar)
  2562. Problem EC_CONB (16420. Even Numbers)
  2563. Problem DCRYPT (16480. Decrypt the message !)
  2564. Problem MKEQUAL (16482. Make them equal !)
  2565. Problem LUCKY (16483. Lucky Cities)
  2566. Problem UPDATEIT (16487. Update the array !)
  2567. Problem QTREE6 (16549. Query on a tree VI)
  2568. Problem COLONY (16554. Linearian Colony)
  2569. Problem PEGS (16556. Triangle)
  2570. Problem FORMAT (16557. HTML Formatting)
  2571. Problem QTREE7 (16580. Query on a tree VII)
  2572. Problem IE1 (16607. Sweets)
  2573. Problem IE2 (16636. Journey)
  2574. Problem IE4 (16639. Endless Knight)
  2575. Problem SOMESUMS (16686. Some Sums)
  2576. Problem RAFANOLE (16696. Nadal vs Djokovic)
  2577. Problem HELPCOMM (16716. Help Your Commander)
  2578. Problem SNGDIV69 (16758. Divisible by 6 and 9)
  2579. Problem EC_MODE (16776. Modems)
  2580. Problem CSHOWB (16778. Sir and the Guitar)
  2581. Problem EC_ESTA (16793. Statistics Applied)
  2582. Problem EST (16809. Estimation)
  2583. Problem EC_DIVS (16825. Divisors)
  2584. Problem EC_P (16909. Critical Edges)
  2585. Problem ENCODE (16956. Encoded Coordinates)
  2586. Problem BWIDOW (17110. Black Widow Rings)
  2587. Problem NFURY (17112. Training Land of Fury)
  2588. Problem TESSER (17113. Finding the Tesserect)
  2589. Problem IMBOX (17123. Destroying the Weapon Warehouse)
  2590. Problem AVCHESS (17124. Chess Board of Avengers)
  2591. Problem TBATTLE (17125. Thor vs Frost Giants)
  2592. Problem PUTNIK (17128. Putnik)
  2593. Problem PSYCHO3 (17143. Make Psycho)
  2594. Problem PR003004 (17247. Digit Sum)
  2595. Problem HPREFIX (17258. Yungom)
  2596. Problem BANKROB (17261. Bank robbery)
  2597. Problem SERVS (17302. Servers)
  2598. Problem BOARD1 (17303. Board)
  2599. Problem OPBIT (17309. Operation Bits)
  2600. Problem GUESSN3 (17320. Guess The Number With Lies v3)
  2601. Problem HFLY (17382. Airplane Parking)
  2602. Problem DCEPC12B (17394. Bits Game)
  2603. Problem DCEPC12D (17396. Dazzling Pearls)
  2604. Problem DCEPC12E (17397. End of Fun)
  2605. Problem DCEPC12F (17398. Fitting in the Team)
  2606. Problem DCEPC12G (17399. G Force)
  2607. Problem DCEPC12H (17400. Height of Expectation)
  2608. Problem DCEPC12J (17402. Joy of Arbitrage)
  2609. Problem GCJ082A (17406. Cheating a Boolean Tree)
  2610. Problem MABJ (17443. Magical Bus Journey)
  2611. Problem RLE (17504. Run length encoding)
  2612. Problem COWWORDS (17539. Cows Language)
  2613. Problem TWOGAME (17559. Two Game)
  2614. Problem SYNC13C (17617. WHAT A CO-ACCIDENT)
  2615. Problem GCOOP (17624. Cooperation in geometry !)
  2616. Problem CUTCAKE (17626. Eat all the brownies !)
  2617. Problem FAMWEALT (17627. Family members)
  2618. Problem WAYHOME (17660. The Bridge to Home)
  2619. Problem SPCE (17705. Gopu and Combinatorics on Graphs)
  2620. Problem POLCONST (17707. Constructible Regular Polygons)
  2621. Problem SPCJ (17711. Gopu and Create Collections Part Two)
  2622. Problem SPCM (17714. Gopu and function)
  2623. Problem SPCO (17717. Gopu and Counting Bitwise Prime Numbers)
  2624. Problem BADXOR (17725. Bad XOR)
  2625. Problem MAXRAD (17730. Maximum Radius)
  2626. Problem BUYINT (17731. Buying Integers)
  2627. Problem SALMAN (17732. Salary Management)
  2628. Problem TREEPAL (17755. Tree and Palindrome)
  2629. Problem SPCQ (17761. Gopu and Digits Divisibility)
  2630. Problem CHARCHOC (17779. Charlie and the Chocolate Factory)
  2631. Problem SPACEBRG (17789. Space Bridges)
  2632. Problem SPCS (17804. Gopu And Palindromes)
  2633. Problem XYI (17819. XYI)
  2634. Problem MNIU (17821. My Name is UMMM!)
  2635. Problem SAWMILL (17877. Two Swamills)
  2636. Problem SPCU (17918. Gopu and Validity of Arrangement)
  2637. Problem MMMAGIC3 (17943. Mickey Mouse Magic Trick v3)
  2638. Problem MMMAGIC4 (17944. Mickey Mouse Magic Trick v4)
  2639. Problem MMMAGIC5 (17945. Mickey Mouse Magic Trick v5)
  2640. Problem MMMAGIC6 (17946. Mickey Mouse Magic Trick v6)
  2641. Problem DOSA (17955. Lalith Dosa)
  2642. Problem RLCAT (18050. Robert Langdon & Class Attendance)
  2643. Problem RLCIPHER (18056. Robert Langdon & Cipher)
  2644. Problem RLTOUR (18094. Robert Langdon & Florence)
  2645. Problem CHOTU (18095. Faridi and Yadav)
  2646. Problem GSHOP (18149. Rama and Friends)
  2647. Problem SHAKTI (18150. SHAKTIMAN AND KILWISH)
  2648. Problem RLTHREE (18153. Robert Langdon & The Rule of Three)
  2649. Problem ABSP1 (18155. abs(a-b) I)
  2650. Problem ATOMS (18164. Atoms in the Lab)
  2651. Problem NCOPRIME (18165. Coprime Pairs)
  2652. Problem SUBXOR (18167. SubXor)
  2653. Problem TWOCIR (18168. Entangled Circles)
  2654. Problem TKV1000 (18170. Takeover Wars)
  2655. Problem RROOT (18174. REAL ROOTS)
  2656. Problem TENNIS1 (18175. TENNIS CHAMPIONSHIP)
  2657. Problem FRND (18176. FRIENDSHIP!!!)
  2658. Problem NAUGHTY (18182. Naughty and Balls)
  2659. Problem DRUNK (18183. Drunk Game)
  2660. Problem DURIN (18184. Durins Day)
  2661. Problem GIVEAWAY (18185. Give Away)
  2662. Problem MACHMAY (18186. Machine Mayhem)
  2663. Problem INGRED (18187. Ingredients)
  2664. Problem QSTABLE (18188. Queen and Stable Relationships)
  2665. Problem RKS (18201. RK Sorting)
  2666. Problem HG (18202. HUGE GCD)
  2667. Problem KURUK14 (18240. GENIE SEQUENCE)
  2668. Problem IITWPC4A (18243. Maggu and Strings)
  2669. Problem IITWPC4B (18245. Maggu and Triangles)
  2670. Problem IITWPC4C (18246. Maggu and Vectors)
  2671. Problem IITWPC4D (18247. Arrangement Validity)
  2672. Problem IITWPC4E (18248. Maggu’s Solar Panels)
  2673. Problem IITWPC4F (18249. Gopu and the Grid Problem)
  2674. Problem IITWPC4G (18261. Maggu and Weird things)
  2675. Problem SNGINT (18273. Encode Integer)
  2676. Problem IITWPC4H (18283. Maggu and Cuteness of Strings)
  2677. Problem IITWPC4I (18284. Petya and Repairment of Roads)
  2678. Problem IITWPC4J (18286. Gopu and Fishes)
  2679. Problem IITWPC4K (18287. Maggu and Magguness Level)
  2680. Problem IITWPC4L (18289. Maggu and Mystery)
  2681. Problem CODEM4 (18297. Problem4)
  2682. Problem IDC1948 (18302. Identity crisis)
  2683. Problem BIT2 (18336. Search Bit Sum)
  2684. Problem IE5 (18393. Hamiltonian Cycles)
  2685. Problem CRNVALEN (18408. The Valentine Confession)
  2686. Problem POLYMUL (18425. Polynomial Multiplication)
  2687. Problem VAL_GAM4 (18438. Happy Valentine Day (Valentine Adventure Game))
  2688. Problem MXSBMTRX (18450. Largest Increasing Sub-Matrix)
  2689. Problem VFRIENDS (18457. Very Friends)
  2690. Problem VFRIEND2 (18458. Very Friends 2)
  2691. Problem UOFTCC (18465. A Subtle Surf)
  2692. Problem UOFTCD (18466. A Frightening Evening)
  2693. Problem UOFTCE (18467. A Brief Expedition)
  2694. Problem UOFTCF (18468. A Pleasant Stroll)
  2695. Problem UOFTCG (18469. Office Mates)
  2696. Problem AKVOD05 (18510. Ross generates Data)
  2697. Problem AKVOD06 (18511. Cartman and Butters Game)
  2698. Problem FBWHEELS (18521. Fortunate Wheels)
  2699. Problem FBTOURS (18522. Tours)
  2700. Problem FONTSIZE (18530. Font Size)
  2701. Problem BRLRIDER (18531. Barrelrider)
  2702. Problem TREEORD (18532. Tree _order)
  2703. Problem SNGMSG (18598. Encode Message)
  2704. Problem LAWRENCE (18637. Lawrence of Arabia)
  2705. Problem FACTMULN (18660. Product of factorials (easy))
  2706. Problem FACTMULO (18662. Product of factorials (again))
  2707. Problem UVA1 (18666. Radiation)
  2708. Problem FACTMULP (18667. Product of factorials (hard))
  2709. Problem GOPI (18693. TOC)
  2710. Problem EMTY2 (18714. Can You Make It Empty 2)
  2711. Problem BORING (18715. Boring Factorials (Reloaded))
  2712. Problem BORING2 (18799. Boring Factorials (Extended))
  2713. Problem SPEC_SET (18829. Special Set)
  2714. Problem GOPI_SW (18857. Gopi and Sandwich)
  2715. Problem HLP_RAMS (18878. Topper Rama Rao)
  2716. Problem NR1 (18905. Kapti and Balu)
  2717. Problem ANIL_PRO (18915. Anils Proposal)
  2718. Problem DUKKAR (18917. Dukkar and Pikka)
  2719. Problem SUMPRIM2 (18932. Sum of primes (reverse mode))
  2720. Problem VENOM (18937. Touch of Venom)
  2721. Problem KSMALL (18939. K-th smallest number)
  2722. Problem FACENEMY (18940. Face the mate)
  2723. Problem TFRIENDS (18941. True Friends)
  2724. Problem POWERCAR (18945. Car with powers)
  2725. Problem NR2 (18963. Bhagat The Bit Man)
  2726. Problem COLORCAT (19037. The colors of cats)
  2727. Problem KIT (19039. Krypt in Time)
  2728. Problem DUKKAR2 (19084. Huge Pascal triangle)
  2729. Problem PIHEX2 (19125. Hexadecimal value of Pi)
  2730. Problem BASECONV (19133. Base Conversion)
  2731. Problem BOILING (19139. Boiling Vegetables)
  2732. Problem INS14A (19142. BSTRING)
  2733. Problem INS14B (19143. TRISQRS)
  2734. Problem INS14C (19144. Digo plays with Numbers)
  2735. Problem INS14D (19145. Digo Needs Guns)
  2736. Problem INS14E (19146. Glorious Gamblers)
  2737. Problem INS14F (19147. Save CodeVillage)
  2738. Problem INS14G (19148. Kill them All)
  2739. Problem INS14H (19149. Virus Revisited)
  2740. Problem INS14I (19150. Infinite Sequence)
  2741. Problem INS14J (19151. Checkers)
  2742. Problem INS14K (19152. Digo Goes Training)
  2743. Problem INS14L (19153. Rooted Trees)
  2744. Problem INS14M (19154. Terrorist Attack)
  2745. Problem WAL3A (19174. Khairy and Gold Alloys)
  2746. Problem SMARIO (19216. Super Mario)
  2747. Problem CAGES (19224. Lights, Snakes and Cages)
  2748. Problem LKID (19234. Identity crisis(Medium))
  2749. Problem SIRNUMS (19270. SIR CHIRAG AND MAGIC NUMBERS)
  2750. Problem BLOPER (19274. Operators)
  2751. Problem BFPRMCYC (19276. Peculiar Permutivores)
  2752. Problem WPC5C (19288. Sword Game)
  2753. Problem WPC5F (19290. Parade)
  2754. Problem WPC5A (19291. Structures)
  2755. Problem WPC5D (19292. Complicated Calculations)
  2756. Problem WPC5E (19293. Galaxy distances)
  2757. Problem WPC5G (19295. The dilemma of Idli)
  2758. Problem WPC5H (19297. Nymphs from H10)
  2759. Problem BLOPER2 (19301. Operators (new ver))
  2760. Problem WPC5I (19308. LCM)
  2761. Problem SKYLINE2 (19320. Draw Skyline Graph)
  2762. Problem GRUPVIVA (19329. Group Viva)
  2763. Problem KHAOTMPL (19334. Khaolin Temple)
  2764. Problem MACVSMAG (19335. Machau vs Maggu )
  2765. Problem BGRAVITY (19367. St Bernard and Gravity)
  2766. Problem STK (19382. Stock)
  2767. Problem FIBOSUM2 (19406. Fibonacci extraction Sum)
  2768. Problem POTIONS (19416. Potions Class)
  2769. Problem PAUWS (19490. Pair and unpair weightest string)
  2770. Problem GSS8 (19543. Can you answer these queries VIII)
  2771. Problem BWB (19545. Black and White beads)
  2772. Problem CWORLD (19551. A Colorful world)
  2773. Problem NBIN (19561. New Binary)
  2774. Problem PRMQUER (19568. Prime queries)
  2775. Problem PAML (19576. Popeye and the magical land)
  2776. Problem CWB (19578. Chipmunks with Brain)
  2777. Problem MATPROD (19684. Symmetric matrix)
  2778. Problem MCAMP (19686. Mining Camps)
  2779. Problem MATPROD2 (19687. Symmetric matrix 2)
  2780. Problem MTETRA (19722. Modular Tetration)
  2781. Problem PSYCHOT (19795. Psycho34 (easy))
  2782. Problem MIDEARTH (19899. Middle Earth)
  2783. Problem PYTRIP3 (19913. Counting Pythagorean Triples)
  2784. Problem KN2 (19954. Travelling Knight 2)
  2785. Problem APPROB (19957. GETTING AN AP)
  2786. Problem HAL9000 (19971. 100pct failure in 72 hours)
  2787. Problem APS2 (19975. Amazing Prime Sequence (hard))
  2788. Problem CUBE (19976. HYPERCUBES)
  2789. Problem GCDEX2 (19985. GCD Extreme (hard))
  2790. Problem FAILURE (19991. In case of failure)
  2791. Problem MOON1 (19996. Moon Safari (medium))
  2792. Problem MOON2 (19997. Moon Safari (Hard))
  2793. Problem SNGLOOP1 (20038. Easiest Loop 1)
  2794. Problem HIPPO (20041. Hippo and Bloody Jungle)
  2795. Problem LARSUBP (20063. Large subsequence Problem)
  2796. Problem HONDA (20100. Honda and Kagawa)
  2797. Problem ARRHUDAI (20167. Array with Hudai Calculation)
  2798. Problem COLORSEG (20170. Coloring Segments)
  2799. Problem DIVISION (20172. Divisiblity by 3)
  2800. Problem DIVCNT2 (20173. Counting Divisors (square))
  2801. Problem DIVCNT3 (20174. Counting Divisors (cube))
  2802. Problem DIVEQL (20196. The Magical Bag)
  2803. Problem BOI02TRI (20327. Triangles)
  2804. Problem TANDC (20562. Tracy and Charlie)
  2805. Problem MCIRCLE (20563. Minion Circle)
  2806. Problem DORTMUND (20635. Dortmund Dilemma)
  2807. Problem AJOB (20637. Ajob Subsequence)
  2808. Problem INTSUB (20654. Interesting Subset)
  2809. Problem CNTINDX (20673. Count The Indexes)
  2810. Problem LPPP (20674. Lov-e Pap Pap-e Polti)
  2811. Problem WRP (20689. WA,RTE and Placements)
  2812. Problem SUMXYZ (20723. Mechajny)
  2813. Problem RTREE (20775. Roger and tree)
  2814. Problem INUM (20845. Interesting Numbers)
  2815. Problem ISELECT (20846. Interesting Selection)
  2816. Problem IGAME (20848. Interesting Game)
  2817. Problem IQUERY (20849. Interesting queries)
  2818. Problem MINSUB (20863. Largest Submatrix)
  2819. Problem PCOPTRIP (20872. Counting Pairwise Coprime Triples)
  2820. Problem REVADD (20926. Special Numbers (Reverse and Add))
  2821. Problem EC_SER (20930. Progression)
  2822. Problem SNIM (20951. Pebbles)
  2823. Problem KHANS (20957. Alia and 3 Khans)
  2824. Problem HDEVIL (20970. Alia and Handsome Devil)
  2825. Problem HAGU (20971. Alia and Substrings)
  2826. Problem CONOR (20972. Alia and Cryptography)
  2827. Problem UCBINTA (20976. Sum)
  2828. Problem UCF (21049. Under Construction Forever)
  2829. Problem CTPLUCKY (21057. Super Lucky Palindromes)
  2830. Problem CTPDIRTY (21058. Dirty Plates)
  2831. Problem YASSP (21061. Yet Another Subset Sum Problem)
  2832. Problem RESSTNCE (21079. The Resistance)
  2833. Problem FRMT (21092. DRAW TABLE)
  2834. Problem WORDCNT2 (21096. Word Counting 2)
  2835. Problem JLNT (21104. Jarin Loves New Task)
  2836. Problem APIO14_A (21132. Palindromes)
  2837. Problem BFCC (21135. Distinct Viewpoints)
  2838. Problem MANJFIRE (21155. Manoj and Fire)
  2839. Problem TAP2014B (21169. Balanced base-3)
  2840. Problem TAP2014C (21170. Constellation of the parallelogram)
  2841. Problem TAP2014D (21171. Fractal domino)
  2842. Problem TAP2014E (21172. Erdos et al)
  2843. Problem TAP2014F (21173. String fertilization)
  2844. Problem TAP2014G (21174. Gallantry)
  2845. Problem TAP2014H (21175. Rush hour)
  2846. Problem TAP2014I (21176. Stapled intervals)
  2847. Problem TAP2014J (21177. Distracted judges)
  2848. Problem TAP2014K (21178. Encryption kit)
  2849. Problem ACPC13 (21187. Increasing Shortest Path)
  2850. Problem ADJDUCKS (21193. Adjusting Ducks)









SPOJ Problem Set (classical)

1. Life, the Universe, and Everything

Problem code: TEST

Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.

Example

Input:
1
2
88
42
99

Output:
1
2
88

Added by:Micha³ Ma³afiejski
Date:2004-05-01
Time limit:10s
Source limit:50000B
Cluster: Cube (Intel Pentium G860 3GHz)
Languages:All
Resource:Douglas Adams, The Hitchhiker's Guide to the Galaxy









SPOJ Problem Set (classical)

2. Prime Generator

Problem code: PRIME1

Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!

Input

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

Output

For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

Example

Input:
2
1 10
3 5

Output:
2
3
5
7

3
5
Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed)
Added by:Adam Dzedzej
Date:2004-05-01
Time limit:6s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

3. Substring Check (Bug Funny)

Problem code: SBSTR1

Given two binary strings, A (of length 10) and B (of length 5), output 1 if B is a substring of A and 0 otherwise.

Please note, that the solution may only be submitted in the following languages: Brainf**k, Whitespace and Intercal.

Input

24 lines consisting of pairs of binary strings A and B separated by a single space.

Output

The logical value of: 'B is a substring of A'.

Example

First two lines of input:

1010110010 10110
1110111011 10011

First two lines of output:
1
0


Added by:Adrian Kosowski
Date:2004-05-01
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:BF ICK WSPC









SPOJ Problem Set (main)

4. Transform the Expression

Problem code: ONP

Transform the algebraic expression with brackets into RPN form (Reverse Polish Notation). Two-argument operators: +, -, *, /, ^ (priority from the lowest to the highest), brackets ( ). Operands: only letters: a,b,...,z. Assume that there is only one RPN form (no expressions like a*b*c).

Input

t [the number of expressions <= 100]
expression [length <= 400]
[other expressions]

Text grouped in [ ] does not appear in the input file.

Output

The expressions in RPN form, one per line.

Example

Input:
3
(a+(b*c))
((a+b)*(z+x))
((a+t)*((b+(a+c))^(c+d)))

Output:
abc*+
ab+zx+*
at+bac++cd+^*

Added by:Micha³ Ma³afiejski
Date:2004-05-01
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ F# GO HASK NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCM qobi SED WSPC
Resource:-









SPOJ Problem Set (classical)

5. The Next Palindrome

Problem code: PALIN


A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.

Input

The first line contains integer t, the number of test cases. Integers K are given in the next t lines.

Output

For each K, output the smallest palindrome larger than K.

Example

Input:
2
808
2133

Output:
818
2222

Warning: large Input/Output data, be careful with certain languages


Added by:Adrian Kosowski
Date:2004-05-01
Time limit:2s-9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

6. Simple Arithmetics

Problem code: ARITH

One part of the new WAP portal is also a calculator computing expressions with very long numbers. To make the output look better, the result is formated the same way as is it usually used with manual calculations.

Your task is to write the core part of this calculator. Given two numbers and the requested operation, you are to compute the result and print it in the form specified below. With addition and subtraction, the numbers are written below each other. Multiplication is a little bit more complex: first of all, we make a partial result for every digit of one of the numbers, and then sum the results together.

Input

There is a single positive integer T on the first line of input (equal to about 1000). It stands for the number of expressions to follow. Each expression consists of a single line containing a positive integer number, an operator (one of +, - and *) and the second positive integer number. Every number has at most 500 digits. There are no spaces on the line. If the operation is subtraction, the second number is always lower than the first one. No number will begin with zero.

Output

For each expression, print two lines with two given numbers, the second number below the first one, last digits (representing unities) must be aligned in the same column. Put the operator right in front of the first digit of the second number. After the second number, there must be a horizontal line made of dashes (-).

For each addition or subtraction, put the result right below the horizontal line, with last digit aligned to the last digit of both operands.

For each multiplication, multiply the first number by each digit of the second number. Put the partial results one below the other, starting with the product of the last digit of the second number. Each partial result should be aligned with the corresponding digit. That means the last digit of the partial product must be in the same column as the digit of the second number. No product may begin with any additional zeros. If a particular digit is zero, the product has exactly one digit -- zero. If the second number has more than one digit, print another horizontal line under the partial results, and then print the sum of them.

There must be minimal number of spaces on the beginning of lines, with respect to other constraints. The horizontal line is always as long as necessary to reach the left and right end of both numbers (and operators) directly below and above it. That means it begins in the same column where the leftmost digit or operator of that two lines (one below and one above) is. It ends in the column where is the rightmost digit of that two numbers. The line can be neither longer nor shorter than specified.

Print one blank line after each test case, including the last one.

Example

Sample Input:

4
12345+67890
324-111
325*4405
1234*4

Sample Output:

 12345
+67890
------
 80235

 324
-111
----
 213

    325
  *4405
  -----
   1625
     0
 1300
1300
-------
1431625

1234
  *4
----
4936
Warning: large Input/Output data, be careful with certain languages.
Added by:Adrian Kosowski
Date:2004-05-08
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Prague 2000









SPOJ Problem Set (classical)

7. The Bulk!

Problem code: BULK

ACM uses a new special technology of building its transceiver stations. This technology is called Modular Cuboid Architecture (MCA) and is covered by a patent of Lego company. All parts of the transceiver are shipped in unit blocks that have the form of cubes of exactly the same size. The cubes can be then connected to each other. The MCA is modular architecture, that means we can select preferred transceiver configuration and buy only those components we need .

The cubes must be always connected "face-to-face", i.e. the whole side of one cube is connected to the whole side of another cube. One cube can be thus connected to at most six other units. The resulting equipment, consisting of unit cubes is called The Bulk in the communication technology slang.

Sometimes, an old and unneeded bulk is condemned, put into a storage place, and replaced with a new one. It was recently found that ACM has many of such old bulks that just occupy space and are no longer needed. The director has decided that all such bulks must be disassembled to single pieces to save some space. Unfortunately, there is no documentation for the old bulks and nobody knows the exact number of pieces that form them. You are to write a computer program that takes the bulk description and computes the number of unit cubes.

Each bulk is described by its faces (sides). A special X-ray based machine was constructed that is able to localise all faces of the bulk in the space, even the inner faces, because the bulk can be partially hollow (it can contain empty spaces inside). But any bulk must be connected (i.e. it cannot drop into two pieces) and composed of whole unit cubes.

 

Input

There is a single positive integer T on the first line of input (equal to about 1000). It stands for the number of bulks to follow. Each bulk description begins with a line containing single positive integer F, 6 <= F <= 250, stating the number of faces. Then there are F lines, each containing one face description. All faces of the bulk are always listed, in any order. Any face may be divided into several distinct parts and described like if it was more faces. Faces do not overlap. Every face has one inner side and one outer side. No side can be "partially inner and partially outer".

Each face is described on a single line. The line begins with an integer number P stating the number of points that determine the face, 4 <= P <= 200. Then there are 3 x P numbers, coordinates of the points. Each point is described by three coordinates X,Y,Z (0 <= X,Y,Z <= 1000) separated by spaces. The points are separated from each other and from the number P by two space characters. These additional spaces were added to make the input more human readable. The face can be constructed by connecting the points in the specified order, plus connecting the last point with the first one.

The face is always composed of "unit squares", that means every edge runs either in X, Y or Z-axis direction. If we take any two neighbouring points X1,Y1,Z1 and X2,Y2,Z2, then the points will always differ in exactly one of the three coordinates. I.e. it is either X1 <> X2, or Y1 <> Y2, or Z1 <> Z2, other two coordinates are the same. Every face lies in an orthogonal plane, i.e. exactly one coordinate is always the same for all points of the face. The face outline will never touch nor cross itself.

 

Output

Your program must print a single line for every test case. The line must contain the sentence The bulk is composed of V units., where V is the volume of the bulk.

Example

Sample Input:

2
12
4  10 10 10  10 10 20  10 20 20  10 20 10
4  20 10 10  20 10 20  20 20 20  20 20 10
4  10 10 10  10 10 20  20 10 20  20 10 10
4  10 20 10  10 20 20  20 20 20  20 20 10
4  10 10 10  10 20 10  20 20 10  20 10 10
5  10 10 20  10 20 20  20 20 20  20 15 20  20 10 20
4  14 14 14  14 14 16  14 16 16  14 16 14
4  16 14 14  16 14 16  16 16 16  16 16 14
4  14 14 14  14 14 16  16 14 16  16 14 14
4  14 16 14  14 16 16  16 16 16  16 16 14
4  14 14 14  14 16 14  16 16 14  16 14 14
4  14 14 16  14 16 16  16 16 16  16 14 16
12
4  20 20 30  20 30 30  30 30 30  30 20 30
4  10 10 10  10 40 10  40 40 10  40 10 10
6  10 10 20  20 10 20  20 30 20  30 30 20  30 40 20  10 40 20
6  20 10 20  20 20 20  30 20 20  30 40 20  40 40 20  40 10 20
4  10 10 10  40 10 10  40 10 20  10 10 20
4  10 40 10  40 40 10  40 40 20  10 40 20
4  20 20 20  30 20 20  30 20 30  20 20 30
4  20 30 20  30 30 20  30 30 30  20 30 30
4  10 10 10  10 40 10  10 40 20  10 10 20
4  40 10 10  40 40 10  40 40 20  40 10 20
4  20 20 20  20 30 20  20 30 30  20 20 30
4  30 20 20  30 30 20  30 30 30  30 20 30

Sample Output:

The bulk is composed of 992 units.
The bulk is composed of 10000 units.

Warning: large Input/Output data, be careful with certain languages


Added by:Adrian Kosowski
Date:2004-05-08
Time limit:1s-7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Prague 2000









SPOJ Problem Set (classical)

8. Complete the Sequence!

Problem code: CMPLS

You probably know those quizzes in Sunday magazines: given the sequence 1, 2, 3, 4, 5, what is the next number? Sometimes it is very easy to answer, sometimes it could be pretty hard. Because these "sequence problems" are very popular, ACM wants to implement them into the "Free Time" section of their new WAP portal.

ACM programmers have noticed that some of the quizzes can be solved by describing the sequence by polynomials. For example, the sequence 1, 2, 3, 4, 5 can be easily understood as a trivial polynomial. The next number is 6. But even more complex sequences, like 1, 2, 4, 7, 11, can be described by a polynomial. In this case, 1/2.n2-1/2.n+1 can be used. Note that even if the members of the sequence are integers, polynomial coefficients may be any real numbers.

Polynomial is an expression in the following form:

P(n) = aD.nD+aD-1.nD-1+...+a1.n+a0

If aD <> 0, the number D is called a degree of the polynomial. Note that constant function P(n) = C can be considered as polynomial of degree 0, and the zero function P(n) = 0 is usually defined to have degree -1.

Input

There is a single positive integer T on the first line of input (equal to about 5000). It stands for the number of test cases to follow. Each test case consists of two lines. First line of each test case contains two integer numbers S and C separated by a single space, 1 <= S < 100, 1 <= C < 100, (S+C) <= 100. The first number, S, stands for the length of the given sequence, the second number, C is the amount of numbers you are to find to complete the sequence.

The second line of each test case contains S integer numbers X1, X2, ... XS separated by a space. These numbers form the given sequence. The sequence can always be described by a polynomial P(n) such that for every i, Xi = P(i). Among these polynomials, we can find the polynomial Pmin with the lowest possible degree. This polynomial should be used for completing the sequence.

Output

For every test case, your program must print a single line containing C integer numbers, separated by a space. These numbers are the values completing the sequence according to the polynomial of the lowest possible degree. In other words, you are to print values Pmin(S+1), Pmin(S+2), .... Pmin(S+C).

It is guaranteed that the results Pmin(S+i) will be non-negative and will fit into the standard integer type.

Example

Sample Input:

4
6 3
1 2 3 4 5 6
8 2
1 2 4 7 11 16 22 29
10 2
1 1 1 1 1 1 1 1 1 2
1 10
3

Sample Output:

7 8 9
37 46
11 56
3 3 3 3 3 3 3 3 3 3
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-05-08
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Prague 2000









SPOJ Problem Set (classical)

9. Direct Visibility

Problem code: DIRVS

Building the GSM network is a very expensive and complex task. Moreover, after the Base Transceiver Stations (BTS) are built and working, we need to perform many various measurements to determine the state of the network, and propose effective improvements to be made.

The ACM technicians have a special equipment for measuring the strength of electro-magnetic fields, the transceivers' power and quality of the signal. This equipment is packed into a huge knapsack and the technician must move with it from one BTS to another. Unfortunately, the knapsack have not enough memory for storing all of the measured values. It has a small cache only, that can store values for several seconds. Then the values must be transmitted to the BTS by an infrared connection (IRDA). The IRDA needs direct visibility between the technician and the BTS.

Your task is to find the path between two neighbouring BTSes such that at least one of those BTSes is always visible.

Input

There is a single positive integer T on the first line of input (equal to about 500). It stands for the number of test cases to follow. Each test case consists of a town description. For simplicity, a town is modelled as a rectangular grid of P x Q square fields. Each field is exactly 1 metre wide. For each field, a non-negative integer Zi,j is given, representing the height of the terrain in that place, in metres. That means the town model is made of cubes, each of them being either solid or empty. There are no "half solid" cubes.

The first line of each test case contains two integer numbers P and Q, separated by a single space, 1 <= P,Q <= 200. Then there are P lines each containing Q integer numbers separated by a space. These numbers are Zi,j, where 1 <= i <= P, 1 <= j <= Q and 0 <= Zi,j <= 5000. After the terrain description, there are four numbers R1, C1, R2, C2 on the last line of each test case. These numbers represent position of two BTSes, 1 <= R1,R2 <= P, 1 <= C1,C2 <= Q. The first coordinate (R) determines the row of the town, the second coordinate determines the column.

The technician is moving in steps (steps stands for Standard Technician's Elementary Positional Shift). Each step is made between two neighbouring square fields. That means the step is always in North, South, West or East direction. It is not possible to move diagonally. The step between two fields A and B (step from A to B) is allowed only if the height of the terrain in the field B is not very different from the height in the field A. The technician can climb at most 1 metre up or descend at most 3 metres down in a single step.

At the end of each step, at least one of the two BTSes must be visible. However, there can be some point "in the middle of the step" where no BTS is visible. This is OK and the data is handled by the cache. The BTS is considered visible, if there is a direct visibility between the unit cube just above the terrain on the BTSes coordinates and the cube just above the terrain on the square field, where the technician is. Direct visibility between two cubes means that the line connecting the centres of the two cubes does not intersect any solid cube. However, the line can touch any number of solid cubes. In other words, consider both the BTS and the technician being points exactly half metre above the surface and in the centre of the appropriate square field.

Note that the IRDA beam can go between two cubes that touch each other by their edge, although there is no space between them. It is because such a beam touches both of these two cubes but does not intersect any of them. See the last test case of the sample input for an example of such a situation.

Output

You are to find the shortest possible path from BTS (R1, C1) to BTS (R2, C2), meeting the above criteria. All steps must be done between neighbouring fields, the terrain must not elevate or descend too much, and at the end of each step, at least one BTS must be visible.

For each test case, print one line containing the sentence The shortest path is M steps long., where M is the number of steps that must be made. If there is no such path, output the sentence Mission impossible!.

Example

Sample Input:

4
5 5
8 7 6 5 4
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
1 1 5 1
5 8
2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2
9 9 9 9 9 9 9 2
2 2 2 2 2 2 2 2
1 2 5 1
5 8
2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2
9 9 9 9 9 9 9 2
2 2 2 2 2 2 2 2
1 5 5 1
6 12
5 5 5 5 1 5 5 5 5 5 5 5
5 5 5 5 1 5 5 5 5 5 5 5
5 5 5 5 9 5 5 5 5 5 5 5
5 9 1 5 5 5 5 5 5 5 5 5
5 5 9 5 5 5 5 5 5 5 5 5
5 5 9 5 5 5 5 5 5 5 5 5
6 1 3 12

Sample Output:

The shortest path is 10 steps long.
Mission impossible!
The shortest path is 14 steps long.
The shortest path is 18 steps long.

Added by:Adrian Kosowski
Date:2004-05-08
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Prague 2000









SPOJ Problem Set (classical)

10. Complicated Expressions

Problem code: CMEXPR

The most important activity of ACM is the GSM network. As the mobile phone operator, ACM must build its own transmitting stations. It is very important to compute the exact behaviour of electro-magnetic waves. Unfortunately, prediction of electro-magnetic fields is a very complex task and the formulas describing them are very long and hard-to-read. For example, Maxwell's Equations describing the basic laws of electrical engineering are really tough.

ACM has designed its own computer system that can make some field computations and produce results in the form of mathematic expressions. Unfortunately, by generating the expression in several steps, there are always some unneeded parentheses inside the expression. Your task is to take these partial results and make them "nice" by removing all unnecessary parentheses.

Input

There is a single positive integer T on the first line of input (equal to about 10000). It stands for the number of expressions to follow. Each expression consists of a single line containing only lowercase letters, operators (+, -, *, /) and parentheses (( and )). The letters are variables that can have any value, operators and parentheses have their usual meaning. Multiplication and division have higher priority then subtraction and addition. All operations with the same priority are computed from left to right (operators are left-associative). There are no spaces inside the expressions. No input line contains more than 250 characters.

Output

Print a single line for every expression. The line must contain the same expression with unneeded parentheses removed. You must remove as many parentheses as possible without changing the semantics of the expression. The semantics of the expression is considered the same if and only if any of the following conditions hold:

You cannot use any other laws, namely you cannot swap left and right operands and you cannot replace "a-(b-c)" with "a-b+c".

Example

Sample Input:

8
(a+(b*c))
((a+b)*c)
(a*(b*c))
(a*(b/c)*d)
((a/(b/c))/d)
((x))
(a+b)-(c-d)-(e/f)
(a+b)+(c-d)-(e+f)

Sample Output:

a+b*c
(a+b)*c
a*b*c
a*b/c*d
a/(b/c)/d
x
a+b-(c-d)-e/f
a+b+c-d-(e+f)

Added by:Adrian Kosowski
Date:2004-05-09
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Prague 2000









SPOJ Problem Set (classical)

11. Factorial

Problem code: FCTRL

The most important part of a GSM network is so called Base Transceiver Station (BTS). These transceivers form the areas called cells (this term gave the name to the cellular phone) and every phone connects to the BTS with the strongest signal (in a little simplified view). Of course, BTSes need some attention and technicians need to check their function periodically.

ACM technicians faced a very interesting problem recently. Given a set of BTSes to visit, they needed to find the shortest path to visit all of the given points and return back to the central company building. Programmers have spent several months studying this problem but with no results. They were unable to find the solution fast enough. After a long time, one of the programmers found this problem in a conference article. Unfortunately, he found that the problem is so called "Travelling Salesman Problem" and it is very hard to solve. If we have N BTSes to be visited, we can visit them in any order, giving us N! possibilities to examine. The function expressing that number is called factorial and can be computed as a product 1.2.3.4....N. The number is very high even for a relatively small N.

The programmers understood they had no chance to solve the problem. But because they have already received the research grant from the government, they needed to continue with their studies and produce at least some results. So they started to study behaviour of the factorial function.

For example, they defined the function Z. For any positive integer N, Z(N) is the number of zeros at the end of the decimal form of number N!. They noticed that this function never decreases. If we have two numbers N1<N2, then Z(N1) <= Z(N2). It is because we can never "lose" any trailing zero by multiplying by any positive number. We can only get new and new zeros. The function Z is very interesting, so we need a computer program that can determine its value efficiently.

Input

There is a single positive integer T on the first line of input (equal to about 100000). It stands for the number of numbers to follow. Then there are T lines, each containing exactly one positive integer number N, 1 <= N <= 1000000000.

Output

For every number N, output a single line containing the single non-negative integer Z(N).

Example

Sample Input:

6
3
60
100
1024
23456
8735373

Sample Output:

0
14
24
253
5861
2183837

Added by:Adrian Kosowski
Date:2004-05-09
Time limit:6s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Prague 2000









SPOJ Problem Set (classical)

12. The Game of Master-Mind

Problem code: MMIND

If you want to buy a new cellular phone, there are many various types to choose from. To decide which one is the best for you, you have to consider several important things: its size and weight, battery capacity, WAP support, colour, price. One of the most important things is also the list of games the phone provides. Nokia is one of the most successful phone makers because of its famous Snake and Snake II. ACM wants to make and sell its own phone and they need to program several games for it. One of them is Master-Mind, the famous board logical game.

The game is played between two players. One of them chooses a secret code consisting of P ordered pins, each of them having one of the predefined set of C colours. The goal of the second player is to guess that secret sequence of colours. Some colours may not appear in the code, some colours may appear more than once.

The player makes guesses, which are formed in the same way as the secret code. After each guess, he/she is provided with an information on how successful the guess was. This feedback is called a hint. Each hint consists of B black points and W white points. The black point stands for every pin that was guessed right, i.e. the right colour was put on the right position. The white point means right colour but on the wrong position. For example, if the secret code is "white, yellow, red, blue, white" and the guess was "white, red, white, white, blue", the hint would consist of one black point (for the white on the first position) and three white points (for the other white, red and blue colours). The goal is to guess the sequence with the minimal number of hints.

The new ACM phone should have the possibility to play both roles. It can make the secret code and give hints, but it can also make its own guesses. Your goal is to write a program for the latter case, that means a program that makes Master-Mind guesses.

Input

There is a single positive integer T on the first line of input. It stands for the number of test cases to follow. Each test case describes one game situation and you are to make a guess. On the first line of each test case, there are three integer numbers, P, C and M. P ( 1 <= P <= 10) is the number of pins, C (1 <= C <= 100) is the number of colours, and M (1 <= M <= 100) is the number of already played guesses.

Then there are 2 x M lines, two lines for every guess. At the first line of each guess, there are P integer numbers representing colours of the guess. Each colour is represented by a number Gi, 1 <= Gi <= C. The second line contains two integer numbers, B and W, stating for the number of black and white points given by the corresponding hint.

Let's have a secret code S1, S2, ... SP and the guess G1, G2, ... GP. Then we can make a set H containing pairs of numbers (I,J) such that SI = GJ, and that any number can appear at most once on the first position and at most once on the second position. That means for every two different pairs from that set, (I1,J1) and (I2,J2), we have I1 <> I2 and J1 <> J2. Then we denote B(H) the number of pairs in the set, that meet the condition I = J, and W(H) the number of pairs with I <> J.

We define an ordering of every two possible sets H1 and H2. Let's say H1 <= H2 if and only if one of the following holds:

Then we can find a maximal set Hmax according to this ordering. The numbers B(Hmax) and W(Hmax) are the black and white points for that hint.

Output

For every test case, print the line containing P numbers representing P colours of the next guess. Your guess must be valid according to all previous guesses and hints. The guess is valid if the sequence could be a secret code, i.e. the sequence was not eliminated by previous guesses and hints.

If there is no valid guess possible, output the sentence You are cheating!. If there are more valid guesses, output the one that is lexicographically smallest. I.e. find such guess G that for every other valid guess V there exists such a number I that:

Example

Sample Input:

3
4 3 2
1 2 3 2
1 1
2 1 3 2
1 1
4 6 2
3 3 3 3
3 0
4 4 4 4
2 0
8 9 3
1 2 3 4 5 6 7 8
0 0
2 3 4 5 6 7 8 9
1 0
3 4 5 6 7 8 9 9
2 0

Sample Output

1 1 1 3
You are cheating!
9 9 9 9 9 9 9 9
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-05-09
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 2000









SPOJ Problem Set (classical)

13. Hotline

Problem code: HOTLINE

Every customer sometimes needs help with new and unusual products. Therefore, hotline service is very important for every company. We need a single phone number where the customer can always find a friendly voice ready to help with anything. On the other hand, many people are needed to serve as hotline operators, and human resources are always very expensive. Moreover, it is not easy to pretend "friendly voice" at 4am and explain to a drunken man that you are really unable to give him the number to House of Parliament. It was also found that some of the questions repeat very often and it is very annoying to answer them again and again.

ACM is a modern company, wanting to solve its hotline problem. They want to decrease the number of human operators by creating a complex software system that would be able to answer most common questions. The customer's voice is analysed by a special Voice Recognition Module (VRM) and converted to a plain text. The text is then taken by an Artificial Automatic Adaptive Answering Algorithm (AAAAA). The most common questions are recognised and answered automatically. The replies are then converted to a sound by Text-to-Speech Module (TTS).

You are to write the AAAAA module. Because your algorithm should be adaptive, it has no explicit knowledge base. But it must be able to listen to sentences in English and remember the mentioned facts. Whenever the question is asked about such a fact, the system has to answer it properly. The VRM and TTS modules are already implemented, so the input and output of AAAAA will be in the text form.

Input

There is a single positive integer T on the first line of input. It stands for the number of dialogues to follow. Each dialogue consists of zero or more lines, each of them containing one sentence: either statement or question. The statement ends with a dot character (.), the question ends with a question mark (?). No statement will appear more than once, however the questions can be repeated. There is one extra line after each dialogue. That line ends with an exclamation mark (!).

Sentences can contain words, spaces and punctuation characters (such as commas, colons, semicolons etc.). All words contain only letters of English alphabet and are case-sensitive. That means the same word is always written the same way, usually in lowercase. Acronyms, names and some other words can begin with capital letters. For simplicity, all sentences begin with a lowercase letter. Only if the first word should be written with a capital, the sentence begins with a capital letter. There are no unneeded spaces between words. No line will have more than 100 characters. There will be at most 100 statements per each test case.

Statements

Each statement has one of the following two forms ( _ denotes a space):
subject _predicate[s] [ _object] .
subject _don't|doesn't _predicate [ _object] .

The square brackets mark an optional part, the vertical line two possible variants. Subject is a single word, noun or pronoun in singular. Predicate is a verb (single word) denoting some activity. Object can be any text. Object does not contain any dots. Any pair "verb + object" determines unique activity. The same verb with different objects makes different independent activities, i.e. the different and independent meaning of the sentence. Sentence without any object can be considered as sentence with an empty object. The verb without an object has different and independent meaning than the same verb with any non-empty object.

The first variant of sentence denotes a positive statement. The word "predicate[s]" means verb that matches the subject of the sentence. If the subject is "I" or "you", the verb has the same form as the infinitive. With any other subject, the letter "s" is appended on the end of the verb. Assume there are no irregular verbs.

The second variant is a negative statement. Verb "don't" or "doesn't" must also match the subject. The form "don't" is used with either "I" or "you", "doesn't" is used in any other case.

A special generic subject "everybody" can be used. It means the activity holds for any subject. Other special subject is "nobody". Such sentence also holds for any subject, but its meaning is negative. Both of these generic subjects can be used with the first variant only (without "doesn't"). The sentence "nobody likes something" is exactly equal to "everybody doesn't like something", except the latter form will never occur in the input.

Questions

Each question has one of the following three forms:

1.
do|does _subject _predicate [ _object] ?
2.
who _predicates [ _object] ?
3.
what _do|does _subject do ?

The word "do|does" always matches the subject ("do I?", "do you?", "does any other subject?"). In the second type of question, predicate always matches the word "who", i.e. the "s" is always appended. Generic subjects cannot be used in questions.

Output

For each dialogue, your program must output the line Dialogue #D:, where D is the sequence number of dialogue, starting with 1. Then print exactly three lines for every question: the first line repeats the question, the second line contains the answer, and the third line is empty. Print nothing for statements. After each dialogue, print the same line with an exclamation mark that was in the input. Then print one extra empty line. Empty line contains a new-line character only.

The answer must be properly formated to be accepted by a TTS module. Only the statements appearing in the input before the answer are used for the corresponding reply. If there is any contradiction among statements, the reply is always I am abroad.. If the question and statements consider the special subject "you", it must be replaced with "I" in the answer. If the question considers special subject "I", it must be replaced with "you" in the answer. The verb must always match the subject of the sentence. The exact form of the correct answer depends on the type of question.

1. does subject predicate [object] ?

If there is any positive statement about the mentioned subject (or generic subject "everybody"), predicate and object, the answer is:
yes, _subject _predicate[s] [ _object] .

If there is any negative statement about the mentioned subject (or generic subject "nobody"), predicate and object, the answer is:
no, _subject _don't|doesn't _predicate [ _object] .

Otherwise, the answer is: maybe.

Subject in the answer is always the same subject as the subject of the question.

2. who predicates [object] ?

If there is a positive statement considering any subject, the specified predicate and object, the answer is:
subject _predicate[s] [ _object] .

If two or more subjects match the activity, replace the subject in the answer with enumeration of all such subjects, in the same order as the corresponding statements have appeared in the input. Subjects are separated with comma and space, last two subjects are separated with the word "and". If "everybody" belongs to the group of enumerated subjects, do not enumerate subjects, and print "everybody" only. If the enumeration contains at least two subjects, the predicate matches the plural subject (i.e. verb is without trailing "s"), otherwise it matches the only subject.
subject1 , _subject2 _and _subject3 predicate [ _object] .

If there is a negative statement considering the generic subject "nobody", the specified predicate and object, the answer is:
nobody _predicates [ _object] .

Otherwise, the answer is: I don't know.

3. what does subject do ?

If there are one or more sentences (both positive and negative) considering the specified subject (or a generic subject "everybody" or "nobody"), all verbs and objects from such sentences must be included in a reply in the same order as the corresponding sentences have appeared in the input. No verb-object pair can be included more than once (the eventual second appearance must be skipped). The verb-object pairs are separated by a comma followed by a space, the last verb is separated by a comma and the word "and". Please note the comma is printed here although there was no comma when separating the subjects in the previous type of answer (see above). The negative answers have the same form as the statements, that means the verb "don't" or "doesn't" is used:
subject [ _don't|doesn't] _predicate1[s] [ _object1] ,
[ _don't|doesn't] _predicate2[s] [ _object2] ,
_and [ _don't|doesn't] _predicate3[s] [ _object3] .
subject [ _don't|doesn't] _predicate1[s] [ _object1] ,
_and [ _don't|doesn't] _predicate2[s] [ _object2] .
subject [ _don't|doesn't] _predicate[s] [ _object] .

Otherwise, the answer is: I don't know.

Example

Sample Input:

1
I like hotdogs.
nobody likes to work.
everybody smiles.
what do I do?
who smiles?
what do you do?
does Joe smile?
do I like to work?
everybody hurts sometimes.
who walks there?
Michal walks there.
who walks there?
what does Michal do?
do you understand?
nobody walks there.
do you understand now?
bye!

Sample Output:

Dialogue #1:
what do I do?
you like hotdogs, don't like to work, and smile.

who smiles?
everybody smiles.

what do you do?
I don't like to work, and smile.

does Joe smile?
yes, Joe smiles.

do I like to work?
no, you don't like to work.

who walks there?
I don't know.

who walks there?
Michal walks there.

what does Michal do?
Michal doesn't like to work, smiles, hurts sometimes, and walks there.

do you understand?
maybe.

do you understand now?
I am abroad.

bye!

Added by:Adrian Kosowski
Date:2004-05-09
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 2000









SPOJ Problem Set (classical)

14. I-Keyboard

Problem code: IKEYB

Most of you have probably tried to type an SMS message on the keypad of a cellular phone. It is sometimes very annoying to write longer messages, because one key must be usually pressed several times to produce a single letter. It is due to a low number of keys on the keypad. Typical phone has twelve keys only (and maybe some other control keys that are not used for typing). Moreover, only eight keys are used for typing 26 letters of an English alphabet. The standard assignment of letters on the keypad is shown in the left picture:

1
 
2
abc
3
def
4
ghi
5
jkl
6
mno
7
pqrs
8
tuv
9
wxyz
*
 
0
space
#
 
      
1
 
2
abcd
3
efg
4
hijk
5
lm
6
nopq
7
rs
8
tuv
9
wxyz
*
 
0
space
#
 

There are 3 or 4 letters assigned to each key. If you want the first letter of any group, you press that key once. If you want the second letter, you have to press the key twice. For other letters, the key must be pressed three or four times. The authors of the keyboard did not try to optimise the layout for minimal number of keystrokes. Instead, they preferred the even distribution of letters among the keys. Unfortunately, some letters are more frequent than others. Some of these frequent letters are placed on the third or even fourth place on the standard keyboard. For example, S is a very common letter in an English alphabet, and we need four keystrokes to type it. If the assignment of characters was like in the right picture, the keyboard would be much more comfortable for typing average English texts.

ACM have decided to put an optimised version of the keyboard on its new cellular phone. Now they need a computer program that will find an optimal layout for the given letter frequency. We need to preserve alphabetical order of letters, because the user would be confused if the letters were mixed. But we can assign any number of letters to a single key.

Input

There is a single positive integer T on the first line of input (equal to about 2000). It stands for the number of test cases to follow. Each test case begins with a line containing two integers K, L (1 <= K <= L <= 90) separated by a single space. K is the number of keys, L is the number of letters to be mapped onto those keys. Then there are two lines. The first one contains exactly K characters each representing a name of one key. The second line contains exactly L characters representing names of letters of an alphabet. Keys and letters are represented by digits, letters (which are case-sensitive), or any punctuation characters (ASCII code between 33 and 126 inclusively). No two keys have the same character, no two letters are the same. However, the name of a letter can be used also as a name for a key.

After those two lines, there are exactly L lines each containing exactly one positive integer F1, F2, ... FL. These numbers determine the frequency of every letter, starting with the first one and continuing with the others sequentially. The higher number means the more common letter. No frequency will be higher than 100000.

Output

Find an optimal keyboard for each test case. Optimal keyboard is such that has the lowest "price" for typing average text. The price is determined as the sum of the prices of each letter. The price of a letter is a product of the letter frequency (Fi) and its position on the key. The order of letters cannot be changed, they must be grouped in the given order.

If there are more solutions with the same price, we will try to maximise the number of letters assigned to the last key, then to the one before the last one etc.

More formally, you are to find a sequence P1, P2, ... PL representing the position of every letter on a particular key. The sequence must meet following conditions:

The output for every test case must start with a single line saying Keypad #I:, where I is a sequential order of the test case, starting with 1. Then there must be exactly K lines, each representing one letter, in the same order that was used in input. Each line must contain the character representing the key, a colon, one space and a list of letters assigned to that particular key. Letters are not separated from each other.

Print one blank line after each test case, including the last one.

Example

Sample Input:

1
8 26
23456789
ABCDEFGHIJKLMNOPQRSTUVWXYZ
3371
589
1575
1614
6212
971
773
1904
2989
123
209
1588
1513
2996
3269
1080
121
2726
3083
4368
1334
518
752
427
733
871

Sample Output:

Keypad #1:
2: ABCD
3: EFG
4: HIJK
5: LM
6: NOPQ
7: RS
8: TUV
9: WXYZ
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-05-09
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 2000









SPOJ Problem Set (classical)

15. The Shortest Path

Problem code: SHPATH

You are given a list of cities. Each direct connection between two cities has its transportation cost (an integer bigger than 0). The goal is to find the paths of minimum cost between pairs of cities. Assume that the cost of each path (which is the sum of costs of all direct connections belongning to this path) is at most 200000. The name of a city is a string containing characters a,...,z and is at most 10 characters long.

Input

s [the number of tests <= 10]
n [the number of cities <= 10000]
NAME [city name]
p [the number of neighbours of city NAME]
nr cost [nr - index of a city connected to NAME (the index of the first city is 1)]
           [cost - the transportation cost]
r [the number of paths to find <= 100]
NAME1 NAME2 [NAME1 - source, NAME2 - destination]
[empty line separating the tests]

Output

cost [the minimum transportation cost from city NAME1 to city NAME2 (one per line)]

Example

Input:
1
4
gdansk
2
2 1
3 3
bydgoszcz
3
1 1
3 1
4 4
torun
3
1 3
2 1
4 1
warszawa
2
2 4
3 1
2
gdansk warszawa
bydgoszcz warszawa

Output:
3
2

Warning: large Input/Output data, be careful with certain languages
Added by:Darek Dereniowski
Date:2004-05-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: DASM Programming League 2003 (problemset 11)









SPOJ Problem Set (classical)

16. Sphere in a tetrahedron

Problem code: TETRA

Of course a Sphere Online Judge System is bound to have some tasks about spheres. So here is one. Given the lengths of the edges of a tetrahedron calculate the radius of a sphere inscribed in that tetrahedron (i.e. a sphere tangent to all the faces).

Input

Number N of test cases in a single line. ( N <= 30 ) Each of the next N lines consists of 6 integer numbers -- the lengths of the edges of a tetrahedron separated by single spaces. The edges are not longer than 1000 and for the tetrahedron WXYZ, the order of the edges is: WX, WY, WZ, XY, XZ, YZ.

Output

N lines, each consisting of a real number given with four digits decimal precision equal to the radius of a sphere inscribed in the given tetrahedron.

Example

Input:
2
1 1 1 1 1 1
1000 999 998 5 5 6

Output:
0.2041
1.4189


Added by:Adam Dzedzej
Date:2004-05-11
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

17. The Bytelandian Cryptographer (Act I)

Problem code: CRYPTO1

The infamous Bytelandian Bit-eating Fanatic Organisation (BBFO for short) plans to launch an all-out denial-of-service attack on the Bytelandian McDecimal's fast food network by blocking the entrance to every restaurant with a camel (the purpose being to rid the Organisation of unhealthy competition, obviously). In a sly and perfidious move, the head cryptographer of BBFO decided to disclose the date and time of the planned attack to the management of McDecimal's, but in encrypted form (ha ha). He calculated the number of seconds from midnight 1970.01.01 GMT to the moment of attack, squared it, divided it by 4000000007 and sent the remainder by e-mail to McDecimal's. This made the original date impossible to decode.

Or did it?

*   *   *

You work as the head algorthimist at McDecimal's HQ and know nothing of what is happening in Byteland. Things are not going well. You are playing a quiet game of hearts against your computer and wondering why on earth Management are considering making you redundant. Suddenly, the CEO bursts into your office, saying:

- Look here, young man[lady]! I have this number and those guys claim it is supposed to be some date. I am giving you one second to tell me what it all means!

I am afraid you have no choice. You can't ask any further questions.
You just have to answer, now.

Input

The encrypted timestamp.

Output

The decrypted GMT time and date of attack, somewhere between 1970 and 2030, using standard 26 character formatting.

Example

Input:
1749870067

Output:
Sun Jun 13 16:20:39 2004


Added by:Adrian Kosowski
Date:2004-05-13
Time limit:1s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:;)









SPOJ Problem Set (classical)

18. The Bytelandian Cryptographer (Act II)

Problem code: CRYPTO2

Encouraged by his last successful exploit, the Bytelandian fanatic cryptographer impudently encrypted a three-digit number by subtracting 1 from it.

This time he has really overstepped the mark! Soldier, go and beat him, for Burger King & Country! Oh, and remember your good manners, use Brainf**k (no other language is allowed).

Input

An encrypted 3-digit positive integer.

Output

The decrypted value.

Example

Input:
699

Output:

700

Added by:Adrian Kosowski
Date:2004-05-28
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:BF
Resource:Sometimes the simplest language is the most pleasing.









SPOJ Problem Set (classical)

19. The Bytelandian Cryptographer (Act III)

Problem code: CRYPTO3

The Bytelandian cryptographer acknowledged he was sorely beaten in Act 2. He renounced his own methods of encryption and decided to return to the classic techniques.

Not knowing what to do next, he went to the cinema to chew the problem over. To his surprise, he found that the cone containing pop-corn was in fact a rolled up page torn from the classic book, RSA for newbies in 24 seconds. The page in question contained the entire key-generating and encryption algorithm. Fascinated, he thought up two different prime numbers p and q, and calculated his own public key, and revealed the product p*q to the wide world. Then, he began work on his wicked scheme of encryption.

History repeats. Once more, you receive an encrypted message from the cryptographer. This time you know that without additional information you are beaten, so you decide to use the psychological approach. You phone the Bytelandian cryptographer, and ask him whether he couldn't give you a little hint. What you really want to know is the number u of positive integers which are smaller than p*q and have no common factors with p*q other than 1. But the cryptographer, sensing that this would allow you to decode the message right away, refuses to tell you this number. Eventually, after a lot of asking, he gives you a piece of utterly useless information: he tells you how many positive integers x cannot be represented in the form x=a*p+b*q, regardless of what non-negative integer values a and b assume.

You begin to wonder whether the information you received from the cryptographer is not by any chance enough to find the value of u.
Even if the only languages at your disposal are Brainf**k and Intercal...

Input

The number provided by the cryptographer (a positive integer of at most 99 decimal digits). The input ends with a new line symbol.

Output

The value of u.

Example

Input:
1

Output:
2
(This example is possible for p=2, q=3)

Added by:Adrian Kosowski
Date:2004-05-29
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:BF ICK
Resource:Sadly, the ability to make a simple problem difficult to understand is seldom considered a talent.









SPOJ Problem Set (classical)

20. The Bytelandian Cryptographer (Act IV)

Problem code: CRYPTO4

The Bytelandian Cryptographer has been requested by the BBFO to put forward an ecryption scheme which would allow the BBFO to communicate with its foreign associates. After some intensive studies, he has decided upon the Vigenére cipher. Messages written using 26 upper case characters of the Latin alphabet: A, B, ..., Z which are interpreted as integers 0,1, ..., 25 respectively. The secret cypher for transmitting a message is known to both sides and consists of n integers k1, k2,...,kn. Using this cypher, the i-th number xi of the input message x is encrypted to the form of the i-th number of the output message y, as follows:
yi =(xi+k1+ ((i-1) mod n)) mod 26.

You are trying to find out the content of a message transmitted by the BBFO. By a lucky stroke of fortune, your spys managed to intercept the message in both its plaintext and encrypted form (x and y respectively). Unfortunately, during their dramatic escape the files they were carrying where pierced by bullets and fragments of messages x and y were inadvertantly lost. Or were they? It is your task to reconstruct as much of message x as you possibly can.

Input

The first line of input contains a single integer t<=200 denoting the number of test cases. t test case descriptions follow.

For each test case, the first line contains one integer m which is some upper bound on the length of the cypher (1<=n<=m<=100000). The second line of input contains the original message x, while the third line contains the encrypted message y. The messages are expressed using characters 'A'-'Z' (interpreted as integers 0-25) and '*' (denoting a single character illegible due to damage). The total length of the input file is not more than 2MB.

Output

For each test case output a single line containing the original message x, with asterisks '*' in place of only those characters whose value cannot be determined.

Example

Input:
4
1
A*X*C
**CM*
4
*B***A
AAAAAA
6
*B***A
AAAAAA
4
*AA*******
AAAAAAAAAA

Output:
A*XHC
*BA*BA
*B***A
*AA**A****
Warning: large Input/Output data, be careful with certain languages.
The time limit is strict for this problem.

Added by:Konrad Piwakowski
Date:2004-11-16
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004 (problemset 3)









SPOJ Problem Set (classical)

22. Triangle From Centroid

Problem code: TRICENTR

Given the length of side a of a triangle and the distances from the centroid (the point of concurrence of the medians - red in the picture) to all sides: a, b and c, calculate this triangle's area and the distance (blue line) from the orthocenter (the point of concurrence of the heights - green in the picture) to the centroid.

Input

In the first line integer n - the number of test cases (equal to about 1000). The next n lines - 4 floating point values: the length of side a, and distances from the centroid to sides a, b and c.

Output

n lines consisting of 2 floating point values with 3 digits after the decimal point: the area of the triangle and the distance from the orthocenter to centroid.

Example

Input:
2
3.0 0.8660254038 0.8660254038 0.8660254038
657.8256599140 151.6154399062 213.5392629932 139.4878846649

Output:
3.897 0.000
149604.790 150.275


Added by:Patryk Pomykalski
Date:2004-05-22
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

23. Pyramids

Problem code: PIR

Recently in Farland, a country in Asia, the famous scientist Mr. Log Archeo discovered ancient pyramids. But unlike those in Egypt and Central America, they have a triangular (not rectangular) foundation. That is, they are tetrahedrons in the mathematical sense. In order to find out some important facts about the early society of the country (it is widely believed that the pyramid sizes are closely connected with Farland's ancient calendar), Mr. Archeo needs to know the volume of the pyramids. Unluckily, he has reliable data about their edge lengths only. Please, help him!

Input

t [number of tests to follow] In each of the next t lines six positive integer numbers not exceeding 1000 separated by spaces (each number is one of the edge lengths of the pyramid ABCD). The order of the edges is the following: AB, AC, AD, BC, BD, CD.

Output

For each test output a real number - the volume, printed accurate to four digits after decimal point.

Example

Input:

2 1 1 1 1 1 1 1000 1000 1000 3 4 5

Output:

0.1179 1999.9937


Added by:Adam Dzedzej
Date:2004-05-14
Time limit:1s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM ICPC 2002-2003 NEERC, Northern Subregion









SPOJ Problem Set (classical)

24. Small factorials

Problem code: FCTRL2

You are asked to calculate factorials of some small positive integers.

Input

An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.

Output

For each integer n given at input, display a line with the value of n!

Example

Sample input:
4
1
2
5
3

Sample output:

1
2
120
6

Added by:Adrian Kosowski
Date:2004-05-28
Time limit:1s
Source limit:2000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All









SPOJ Problem Set (classical)

25. Pouring water

Problem code: POUR1

Given two vessels, one of which can accommodate a litres of water and the other - b litres of water, determine the number of steps required to obtain exactly c litres of water in one of the vessels.

At the beginning both vessels are empty. The following operations are counted as 'steps':

Input

An integer t, 1<=t<=100, denoting the number of testcases, followed by t sets of input data, each consisting of three positive integers a, b, c, not larger than 40000, given in separate lines.

Output

For each set of input data, output the minimum number of steps required to obtain c litres, or -1 if this is impossible.

Example

Sample input:
2
5
2
3
2
3
4

Sample output:
2
-1

Added by:Adrian Kosowski
Date:2004-05-31
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:An ancient problem, formulated in these words by Mr Tadeusz Ratajczak









SPOJ Problem Set (classical)

26. Build the Fence

Problem code: BSHEEP

At the beginning of spring all the sheep move to the higher pastures in the mountains. If there are thousands of them, it is well worthwhile gathering them together in one place. But sheep don't like to leave their grass-lands. Help the shepherd and build him a fence which would surround all the sheep. The fence should have the smallest possible length! Assume that sheep are negligibly small and that they are not moving. Sometimes a few sheep are standing in the same place. If there is only one sheep, it is probably dying, so no fence is needed at all...

Input


t [the number of tests <= 100]
[empty line]
n [the number of sheep <= 100000]
x1 y1 [coordinates of the first sheep]
...
xn yn
[integer coordinates from -10000 to 10000]
[empty line]
[other lists of sheep]

Text grouped in [ ] does not appear in the input file. Assume that sheep are numbered in the input order.

Output


o [length of circumference, 2 digits precision]
p1 p2 ... pk
[the sheep that are standing in the corners of the fence; the first one should be positioned bottommost and as far to the left as possible, the others ought to be written in anticlockwise order; ignore all sheep standing in the same place but the first to appear in the input file; the number of sheep should be the smallest possible]
[empty line]
[next solutions]

Example

Input:
8

5
0 0
0 5
10 5
3 3
10 0

1
0 0

3
0 0
1 0
2 0

4
0 0
0 0
0 1
1 0

3
0 0
0 1
1 0

6
0 0
-1 -1
1 1
2 2
3 3
4 4

2
10 0
0 0

7
-3 -4
2 -3
4 3
-4 2
0 5
2 -3
-1 4

Output:
30.00
1 5 3 2

0.00
1

4.00
1 3

3.41
1 4 3

3.41
1 3 2

14.14
2 6

20.00
2 1

26.98
1 2 3 5 4

Warning: large Input/Output data, be careful with certain languages
Added by:Micha³ Ma³afiejski
Date:2004-06-01
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:-









SPOJ Problem Set (classical)

27. Sorting Bank Accounts

Problem code: SBANK

In one of the internet banks thousands of operations are being performed every day. Since certain customers do business more actively than others, some of the bank accounts occur many times in the list of operations. Your task is to sort the bank account numbers in ascending order. If an account appears twice or more in the list, write the number of repetitions just after the account number. The format of accounts is as follows: 2 control digits, an 8-digit code of the bank, 16 digits identifying the owner (written in groups of four digits), for example (at the end of each line there is exactly one space):
30 10103538 2222 1233 6160 0142 

Banks are real-time institutions and they need FAST solutions. If you feel you can meet the challenge within a very stringent time limit, go ahead! A well designed sorting algorithm in a fast language is likely to succeed.

Input


t [the number of tests <= 5]
n [the number of accounts<= 100 000]
[list of accounts]
[empty line]
[next test cases]

Output


[sorted list of accounts with the number of repeated accounts]
[empty line]
[other results]

Example

Input:
2
6
03 10103538 2222 1233 6160 0142 
03 10103538 2222 1233 6160 0141 
30 10103538 2222 1233 6160 0141 
30 10103538 2222 1233 6160 0142 
30 10103538 2222 1233 6160 0141 
30 10103538 2222 1233 6160 0142 

5
30 10103538 2222 1233 6160 0144 
30 10103538 2222 1233 6160 0142 
30 10103538 2222 1233 6160 0145 
30 10103538 2222 1233 6160 0146 
30 10103538 2222 1233 6160 0143 

Output:
03 10103538 2222 1233 6160 0141 1
03 10103538 2222 1233 6160 0142 1
30 10103538 2222 1233 6160 0141 2
30 10103538 2222 1233 6160 0142 2

30 10103538 2222 1233 6160 0142 1
30 10103538 2222 1233 6160 0143 1
30 10103538 2222 1233 6160 0144 1
30 10103538 2222 1233 6160 0145 1
30 10103538 2222 1233 6160 0146 1

Added by:Micha³ Ma³afiejski
Date:2004-06-01
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:-









SPOJ Problem Set (classical)

28. Help the Military Recruitment Office!

Problem code: HMRO

At the end of year 2004, the regional agencies of the Polish Military Recruitment Office (known as WKU in Polish) is sending a call to all boys born in 1984. Every recruit has his personal 11-digit identification number (PESEL, format: YYMMDDXXXXX, where YYMMDD is the date of birth, and XXXXX is a zero-padded integer smaller than 100000). Every agency of the Military Recruitment Office has its own code (MRO, format: a place code consisting of 3 upper case letters and a one-digit number). But this year the army underwent some reforms and not all boys at conscription age are going to be recruited. The list of closed down MRO points is as follows: the code of the closed down MRO is followed by the code of some other MRO, to which all the recruits are now going to be assigned. The list of recruits contains their PESEL codes. Your task is to prepare the complete list of recruits and determine the codes of their new MRO-s.

Input

s [the number of tests <= 10]
p [the number of boys at conscription age <= 100000]
PESEL and MRO code
z [the number of closed down MRO points <= 100000]
old_code new_code [old_code - the code of closed down MRO,
new_code - its new MRO code]
p [the number of recruits <= 100000]
PESEL [PESEL code of recruit]
[empty line]
[next tests]

Output

one PESEL and MRO code per line in the order of input
[empty line between tests]
[other results]

Example

Input:
1
4
84101011111 GDA1
84010122222 GDA2
84010233333 GDA2
84020255555 GDY1
1
GDA2 GDA1
3
84101011111
84010122222
84020255555

Output:
84101011111 GDA1
84010122222 GDA1
84020255555 GDY1

Warning: large Input/Output data, be careful with certain languages
Added by:Micha³ Ma³afiejski
Date:2004-06-01
Time limit:30s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:-









SPOJ Problem Set (classical)

29. Hash it!

Problem code: HASHIT

Your task is to calculate the result of the hashing process in a table of 101 elements, containing keys that are strings of length at most 15 letters (ASCII codes 'A',...,'z'). Implement the following operations:

When performing find, insert and delete operations define the following function:
integer Hash(string key),
which for a string key=a1...an returns the value:
Hash(key)=h(key) mod 101, where
h(key)=19 *(ASCII(a1)*1+...+ASCII(an)*n).
Resolve collisions using the open addressing method, i.e. try to insert the key into the table at the first free position: (Hash(key)+j2+23*j) mod 101, for j=1,...,19. After examining of at least 20 table entries, we assume that the insert operation cannot be performed.

Input


t [the number of test cases <= 100]
n1 [the number of operations (one per line)[<= 1000]
ADD:string
[or]
DEL:string [other test cases, without empty lines betwee series]

Output

For every test case you have to create a new table, insert or delete keys, and write to the output:
the number of keys in the table [first line]
index:key [sorted by indices]

Example

Input:
1
11
ADD:marsz
ADD:marsz
ADD:Dabrowski
ADD:z
ADD:ziemii
ADD:wloskiej
ADD:do
ADD:Polski
DEL:od
DEL:do
DEL:wloskiej


Output:
5
34:Dabrowski
46:Polski
63:marsz
76:ziemii
96:z


Added by:Micha³ Ma³afiejski
Date:2004-06-01
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:-









SPOJ Problem Set (classical)

30. Bytelandian Blingors Network

Problem code: BLINNET

We have discovered the fastest communication medium Bytelandian scientists announced, and they called it blingors. The blingors are incomparably better than other media known before. Many companies in Byteland started to build blingors networks, so the information society in the kingdom of Bytes is fact! The priority is to build the core of the blingors network, joinig main cities in the country. Assume there is some number of cities that will be connected at the beginning. The cost of building blingors connection between two cities depends on many elements, but it has been successfully estimated. Your task is to design the blingors network connections between some cities in this way that between any pair of cities is a communication route. The cost of this network should be as small as possible.

Remarks

Input


s [number of test cases <= 10] n [number of cities <= 10 000] NAME [city name] p [number of neigbouring cities to the city NAME] neigh cost [neigh - the unique number of city from the main list cost - the cost of building the blingors connection from NAME to neigh] [empty line between test cases]

Output

[separate lines] cost [the minimum cost of building the blingors network]

Example

Input:
2

4
gdansk
2
2 1
3 3
bydgoszcz
3
1 1
3 1
4 4
torun
3
1 3
2 1
4 1
warszawa
2
2 4
3 1

3
ixowo
2
2 1
3 3
iyekowo
2
1 1
3 7
zetowo
2
1 3 
2 7


Output:
3
4
Warning: large Input/Output data, be careful with certain languages
Added by:£ukasz Kuszner
Date:2004-06-01
Time limit:4s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:PAL









SPOJ Problem Set (classical)

31. Fast Multiplication

Problem code: MUL


Multiply the given numbers.

Input

 

n [the number of multiplications <= 1000]
l1 l2 [numbers to multiply (at most 10000 decimal digits each)]

Text grouped in [ ] does not appear in the input file.

 

Output

 

The results of multiplications.

 

Example

Input:
5
4 2
123 43
324 342
0 12
9999 12345

Output:
8
5289
110808
0
123437655

Warning: large Input/Output data, be careful with certain languages


Added by:Darek Dereniowski
Date:2004-06-01
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:PAL









SPOJ Problem Set (classical)

32. A Needle in the Haystack

Problem code: NHAY

Write a program that finds all occurences of a given pattern in a given input string. This is often referred to as finding a needle in a haystack.

The program has to detect all occurences of the needle in the haystack. It should take the needle and the haystack as input, and output the positions of each occurence, as shown below. The suggested implementation is the KMP algorithm, but this is not a requirement. However, a naive approach will probably exceed the time limit, whereas other algorithms are more complicated... The choice is yours.

Input

The input consists of a number of test cases. Each test case is composed of three lines, containing:

The length of the needle is only limited by the memory available to your program, so do not make any assumptions - instead, read the length and allocate memory as needed. The haystack is not limited in size, which implies that your program should not read the whole haystack at once. The KMP algorithm is stream-based, i.e. it processes the haystack character by character, so this is not a problem.

The test cases come one after another, each occupying three lines, with no additional space or line breaks in between.

Output

For each test case your program should output all positions of the needle's occurences within the haystack. If a match is found, the output should contain the position of the first character of the match. Characters in the haystack are numbered starting with zero.

For a given test case, the positions output should be sorted in ascending order, and each of these should be printed in a separate line. For two different test cases, the positions should be separated by an empty line.

Example

Sample input:
2 na banananobano 6 foobar foo 9 foobarfoo barfoobarfoobarfoobarfoobarfoo

Sample output:

2
4

3
9
15
21

Note the double empty line in the output, which means that no match was found for the second test case.

Warning: large Input/Output data, be careful with certain languages
Added by:Micha³ Ma³afiejski
Date:2004-06-03
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:the problem was phrased and test data was supplied by Mr. Maciej 'hawk' Jarzêbski









SPOJ Problem Set (classical)

33. Trip

Problem code: TRIP

Alice and Bob want to go on holiday. Each of them has drawn up a list of cities to be visited in turn. A list may contain a city more than once. As they want to travel together, they have to agree upon a common route. No one wants to change the order of the cities on his list or add other cities. Therefore they have no choice but to remove some cities from the list. Of course the common route is to involve as much sight-seeing in cities as possible. There are exactly 26 cities in the region. Therefore they are encoded on the lists as lower case letters from 'a' to 'z'.

Input

The first line of input contains a number T <= 10 that indicates the number of test cases to follow. Each test case consists of two lines; the first line is the list of Alice, the second line is the list of Bob. Each list consists of 1 to 80 lower case letters.

Output

The output for each test case should contain all different trips exactly once that meet the conditions described above. There is at least one such trip, but never more than 1000 different ones. You should order the trips in lexicographic order. Print one blank line between the output of different test cases.

Example

Input

1
abcabcaa
acbacba

Output

ababa
abaca
abcba
acaba
acaca
acbaa
acbca

Added by:Adrian Kuegel
Date:2004-06-05
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:own problem, used in CEOI 2003









SPOJ Problem Set (classical)

34. Run Away

Problem code: RUNAWAY

One of the traps we will encounter in the Pyramid is located in the Large Room. A lot of small holes are drilled into the floor. They look completely harmless at the first sight. But when activated, they start to throw out very hot java, uh ... pardon, lava. Unfortunately, all known paths to the Center Room (where the Sarcophagus is) contain a trigger that activates the trap. The ACM were not able to avoid that. But they have carefully monitored the positions of all the holes. So it is important to find the place in the Large Room that has the maximal distance from all the holes. This place is the safest in the entire room and the archaeologist has to hide there.

Input

The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing three integers X, Y, M separated by space. The numbers satisfy conditions: 1 <= X,Y <=10000, 1 <= M <= 1000. The numbers X and Yindicate the dimensions of the Large Room which has a rectangular shape. The number M stands for the number of holes. Then exactly M lines follow, each containing two integer numbers Ui and Vi (0 <= Ui <= X, 0 <= Vi <= Y) indicating the coordinates of one hole. There may be several holes at the same position.

Output

Print exactly one line for each test case. The line should contain the sentence "The safest point is (P, Q)." where P and Qare the coordinates of the point in the room that has the maximum distance from the nearest hole, rounded to the nearest number with exactly one digit after the decimal point (0.05 rounds up to 0.1).

Example

Sample Input:
3
1000 50 1
10 10
100 100 4
10 10
10 90
90 10
90 90
3000 3000 4
1200 85
63 2500
2700 2650 
2990 100

Sample output:
The safest point is (1000.0, 50.0).
The safest point is (50.0, 50.0).
The safest point is (1433.0, 1669.8).

Added by:Adrian Kosowski
Date:2004-06-06
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1999









SPOJ Problem Set (classical)

35. Equipment Box

Problem code: EQBOX

There is a large room in the Pyramid called Room-of-No-Return. Its floor is covered by rectangular tiles of equal size. The name of the room was chosen because of the very high number of traps and mechanisms in it. The ACM group has spent several years studying the secret plan of this room. It has made a clever plan to avoid all the traps. A specially trained mechanic was sent to deactivate the most feared trap called Shattered Bones. After deactivating the trap the mechanic had to escape from the room. It is very important to step on the center of the tiles only; he must not touch the edges. One wrong step and a large rock falls from the ceiling squashing the mechanic like a pancake. After deactivating the trap, he realized a horrible thing: the ACM plan did not take his equipment box into consideration. The box must be laid onto the ground because the mechanic must have both hands free to prevent contact with other traps. But when the box is laid on the ground, it could touch the line separating the tiles. And this is the main problem you are to solve.

Input

The input consists of T test cases (T is equal to about 10000). The number of them (T) is given on the first line of the input file. Each test case consists of a single line. The line contains exactly four integer numbers separated by spaces: A, B, X and Y. A and Bindicate the dimensions of the tiles, X and Y are the dimensions of the equipment box (1 <= A,B,X,Y <= 50000).

Output

Your task is to determine whether it is possible to put the box on a single tile -- that is, if the whole box fits on a single tile without touching its border. If so, you are to print one line with the sentence "Escape is possible.". Otherwise print the sentence "Box cannot be dropped.".

Example

Sample Input:

2
10 10 8 8
8 8 10 10

Sample output:

Escape is possible.
Box cannot be dropped.
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1999









SPOJ Problem Set (classical)

36. Secret Code

Problem code: CODE1

The Sarcophagus itself is locked by a secret numerical code. When somebody wants to open it, he must know the code and set it exactly on the top of the Sarcophagus. A very intricate mechanism then opens the cover. If an incorrect code is entered, the tickets inside would catch fire immediately and they would have been lost forever. The code (consisting of up to 100 integers) was hidden in the Alexandrian Library but unfortunately, as you probably know, the library burned down completely.

But an almost unknown archaeologist has obtained a copy of the code something during the 18th century. He was afraid that the code could get to the ``wrong people'' so he has encoded the numbers in a very special way. He took a random complex number B that was greater (in absolute value) than any of the encoded numbers. Then he counted the numbers as the digits of the system with basis B. That means the sequence of numbers an, an-1, ..., a1, a0 was encoded as the number X = a0 + a1B + a2B2 + ...+ anBn.

Your goal is to decrypt the secret code, i.e. to express a given number X in the number system to the base B. In other words, given the numbers X and Byou are to determine the ``digit'' a0 through an.

Input

The input consists of T test cases (equal to about 100000). The number of them (T) is given on the first line of the input file. Each test case consists of one single line containing four integer numbers Xr, Xi, Br, Bi (|Xr|,|Xi| <= 1000000, |Br|,|Bi| <= 16). These numbers indicate the real and complex components of numbers X and B, i.e. X = Xr + i.Xi, B = Br + i.Bi. B is the basis of the system (|B| > 1), X is the number you have to express.

Output

Your program must output a single line for each test case. The line should contain the ``digits'' an, an-1, ..., a1, a0, separated by commas. The following conditions must be satisfied:

If there are no numbers meeting these criteria, output the sentence "The code cannot be decrypted.". If there are more possibilities, print any of them.

Example

Sample Input

4
-935 2475 -11 -15
1 0 -3 -2
93 16 3 2
191 -192 11 -12

Sample output:

8,11,18
1
The code cannot be decrypted.
16,15
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1999









SPOJ Problem Set (classical)

37. The Proper Key

Problem code: PROPKEY

Many people think that Tetris was invented by two Russian programmers. But that is not the whole truth. The idea of the game is very old -- even the Egyptians had something similar. But they did not use it as a game. Instead, it was used as a very complicated lock. The lock was made of wood and consisted of a large number of square fields, laid out in regular rows and columns. Each field was either completely filled with wood, or empty. The key for this lock was two-dimensional and it was made by joining square parts of the same size as the fields of the lock. So they had a 2D lock and 2D key that could be inserted into the lock from the top. The key was designed so that it was not possible to move it upwards. It could only fall down and it could slide sideways -- exactly like in a Tetris game. The only difference is that the key could not be rotated. Rotation in Tetris is really a Russian invention.

The entry gate into the Pyramid has such a lock. The ACM archaeologists have found several keys and one of them belongs to the lock with a very high probability. Now they need to try them out and find which one to use. Because it is too time-consuming to try all of them, it is better to begin with those keys that may be inserted deeper into the lock. Your program should be able to determine how deep a given key can be inserted into a given lock.

Input

The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing two integers R and C (1 <= R,C <= 100) indicating the key size. Then exactly R rows follow, each containing C characters. Each character is either a hash mark (#) or a period (.). A hash mark represents one square field made of wood; a period is an empty field. The wooden fields are always connected, i.e. the whole key is made of one piece. Moreover, the key remains connected even if we cut off arbitrary number of rows from its top. There is always at least one non-empty field in the top-most and bottom-most rows and the left-most and right-most columns.

After the key description, there is a line containing two integers D and W (1 <= D <= 10000, 1 <= W <= 1000). The number W is the lock width, and D is its depth. The next D lines contain W characters each. The character may be either a hash mark (representing the wood) or a period (the free space).

Output

Your program should print one line of output for each test case. The line should contain the statement "The key falls to depth X.". Replace X with the maximum depth to which the key can be inserted by moving it down and sliding it to the left or right only. The depth is measured as the distance between the bottom side of the key and the top side of the lock. If it is possible to move the key through the whole lock and take it away at the bottom side, output the sentence "The key can fall through.".

Example

Sample Input:

4
2 4
#.##
###.
3 6
#....#
#....#
#..###
2 3
##.
.##
2 7
#.#.#.#
.#.#.#.
1 1
#
1 10
###....###
3 2
##
.#
.#
1 5
#.#.#


Sample output:

The key falls to depth 2.
The key falls to depth 0.
The key can fall through.
The key falls to depth 2.
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1999









SPOJ Problem Set (classical)

38. Labyrinth

Problem code: LABYR1

The northern part of the Pyramid contains a very large and complicated labyrinth. The labyrinth is divided into square blocks, each of them either filled by rock, or free. There is also a little hook on the floor in the center of every free block. The ACM have found that two of the hooks must be connected by a rope that runs through the hooks in every block on the path between the connected ones. When the rope is fastened, a secret door opens. The problem is that we do not know which hooks to connect. That means also that the neccessary length of the rope is unknown. Your task is to determine the maximum length of the rope we could need for a given labyrinth.

Input

The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing two integers C and R (3 <= C,R <= 1000) indicating the number of columns and rows. Then exactly R lines follow, each containing C characters. These characters specify the labyrinth. Each of them is either a hash mark (#) or a period (.). Hash marks represent rocks, periods are free blocks. It is possible to walk between neighbouring blocks only, where neighbouring blocks are blocks sharing a common side. We cannot walk diagonally and we cannot step out of the labyrinth.

The labyrinth is designed in such a way that there is exactly one path between any two free blocks. Consequently, if we find the proper hooks to connect, it is easy to find the right path connecting them.

Output

Your program must print exactly one line of output for each test case. The line must contain the sentence "Maximum rope length is X." where Xis the length of the longest path between any two free blocks, measured in blocks.

Example

Sample Input:

2
3 3
###
#.#
###
7 6
#######
#.#.###
#.#.###
#.#.#.#
#.....#
#######


Sample output:

Maximum rope length is 0.
Maximum rope length is 8.
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1999









SPOJ Problem Set ()

39. Piggy-Bank

Problem code: PIGBANK

Before ACM can do anything, a budget must be prepared and the necessary financial support obtained. The main income for this action comes from Irreversibly Bound Money (IBM). The idea behind is simple. Whenever some ACM member has any small money, he takes all the coins and throws them into a piggy-bank. You know that this process is irreversible, the coins cannot be removed without breaking the pig. After a sufficiently long time, there should be enough cash in the piggy-bank to pay everything that needs to be paid.

But there is a big problem with piggy-banks. It is not possible to determine how much money is inside. So we might break the pig into pieces only to find out that there is not enough money. Clearly, we want to avoid this unpleasant situation. The only possibility is to weigh the piggy-bank and try to guess how many coins are inside. Assume that we are able to determine the weight of the pig exactly and that we know the weights of all coins of a given currency. Then there is some minimum amount of money in the piggy-bank that we can guarantee. Your task is to find out this worst case and determine the minimum amount of cash inside the piggy-bank. We need your help. No more prematurely broken pigs!

Input

The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing two integers E and F. They indicate the weight of an empty pig and of the pig filled with coins. Both weights are given in grams. No pig will weigh more than 10 kg, that means 1 <= E <= F <= 10000. On the second line of each test case, there is an integer number N (1 <= N <= 500) that gives the number of various coins used in the given currency. Following this are exactly N lines, each specifying one coin type. These lines contain two integers each, Pand W (1 <= P <= 50000, 1 <= W <=10000). P is the value of the coin in monetary units, W is it's weight in grams.

Output

Print exactly one line of output for each test case. The line must contain the sentence "The minimum amount of money in the piggy-bank is X." where X is the minimum amount of money that can be achieved using coins with the given total weight. If the weight cannot be reached exactly, print a line "This is impossible.".

Example

Sample Input:

3
10 110
2
1 1
30 50
10 110
2
1 1
50 30
1 6
2
10 3
20 4

Sample output:

The minimum amount of money in the piggy-bank is 60.
The minimum amount of money in the piggy-bank is 100.
This is impossible.

Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1999









SPOJ Problem Set (classical)

40. Lifting the Stone

Problem code: STONE

There are many secret openings in the floor which are covered by a big heavy stone. When the stone is lifted up, a special mechanism detects this and activates poisoned arrows that are shot near the opening. The only possibility is to lift the stone very slowly and carefully. The ACM team must connect a rope to the stone and then lift it using a pulley. Moreover, the stone must be lifted all at once; no side can rise before another. So it is very important to find the centre of gravity and connect the rope exactly to that point. The stone has a polygonal shape and its height is the same throughout the whole polygonal area. Your task is to find the centre of gravity for the given polygon.

Input

The input consists of T test cases (equal to about 500). The number of them (T) is given on the first line of the input file. Each test case begins with a line containing a single integer N (3 <= N <= 1000000) indicating the number of points that form the polygon. This is followed by N lines, each containing two integers Xi and Yi (|Xi|, |Yi| <= 20000). These numbers are the coordinates of the i-th point. When we connect the points in the given order, we get a polygon. You may assume that the edges never touch each other (except the neighbouring ones) and that they never cross. The area of the polygon is never zero, i.e. it cannot collapse into a single line.

Output

Print exactly one line for each test case. The line should contain exactly two numbers separated by one space. These numbers are the coordinates of the centre of gravity. Round the coordinates to the nearest number with exactly two digits after the decimal point (0.005 rounds up to 0.01). Note that the centre of gravity may be outside the polygon, if its shape is not convex. If there is such a case in the input data, print the centre anyway.

Example


Sample Input:
2
4
5 0
0 5
-5 0
0 -5
4
1 1
11 1
11 11
1 11

Sample output:

0.00 0.00
6.00 6.00

Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1999









SPOJ Problem Set (medium)

41. Play on Words

Problem code: WORDS1

Some of the secret doors contain a very interesting word puzzle. The team of archaeologists has to solve it to open that doors. Because there is no other way to open the doors, the puzzle is very important for us.

There is a large number of magnetic plates on every door. Every plate has one word written on it. The plates must be arranged into a sequence in such a way that every word begins with the same letter as the previous word ends. For example, the word ``acm'' can be followed by the word ``motorola''. Your task is to write a computer program that will read the list of words and determine whether it is possible to arrange all of the plates in a sequence (according to the given rule) and consequently to open the door.

Input

The input consists of T test cases. The number of them (T, equal to about 500) is given on the first line of the input file. Each test case begins with a line containing a single integer number N that indicates the number of plates (1 <= N <= 100000). Then exactly Nlines follow, each containing a single word. Each word contains at least two and at most 1000 lowercase characters, that means only letters 'a' through 'z' will appear in the word. The same word may appear several times in the list.

Output

Your program has to determine whether it is possible to arrange all the plates in a sequence such that the first letter of each word is equal to the last letter of the previous word. All the plates from the list must be used, each exactly once. The words mentioned several times must be used that number of times.

If there exists such an ordering of plates, your program should print the sentence "Ordering is possible.". Otherwise, output the sentence "The door cannot be opened.".

Example

Sample input:

3
2
acm
ibm
3
acm
malform
mouse
2
ok
ok


Sample output:

The door cannot be opened.
Ordering is possible.
The door cannot be opened.
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-06
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PAS fpc PAS gpc PYTH 3.2.3 n
Resource:ACM Central European Programming Contest, Prague 1999









SPOJ Problem Set (classical)

42. Adding Reversed Numbers

Problem code: ADDREV

The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.

Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros.

ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).

Input

The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.

Output

For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.

Example

Sample input: 

3
24 1
4358 754
305 794

Sample output:

34
1998
1

Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1998









SPOJ Problem Set (classical)

43. Copying Books

Problem code: BOOKS1

Before the invention of book-printing, it was very hard to make a copy of a book. All the contents had to be re-written by hand by so called scribers. The scriber had been given a book and after several months he finished its copy. One of the most famous scribers lived in the 15th century and his name was Xaverius Endricus Remius Ontius Xendrianus (Xerox). Anyway, the work was very annoying and boring. And the only way to speed it up was to hire more scribers.

Once upon a time, there was a theater ensemble that wanted to play famous Antique Tragedies. The scripts of these plays were divided into many books and actors needed more copies of them, of course. So they hired many scribers to make copies of these books. Imagine you have m books (numbered 1, 2 ... m) that may have different number of pages (p1, p2 ... pm) and you want to make one copy of each of them. Your task is to divide these books among k scribes, k <= m. Each book can be assigned to a single scriber only, and every scriber must get a continuous sequence of books. That means, there exists an increasing succession of numbers 0 = b0 < b1 < b2, ... < bk-1 <= bk = m such that i-th scriber gets a sequence of books with numbers between bi-1+1 and bi. The time needed to make a copy of all the books is determined by the scriber who was assigned the most work. Therefore, our goal is to minimize the maximum number of pages assigned to a single scriber. Your task is to find the optimal assignment.

Input

The input consists of N cases (equal to about 200). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly two lines. At the first line, there are two integers m and k, 1 <= k <= m <= 500. At the second line, there are integers p1, p2, ... pm separated by spaces. All these values are positive and less than 10000000.

Output

For each case, print exactly one line. The line must contain the input succession p1, p2, ... pm divided into exactly k parts such that the maximum sum of a single part should be as small as possible. Use the slash character ('/') to separate the parts. There must be exactly one space character between any two successive numbers and between the number and the slash.

If there is more than one solution, print the one that minimizes the work assigned to the first scriber, then to the second scriber etc. But each scriber must be assigned at least one book.

Example


Sample input:

2
9 3
100 200 300 400 500 600 700 800 900
5 4
100 100 100 100 100

Sample output:

100 200 300 400 500 / 600 700 / 800 900
100 / 100 / 100 / 100 100

Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1998









SPOJ Problem Set (classical)

44. Substitution Cipher

Problem code: SCYPHER

Antique Comedians of Malidinesia would like to play a new discovered comedy of Aristofanes. Putting it on a stage should be a big surprise for the audience so all the preparations must be kept absolutely secret. The ACM director suspects one of his competitors of reading his correspondece. To prevent other companies from revealing his secret, he decided to use a substitution cipher in all the letters mentioning the new play.

Substitution cipher is defined by a substitution table assigning each character of the substitution alphabet another character of the same alphabet. The assignment is a bijection (to each character exactly one character is assigned -- not neccessary different). The director is afraid of disclosing the substitution table and therefore he changes it frequently. After each change he chooses a few words from a dictionary by random, encrypts them and sends them together with an encrypted message. The plain (i.e. non-encrypted) words are sent by a secure channel, not by mail. The recipient of the message can then compare plain and encrypted words and create a new substitution table.

Unfortunately, one of the ACM cipher specialists have found that this system is sometimes insecure. Some messages can be decrypted by the rival company even without knowing the plain words. The reason is that when the director chooses the words from the dictionary and encrypts them, he never changes their order (the words in the dictionary are lexicographically sorted). String a1a2 ... ap is lexicografically smaller than b1b2 ... bq if there exists an integer i, i <= p, i <= q, such that aj=bj for each j, 1 <= j < i and ai < bi.

The director is interested in which of his messages could be read by the rival company. You are to write a program to determine that.

Input

The input consists of N cases (equal to about 1000). The first line of the input contains only positive integer N. Then follow the cases. The first line of each case contains only two positive integers A, 1 <= A <= 26, and K, separated by space. A determines the size of the substitution alphabet (the substitution alphabet consists of the first A lowercase letters of the english alphabet (a--z) and K is the number of encrypted words. The plain words contain only the letters of the substitution alphabet. The plain message can contain any symbol, but only the letters of the substitution alphabet are encrypted. Then follow K lines, each containing exactly one encrypted word. At the next line is encrypted message.

Output

For each case, print exactly one line. If it is possible to decrypt the message uniquely, print the decrypted message. Otherwise, print the sentence 'Message cannot be decrypted.'.

Example

Sample input:

2
5 6
cebdbac
cac
ecd
dca
aba
bac
cedab
4 4
cca
cad
aac
bca
bdac

Sample output:

abcde
Message cannot be decrypted.
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1998









SPOJ Problem Set (classical)

45. Commedia dell Arte

Problem code: COMMEDIA


So called commedia dell' arte is a theater genre first played in Italy at the beginning of the sixteenth century. It was inspired with the Roman Theater. The play had no fixed script and the actors (also called performers) had to improvise a lot. There were only a simple directions by the author like "enter the stage and make something funny" or "everyone comes on stage and everything is resolved happily". You can see it might be very interesting to play the commedia dell' arte. Therefore the ACM want to put a new play on a stage, which was completely unknown before. The main hero has a puzzle that takes a very important role in the play and gives an opportunity of many improvisations. The puzzle is the worldwide known Lloyd's Fifteen Puzzle. ACM wants to make the play more interesting so they want to replace the "standard" puzzle with a three-dimensional one. The puzzle consists of a cube containing M3 slots. Each slot except one contains a cubic tile (one position is free). The tiles are numbered from 1 to M3-1. The goal of the puzzle is to get the original ordering of the tiles after they have been randomly reshuffled. The only allowed moves are sliding a neighbouring tile into the free position along one of the three principal directions. Original configuration is when slot with coordinates (x,y,z) from {0,...,M-1}3 contains tile number z.M2+y.M+x+1 and slot (M-1,M-1,M-1) is free.

You are to write a program to determine whether it is possible to solve the puzzle or not.

Input

The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. The first line of each case contains only one integer M, 1 <= M <= 100. It is the size of 3D puzzle cube. Then follow M lines, each contains exactly M2 numbers on the tiles for one layer. First is the layer on the top of the cube and the last one on the bottom. In each layer numbers are arranged from the left top corner linewise to the right bottom corner of the layer. In other words, slot with coordinates (x,y,z) is described by the (x+M.y+1)-th number on the (z+1)-th line. Numbers are separated by space. Number 0 means free position.

Output

For each case, print exactly one line. If the original configuration can be reached by sliding the tiles, print the sentence 'Puzzle can be solved.'. Otherwise, print the sentence 'Puzzle is unsolvable.'.

Example

Sample input:

2
2
1 2 3 4
5 7 6 0
2
2 1 3 5
4 6 0 7

Sample output:

Puzzle is unsolvable.
Puzzle can be solved.
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Prague 1998









SPOJ Problem Set (classical)

47. Skyscraper Floors

Problem code: SCRAPER

What a great idea it is to build skyscrapers! Using not too large area of land, which is very expensive in many cities today, the skyscrapers offer an extremely large utility area for flats or offices. The only disadvantage is that it takes too long to get to the upper floors. Of course these skyscrapers have to be equiped not only with a stairway but also with several elevators. But even using ordinary elevators is very slow. Just imagine you want to get from the very top floor to the base floor and many other people on other floors want the same. As a result the elevator stops on almost every floor and since its capacity is limited and the elevator is already full from the upper floors, most stops are useless and just cause a delay. If there are more elevators in the skyscrapers, this problem is a little bit eliminated but still not completely. Most people just press all the buttons of all the elevators and then take the first one so that all elevators will stop on the floor anyway.

However, the solution exists as we shall see. The Antique Comedians of Midilesia headquarters reside in a skyscraper with a very special elevator system. The elevators do not stop on every floor but only on every X-th floor. Moreover each elevator can go just to a certain floor Y (called starting floor) and cannot go any lower. There is one high-capacity elevator which can stop on every elevator's starting floor.

The ACM has a big problem. The headquarters should be moved to another office this week, possibly on a different floor. Unfortunately, the high-capacity elevator is out of order right now so it is not always possible to go to the base floor. One piece of furniture cannot be moved using the stairway because it is too large to pass through the stairway door. You are to write a program that decides whether it is possible to move a piece of furniture from the original office to the other.

Input

The input consists of N cases (equal to about 2000). The first line contains only one positive integer N. Then follow the cases. Each case starts with a line containing four integers F, E, A, B, where F, 1 <= F < 50000000 determines the number of floors in the skyscraper (this means that there are floors 0 to F-1), E, 0 < E < 100 is the number of elevators and A, B, 0 <= A,B < F are numbers of the two floors between which the piece of furniture should be moved. Then follow E lines. Each of them contains description of one elevator. There are exactly two integers X and Y, X > 0, Y >= 0 at each line. Y determines, that the elevator starts on the Y-th floor and X determines, that it stops on every X-th floor, eg. for X = 3, Y = 7 the elevator stops on floors 7, 10, 13, 16, etc.).

Output

For each case, print exactly one line. If floor B is reachable from floor A not using the stairway, print the sentence 'It is possible to move the furniture.', otherwise print 'The furniture cannot be moved.'.

Example

Sample input:

2
22 4 0 6
3 2
4 7
13 6
10 0
1000 2 500 777
2 0
2 1

Sample output:

It is possible to move the furniture.
The furniture cannot be moved.
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-06
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1998









SPOJ Problem Set (classical)

48. Glass Beads

Problem code: BEADS

Once upon a time there was a famous actress. As you may expect, she played mostly Antique Comedies most of all. All the people loved her. But she was not interested in the crowds. Her big hobby were beads of any kind. Many bead makers were working for her and they manufactured new necklaces and bracelets every day. One day she called her main Inspector of Bead Makers (IBM) and told him she wanted a very long and special necklace.

The necklace should be made of glass beads of different sizes connected to each other but without any thread running through the beads, so that means the beads can be disconnected at any point. The actress chose the succession of beads she wants to have and the IBM promised to make the necklace. But then he realized a problem. The joint between two neighbouring beads is not very robust so it is possible that the necklace will get torn by its own weight. The situation becomes even worse when the necklace is disjoined. Moreover, the point of disconnection is very important. If there are small beads at the beginning, the possibility of tearing is much higher than if there were large beads. IBM wants to test the robustness of a necklace so he needs a program that will be able to determine the worst possible point of disjoining the beads.

The description of the necklace is a string A = a1a2 ... am specifying sizes of the particular beads, where the last character am is considered to precede character a1 in circular fashion.

The disjoint point i is said to be worse than the disjoint point j if and only if the string aiai+1 ... ana1 ... ai-1 is lexicografically smaller than the string ajaj+1 ... ana1 ... aj-1. String a1a2 ... an is lexicografically smaller than the string b1b2 ... bn if and only if there exists an integer i, i <= n, so that aj=bj, for each j, 1 <= j < i and ai < bi.

Input

The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line containing necklace description. Maximal length of each description is 10000 characters. Each bead is represented by a lower-case character of the english alphabet (a--z), where a < b ... z.

Output

For each case, print exactly one line containing only one integer -- number of the bead which is the first at the worst possible disjoining, i.e. such i, that the string A[i] is lexicographically smallest among all the n possible disjoinings of a necklace. If there are more than one solution, print the one with the lowest i.

Example

Sample input:

4
helloworld
amandamanda
dontcallmebfu
aaabaaa

Sample output:

10
11
6
5

Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Prague 1998









SPOJ Problem Set (main)

49. Hares and Foxes

Problem code: HAREFOX

The Antique Comedians of Malidinesia play an interesting comedy where many animals occur. Because they want their plays to be as true as possible, a specialist studies the behaviour of various animals. Recently, he is interested in a binary dynamic ecological system hares-foxes (SHF). As a part of this project, you are asked to design and implement intelligent automatic target evaluation simulator (IATES) for this system. The behaviour of the SHF follows so called standard model, described by the following set of difference equations.

hy+1 = a.hy - b.fy
fy+1 = c.fy + d.hy

where hy resp. fy represent the difference of the number of hares resp. foxes in year y and the reference count determined at the beginning of the experiment. The units of hy and fy are unknown. Therefore, hy and fy are to be treated as real numbers. Your task is to write a program to determine the long term evolution of SHF.

Input

The input consists of N cases (equal to about 5000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of six real numbers a, b, c, d, h1998 and f1998, written in this order on three lines, two numbers per line, separated by one or more spaces. The numbers are given in the classical format, i.e. optional sign, sequence of digits, optional dot and optional sequence of digits. The text form of a number does not exceed 10 characters. Each case is followed by one empty line.

Output

For each case, print one of the following sentences:

Example

Sample input:

2
2 0.5
0.5 0.6
2 3

0.1 1 
2 0.1
1 1

Sample output:

Both hares and foxes will overgrow.
Hares will die out while foxes will overgrow.

Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK NODEJS PYTH 3.2.3 n SED
Resource:ACM Central European Programming Contest, Prague 1998









SPOJ Problem Set (classical)

50. Invitation Cards

Problem code: INCARDS

In the age of television, not many people attend theater performances. Antique Comedians of Malidinesia are aware of this fact. They want to propagate theater and, most of all, Antique Comedies. They have printed invitation cards with all the necessary information and with the programme. A lot of students were hired to distribute these invitations among the people. Each student volunteer has assigned exactly one bus stop and he or she stays there the whole day and gives invitation to people travelling by bus. A special course was taken where students learned how to influence people and what is the difference between influencing and robbery.

The transport system is very special: all lines are unidirectional and connect exactly two stops. Buses leave the originating stop with passangers each half an hour. After reaching the destination stop they return empty to the originating stop, where they wait until the next full half an hour, e.g. X:00 or X:30, where 'X' denotes the hour. The fee for transport between two stops is given by special tables and is payable on the spot. The lines are planned in such a way, that each round trip (i.e. a journey starting and finishing at the same stop) passes through a Central Checkpoint Stop (CCS) where each passenger has to pass a thorough check including body scan.

All the ACM student members leave the CCS each morning. Each volunteer is to move to one predetermined stop to invite passengers. There are as many volunteers as stops. At the end of the day, all students travel back to CCS. You are to write a computer program that helps ACM to minimize the amount of money to pay every day for the transport of their employees.

Input

The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. Each case begins with a line containing exactly two integers P and Q, 1 <= P,Q <= 1000000. P is the number of stops including CCS and Q the number of bus lines. Then there are Q lines, each describing one bus line. Each of the lines contains exactly three numbers - the originating stop, the destination stop and the price. The CCS is designated by number 1. Prices are positive integers the sum of which is smaller than 1000000000. You can also assume it is always possible to get from any stop to any other stop.

Output

For each case, print one line containing the minimum amount of money to be paid each day by ACM for the travel costs of its volunteers.

Example

Sample input:

2
2 2
1 2 13
2 1 33
4 6
1 2 10
2 1 60
1 3 20
3 4 10
2 4 5
4 1 50

Sample output:

46
210
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Prague 1998









SPOJ Problem Set (classical)

51. Fake tournament

Problem code: TOUR

We consider only special type of tournaments. Each tournament consists of a series of matches. We have n competitors at the beginning of a competition and after each match the loser is moved out of the competition and the winner stays in (there are no draws). The tournament ends when there is only one participant left - the winner. It is a task of National Sports Federation to schedule the matches. Members of this committee can pick the contestants for the first match. Then, after they know the result, they say which of the remaining contestants meet in the second match, and so on until there is only one participant left.
It is easy to see that not only skill and training decides about the win, but also "luck" - i.e. the schedule. The members of NSF know it as well.
The committee used the training time to look carefully on the performance of each probable contestant. It is clear now, at the start of the season, that some of the results between the competitors are 100% predictable. Having this information NSF considers if it is possible to schedule the matches in such a way that the given contestant x wins. That is to plan the matches for x only with those who will lose with him (then he wins the whole tournament of course). If it is possible then w say that the tournament can be set for x.

Task

Your task is to write a program which determines the number of contestants of a given tournament for which it is possible to set it.

Input

t [number of tests to solve].
In the first line of each test: n (1<=n<=1000) - the number of participants of the tournament. We number the participants with numbers 1,2, ... ,n. The following line contains a list of participants who will inevitably win with participant 1. This list begins with a number m (the number of contestants "better" than 1) and numbers n1,n2, ... , nm delimited by single spaces.
Next n-1 lines contain analogous lists for participants 2, 3, ..., n.
Remark 1. The fact that participant a would lose with b and b would lose with c doesn't necessarily mean that a would lose with c in a direct match.
Remark 2. It is not possible that a is on the list of contestants better than b and b is on the list of a at the same time.

Output

For each test your program should output a single integer - the number of participants, for which it is possible to set the tournament.

Example

Input:
1
3
2 3 2
1 3
0
Output:
1

Added by:Adam Dzedzej
Date:2004-06-08
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Internet Contest Pogromcy Algorytmów (Algorithm Tamers)
Round IV, 2001









SPOJ Problem Set ()

54. Julka

Problem code: JULKA

Julka surprised her teacher at preschool by solving the following riddle:

Klaudia and Natalia have 10 apples together, but Klaudia has two apples more than Natalia. How many apples does each of he girls have?

Julka said without thinking: Klaudia has 6 apples and Natalia 4 apples. The teacher tried to check if Julka's answer wasn't accidental and repeated the riddle every time increasing the numbers. Every time Julka answered correctly. The surprised teacher wanted to continue questioning Julka, but with big numbers she could't solve the riddle fast enough herself. Help the teacher and write a program which will give her the right answers.

Task

Write a program which

Input

Ten test cases (given one under another, you have to process all!). Every test case consists of two lines. The first line says how many apples both girls have together. The second line says how many more apples Klaudia has. Both numbers are positive integers. It is known that both girls have no more than 10100 (1 and 100 zeros) apples together. As you can see apples can be very small.

Output

For every test case your program should output two lines. The first line should contain the number of apples belonging to Klaudia. The second line should contain the number of apples belonging to Natalia.

Example

Input:
10
2
[and 9 test cases more]

Output:
6
4
[and 9 test cases more]


Added by:Adam Dzedzej
Date:2004-06-08
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
Resource:Internet Contest Pogromcy Algorytmow (Algorithm Tamers)
Round II, 2003









SPOJ Problem Set (classical)

55. Jasiek

Problem code: JASIEK

Jasiek is only 6 years old, but he already has many skills. He likes drawing and asking riddles very much. This morning he got a sheet of grid paper and a pencil from his mother and he started drawing. All his drawings have some common properties:

At noon mom phoned and asked what Jasiek's today's picture was. The boy didn't answer directly, but described the picture by a sequence of moves needed to walk around the centres of the coloured squares on its boundary, ie. those squares which have at least one common corner with a white square. Jasiek set the starting square and then gave the sequence of moves necessary to walk along the boundary squares anti-clockwise. Mom was very surprised by the complexity of the picture and especcialy by the number of coloured squares. Given Jasiek's description, can you quickly count how many coloured squares there are in the picture?

Task

Write a program which

Input

Ten test cases (given one under another, you have to process all!). Each of the test cases is a series of lines. Each line consists of only one character. The letter P means the beginning of the description. The letter K means the end of the desription (and the test case). All other lines (if any) contain one of the letters N, W, S or E (N meaning North, W - West, S - South and E - East). Every line of the description corresponds to the relative position of the centre of some square on the boundary of the picture. The first and the last line correspond to the same square. A letter in a line other than the first or the last tells you which way you have to go in order to get to the next boundary square when going around the picture anti-clockwise. Jasiek's description finishes after going around the picture once. The length of the description doesn't exceed 20000 letters.

Output

For every testcase your program should write (to the standard output) only one line with one integer, equal to the number of coloured squares in Jasiek's picture.

Example

Example illustration

Input:
P
S
S
S
E
N
E
E
S
E
E
N
N
N
N
S
S
S
W
W
N
N
W
W
W
N
S
K
[and 9 test cases more]

Output:
23
[and 9 test cases more]


Added by:Adam Dzedzej
Date:2004-06-09
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Internet Contest Pogromcy Algorytmow (Algorithm Tamers)
Round III, 2003









SPOJ Problem Set (classical)

56. Dyzio

Problem code: DYZIO


Dyzio is Jasiek's friend and he also likes riddles. Here is a riddle he came up with:

Jasiek, here is a piece of string, which has to be cut into smaller pieces. I will not tell you directly how to do it, but look at this sequence of zeros (0) and ones (1). A one at the begining means that the string has to be cut in half. If the first digit was zero, it would be the only digit in the sequence and mean you don't have to cut anything - I want the whole string. If you have to cut the string anyway then after the first 1 I wrote what to do with the left piece (according to the same rules as with the whole string) and then I wrote what to do with the right piece of string (all the time with the same rules of notation). Every time you have to cut the left piece first, only then can you cut the right one. Now start cutting and tell me, how many cuts you have to do until you have cut off the shortest piece.

Unfortunately mom hid the scissors from Jasiek, but luckily a computer was at hand and Jasiek quickly wrote a program simulating the string cutting. Can you write such a program?

Task

Write a program which

Input

Ten test cases (given one under another, you have to process all!). Each test case consists of two lines. In the first line there is a number n (1<=n<=20000). In the second line one zero-one word (a sequence of zeros and ones without spaces between them) of length n - the description of the cutting procedure given by Dyzio.

Output

For every testcase your program should write (to the standard output) only one line with one integer equal to the number of cuts which have to be made in order to get the shortest piece.

Example

Input:
9
110011000
[and 9 test cases more]

Output:
4
[and 9 test cases more]


Added by:Adam Dzedzej
Date:2004-06-10
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Internet Contest Pogromcy Algorytmow (Algorithm Tamers)
Round III, 2003









SPOJ Problem Set (classical)

57. Supernumbers in a permutation

Problem code: SUPPER

An n-element permutation is an n-element sequence of distinct numbers from the set {1, 2, ...,n}. For example the sequence 2,1,4,5,3 is a 5-element permutation. We are interested in the longest increasing subsequences in a permutation. In this exemplary permutation they are of length 3 and there are exactly 2 such subsequences: 2,4,5 and 1,4,5. We will call a number belonging to any of the longest increasing subsequences a supernumber. In the permutation 2,1,4,5,3 the supernumbers are 1,2,4,5 and 3 is not a supernumber. Your task is to find all supernumbers for a given permutation.

Task

Write a program which

Input

Ten test cases (given one under another, you have to process all!). Each test case consists of two lines. In the first line there is a number n (1<=n<=100000). In the second line: an n-element permutation - n numbers separated by single spaces.

Output

For every test case your program should write two lines. In the first line - the number of supernumbers in the input permutation. In the second line the supernumbers separated by single spaces in increasing order.

Example

Input:
5
2 1 4 5 3
[and 9 test cases more]

Output:
4
1 2 4 5
[and 9 test cases more]

Warning: large Input/Output data, be careful with certain languages
Added by:Adam Dzedzej
Date:2004-06-10
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Internet Contest Pogromcy Algorytmow (Algorithm Tamers)
Round IV, 2003









SPOJ Problem Set (classical)

58. Crime at Piccadily Circus

Problem code: PICAD


Sherlock Holmes is carrying out an investigation into the crime at Piccadily Circus. Holmes is trying to determine the maximal and minimal number of people staying simultaneously at the crime scene at a moment when the crime could have been commited. Scotland Yard has already carried out a thorough investigation already, interrogated everyone seen at the crime scene and determined what time they appeared at the crime scene and what time they left. Doctor Watson offered his help to process the data gathered by Scotland Yard and find the numbers interesting Sherlock Holmes, but he has some difficulties. Help him!

Task

Write a program which

Input

Ten test cases (given one under another, you have to process all!). The first line of each test case consists of two integer numbers p and k, 0<=p<=k<=100000000. These denote the first and the last moment when the crime could have been commited. The second line of each test case contains one integer n, 3<=n<=5000. This is the number of people interrogated by Scotland Yard. The next n lines consist of two integers - line i+2 contains numbers ai and bi separated by a single space, 0<=ai<=bi<=1000000000. These are the moments at which the i-th person apperared at and left the crime scene respectively. It means that the i-th person was at the crime scene for the whole time from moment ai until moment bi (inclusive).

Output

For every test case your program should write to the standard output only one line with two integers separated by a single space: the minimal and maximal number of people staying simultaneously at the crime scene, in the interval between moment p and k, (inclusive).

Example

Only one test case.

Input:
5 10
4
1 8
5 8
7 10
8 9

Output:
1 4


Added by:Adam Dzedzej
Date:2004-06-10
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Internet Contest Pogromcy Algorytmow (Algorithm Tamers)
Round IV, 2003









SPOJ Problem Set (classical)

59. Bytelandian Information Agency

Problem code: BIA

Bytelandian Information Agency (BIA) uses a net of n computers. The computers are numbered from 1 to n, and the computer number 1 is a server. The computers are connected by one-way information channels. Every channel connects a pair of computers. The whole network is organised in such a way that one can send information from the server to any other computer either directly or indirectly.

When BIA acquires new information, the information is put on the server and propagated in the net. The chief of BIA considers what would happen if one computer stopped working (was blown away by terrorists for example). It could happen that some other computers would stop receiving information from the server, because the broken computer was a necessary transmitter. We will call such computers critical. For example in the situation in the picture below the critical computers are 1 and 2. 1 is the server and all information sent from the server to 3 has to go through 2.

BIA computer net

Task

Write a program which

Input

Ten test cases (given one under another, you have to process all!). Each test case consists of several lines. In the first line there are numbers n and m. n denotes the number of computers in the net,(2<=n<=5000). m denotes the number of information channels, n-1<=m<=200000. The following m lines describes a single information channel and consist of two integer numbers a and b separated by a space. It means the computer a sends information to computer b by that channel. You may assume there are no two channels which start and end at the same points a, b.

Output

For every testcase your program should write two lines. In the first line k - the number of critical computers in the net. In the second line k numbers separated by single spaces - the numbers of critical computers in increasing order.

Example

Input:
4 5
1 2
1 4
2 3
3 4
4 2
[and 9 test cases more]

Output:
2
1 2
[and 9 test cases more]

Warning: large Input/Output data, be careful with certain languages
Added by:Adam Dzedzej
Date:2004-06-14
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Internet Contest Pogromcy Algorytmow (Algorithm Tamers)
Round IV, 2003









SPOJ Problem Set (classical)

60. The Gordian Dance

Problem code: DANCE


The Gordian Dance is a traditional Bytelandian dance performed by two pairs of dancers. At the beginning the dancers are standing in the corners of the square ABCD, forming two pairs: A-B and C-D. Every pair is holding an outstretched string. So in the starting position both strings are stretched horizontally and parallel.

The starting position of dancers.

The dance consists of a series of moves. There are two kinds of moves:

During the dance the strings tangle with each other, but in the end they should be untangled and stretched horizontally and parallel. The dancers do not have to occupy the same spots as in the begining. The dance requires a lot of experience, because the strings can be extremely tangled during the dance. The sequence of moves after which they are no longer tangled and are stretched horizontally and parallel can be difficult to guess.

Your program should help beginner dancers end a dance. You are to determine the minimal number of mover required to end the dance given a sequence of moves already performed.

Illustration

For example after the sequence SS we get the following configuration.

The configuration after SS

The shortest sequence of moves required to end the dance is of length 5: RSRSS.

Task

Write a program which

Input

Ten test cases (given one under another, you have to process all!). The first line of each test case consists of one integer n equal to the nmber of moves already made, 0<=n<=1000000. The second line of each test case consists of one word of length n, made up of letters S and/or R.

Output

For every testcase your program should write to standard output only one line with one integer number: the minimal number of moves required to untangle the strings and stretch them horizontally and parallel.

Example

Input:
2
SS
[and 9 test cases more]

Output:
5
[and 9 test cases more]

Warning: large Input/Output data, be careful with certain languages
Added by:Adam Dzedzej
Date:2004-06-15
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Internet Contest Pogromcy Algorytmow(Algorithm Tamers) 2003 Round V









SPOJ Problem Set (classical)

61. Brackets

Problem code: BRCKTS

We will call a bracket word any word constructed out of two sorts of characters: the opening bracket "(" and the closing bracket ")". Among these words we will distinguish correct bracket expressions. These are such bracket words in which the brackets can be matched into pairs such that

On a bracket word one can do the following operations:

Task

Write a program which

Input

Ten test cases (given one under another, you have to process all!). Each of the test cases is a series of lines. The first line of a test consists of a single number n (1<=n<=30000) denoting the length of the bracket word. The second line consists of n brackets, not separated by any spaces. The third line consists of a single number m -- the number of operations. Each of the following m lines carries a number k denoting the operation performed. k=0 denotes the check operation, k>0 denotes replacement of k-th bracket by the opposite.

Output

For every test case your program should print a line:
Test i:
where i is replaced by the number of the test and in the following lines, for every check operation in the i-th test your program should print a line with the word YES, if the current bracket word is a correct bracket expression, and a line with a word NO otherwise. (There should be as many lines as check operations in the test.)

Example

Input:
4
()((
4
4
0
2
0
[and 9 test cases more]
Output:
Test 1:
YES
NO
[and 9 test cases more]

Warning: large Input/Output data, be careful with certain languages
Added by:Adam Dzedzej
Date:2004-06-15
Time limit:11s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Internet Contest Pogromcy Algorytmow(Algorithm Tamers) 2003 Round IV









SPOJ Problem Set (classical)

62. The Imp

Problem code: IMP

An Imp jumps on an infinite chessboard. Moves possible for the Imp are described by two pairs of integers: (a,b) and (c,d) - from square (x,y) the Imp can move to one of the squares: (x+a,y+b), (x-a,y-b), (x+c,y+d), (x-c,y-d). We want to know for which square different from (0,0) to which the Imp can jump from (0,0) (possibly in many moves) the value |x|+|y| is the lowest.

Task

Write a program which

Input

Ten test cases. Each test consists of four numbers a,b,c,d in one line, separated by spaces.
-100000 <= a, b, c, d <= 100000

Output

For every test case your program should write a single line with a number equal the lowest possible value |x|+|y|.

Example

Input:
13 4 17 5
[and 9 test cases more]
Output:
2
[and 9 answers more]


Added by:Adam Dzedzej
Date:2004-06-15
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Internet Contest Pogromcy Algorytmow(Algorithm Tamers) 2003 Round V









SPOJ Problem Set (classical)

63. Square Brackets

Problem code: SQRBR

You are given:

What is the number of proper bracket expressions of length 2n with opening brackets appearing in positions s1, s2,...,sk?

Illustration

Several proper bracket expressions:

[[]][[[]][]] 
[[[][]]][][[]]

An improper bracket expression:

[[[][]]][]][[]]

There is exactly one proper expression of length 8 with opening brackets in positions 2, 5 and 7.

Task

Write a program which for each data set from a sequence of several data sets:

Input

The first line of the input file contains one integer d, 1 <= d <= 10, which is the number of data sets. The data sets follow. Each data set occupies two lines of the input file. The first line contains two integers n and k separated by single space, 1 <= n <= 19, 1 <= k <= n. The second line contains an increasing sequence of k integers from the interval [1;2n] separated by single spaces.

Output

The i-th line of output should contain one integer - the number of proper bracket expressions of length 2n with opening brackets appearing at positions s1, s2,...,sk.

Example

Sample input:
5 
1 1 
1 
1 1 
2 
2 1 
1 
3 1 
2 
4 2 
5 7 

Sample output:
1 
0 
2 
3 
2 

Added by:Adrian Kosowski
Date:2004-06-22
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:III Polish Collegiate Team Programming Contest (AMPPZ), 1998









SPOJ Problem Set (main)

64. Permutations

Problem code: PERMUT1

Let A = [a1,a2,...,an] be a permutation of integers 1,2,...,n. A pair of indices (i,j), 1<=i<=j<=n, is an inversion of the permutation A if ai>aj. We are given integers n>0 and k>=0. What is the number of n-element permutations containing exactly k inversions?

For instance, the number of 4-element permutations with exactly 1 inversion equals 3.

Task

Write a program which for each data set from a sequence of several data sets:

Input

The first line of the input file contains one integer d, 1<=d<=10, which is the number of data sets. The data sets follow. Each data set occupies one line of the input file and contains two integers n (1<=n<=12) and k (0<=k<=98) separated by a single space.

Output

The i-th line of the output file should contain one integer - the number of n-element permutations with exactly k inversions.

Example

Sample input:
1 
4 1 

Sample output:
3 

Added by:Adrian Kosowski
Date:2004-06-22
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
Resource:III Polish Collegiate Team Programming Contest (AMPPZ), 1998









SPOJ Problem Set ()

65. Ball

Problem code: BALL1

On the rectangular chessboard of n x m square fields we choose one field adjacent to the edge of the chessboard, called the starting field. Then we put a ball in the center of this field and push it to roll through the chessboard. The diameter of the ball equals the width (and height) of chessboard field. The angle between the direction of ball movement and the edge of the chessboard equals 45 degrees. The ball bounces off the edges of the chessboard: if the ball touches the edge of the chessboard then each composite of its velocity perpendicular to the edge touched is reversed. At the start the ball is pushed toward increasing coordinates (when the starting field is a field of the highest coordinate, the ball bounces momentarily).

We assign a point to a field of the chessboard each time the point of adjacency between the ball and the chessboard enters the interior of the field. The game is over when a point is assigned to the starting field. What is the number of fields to which an odd number of points is assigned? The following figures illustrate the problem. The route of the ball is marked with a dashed line. Fields with the odd number of points are shadowed.

Task

Write a program which for each data set from a sequence of several data sets:

Input

The first line of the input file contains one integer d, 1 <= d <= 10, which is the number of data sets. The data sets follow. Each data set occupies one line of the input file. Such a line consists of four integers x, y, a, b separated with single spaces. These integers are the x- and y-dimensions of the chessboard and x- and y-coordinates of the starting field, respectively. Integers x and y are greater than two, the number of fields of the chessboard does not exceed 109,the starting field is adjacent to the edge of the chessboard.

Output

The i-th line of output should contain one integer which is equal to the number of fields of the chessboard with the odd number of points.

Example

Sample input:

2
13 6 1 5
10 7 1 5

Sample output:

2 
22

Added by:Adrian Kosowski
Date:2004-06-06
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:III Polish Collegiate Team Programming Contest (AMPPZ), 1998









SPOJ Problem Set (classical)

66. Cross-country

Problem code: CRSCNTRY

Agness, a student of computer science, is very keen on cross­country running, and she participates in races organised every Saturday in a big park. Each of the participants obtains a route card, which specifies a sequence of checkpoints, which they need to visit in the given order. Agness is a very atractive girl, and a number of male runners have asked her for a date. She would like to choose one of them during the race. Thus she invited all her admirers to the park on Saturday and let the race decide. The winner would be the one, who scores the maximum number of points. Agnes came up with the following rules:

Between two consecutive meetings, the girl and the competitors may visit any number of checkpoints. The boys will be really doing their best, so you may assume, that each of them will be able to visit any number of checkpoints whilst Agnes runs between two consecutive ones on her route.

Task

Write a program which for each data set from a sequence of several data sets:

Input

There is one integer d in the first line of the input file, 1 <= d <= 10. This is the number of data sets. The data sets follow. Each data set consists of a number of lines, with the first one specifying the route in Agnes' race card. Consecutive lines contain routes on cards presented to Tom. At least one route is presented to Tom. The route is given as a sequence of integers from interval [1, 1000] separated by single spaces. Number 0 stands for the end of the route, though when it is placed at the beginning of the line it means the end of data set. There are at least two and at most 2000 checkpoints in a race card.

Output

The i-th line of the output file should contain one integer. That integer should equal the greatest number of times Tom is able to meet with Agnes for race cards given in the i-th data set.

Example

Sample input:

3 
1 2 3 4 5 6 7 8 9 0 
1 3 8 2 0 
2 5 7 8 9 0 
1 1 1 1 1 1 2 3 0 
1 3 1 3 5 7 8 9 3 4 0 
1 2 35 0 
0 
1 3 5 7 0 
3 7 5 1 0 
0 
1 2 1 1 0 
1 1 1 0 
0 

Sample output:

6 
2 
3 

Added by:Adrian Kosowski
Date:2004-06-08
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:III Polish Collegiate Team Programming Contest (AMPPZ), 1998









SPOJ Problem Set ()

67. Cutting out

Problem code: CUTOUT

One has to cut out a number of rectangles from a paper square. The sides of each rectangle are to be parallel to the sides of the square. Some rectangles can be already cut out. What is the largest area of a rectangle which can be cut out from the remaining paper?

Illustration

Three rectangles have been cut out from the square 10x10 in the figure shown below. The area of the largest rectangle that can be cut out from the remaining paper is 16. One of such rectangles is shown with a dashed line.

Task

Write a program that for each data set from a sequence of several data sets:

Input

The first line of the input file contains one positive integer d not larger than 10. This is the number of data sets. The data sets follow. Each set of data occupies two consecutive lines of the input file. The first line of each data set contains two integers n and r, 1 <= n <= 40000, 0 <= r <= 100. The integer n is the length of the sides of an input square. The integer r is the number of rectangles which have been cut out from the square. The second line of the data set contains a sequence of 4r integers x1, x2,...,x4r from the interval [0,n] separated by single spaces. For each i = 1,...,r, integers x4i-3, x4i-2, x4i-1, x4i describe the i-th rectangle: x4i-3 is the distance of its left side from the left side of the square, x4i-2 is the distance of its right side from the left side of the square, x4i-1 is the distance of the bottom side of the rectangle from the bottom side of the square and x4i is the distance of its top side from the bottom side of the square.

Output

For each i = 1,...,d, your program should write only one integer to the i-th line of the output file -- the largest area of a rectangle which can be cut out from the rest of the i-th square.

Example

Sample input:

2 
6 2 
0 3 0 3 3 6 3 6 
10 3 
0 5 0 5 0 10 5 10 9 10 0 5 

Sample output:

9 
20 

Added by:Adrian Kosowski
Date:2004-06-08
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:III Polish Collegiate Team Programming Contest (AMPPZ), 1998









SPOJ Problem Set (classical)

68. Expression

Problem code: EXPR1

We are given an integer k and an arithmetic expression E with the operations '+', '-', and arguments from the set {0,1,...,9}. Is it possible to put some parentheses in E to get a new expression E' whose value equals k? If the answer is positive what is the minimum number of pairs of parentheses '(', ')' that are necessary?

Illustration

It is sufficient to put one pair of parentheses in the expression 5 - 4 + 5 to get an expression with value -4, namely 5 - (4 + 5) = -4.

Task

Write a program that for each data set from a sequence of several data sets:

Input

The first line of the input file contains one positive integer d not larger than 10. This is the number of data sets. The data sets follow. Each set of data occupies two consecutive lines of the input file. The first line contains two integers n and k, 2 <= n <= 40, -180 <= k <= 180. The even integer n is the length of E. The second line contains the expression itself written as a string of length n. The string contains operators '+' or '-' in odd positions and numbers from the set {0,1,...,9} in even positions.

Output

For each i = 1,...,d, your program should write to the i-th line of the output file one word 'NO' if the i-th input expression cannot be transformed into any expression of value k, and the smallest number of pairs of parentheses necessary otherwise.

Example

Sample input:

5 
6 -4 
+5-4+5 
2 1 
+1 
4 1 
-1+1 
4 0 
-1+1 
4 -2 
-1+1 

Sample output:

1 
0 
NO 
0 
1 

Added by:Adrian Kosowski
Date:2004-06-08
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:III Polish Collegiate Team Programming Contest (AMPPZ), 1998









SPOJ Problem Set ()

69. Moulds

Problem code: MOULDS

In a factory, moulds for casting metal objects are produced by a special cutting device. The device is equipped with cuboid-shaped blade of size 1 mm x 1 mm x 30 mm (its height) which operates with each of its sides thus producing the mould from cuboid of size 250 mm x 250 mm x 30 mm (its height). The end of the blade newer lowers below the bottom surface of the cuboid. In any moment the distance between initial and current position doesn't exceed 1000.

The machine understands special command language which has the following grammar:

<command block> ::= [ <command> ; {<command> ; } ] 
<command>       ::= <lift> | <shift> | <command block>
<lift>          ::= ^ <distance>
<shift>         ::= @ <direction> <distance>
<direction>     ::= N | S | W | E 
<distance>      ::= <sign> <number> | <number>
<number>        ::= <digit> {<digit>}
<sign>          ::= - | + 
<digit>         ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 

where {exp} means zero or more exps. 

The command <lift> causes moving the blade downwards when the distance is a positive number and upwards otherwise. The command <shift> moves the blade in the appropriate direction (N--north, S--south, W--west, E--east).

Task

Write a program which for each data set from a sequence of several data sets:

Input

The first line of the input file contains one integer d, 1 <= d <= 10, which is the number of data sets. The data sets follow. Each data set occupies one line of the input file and is a word derived from <command block> of the above grammar of length not exceeding 10000 characters.

Output

The i-th line of the output file should contain one integer -- the volume (in cubic mm) of the hollows made by the machine controlled by the command block given in the i-th data set.

Example

Sample input:

1 
[^2;@S2;] 


Sample output:

3


Added by:Adrian Kosowski
Date:2004-06-08
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:III Polish Collegiate Team Programming Contest (AMPPZ), 1998









SPOJ Problem Set ()

70. Relations

Problem code: RELATS1

You are given a directed graph, whose edges are labeled with relational symbols '<', '>' and '='. For a nonnegative integer k, a k-correct G-labeling is a mapping from vertices of G into integers from interval [0,k] such that numbers at the ends of each edge satisfy the relation described by the label of the edge. We assume that an element on the left side of the relational symbol is a number assigned to the initial vertex. Compute the smallest k for which k-correct G-labeling exists or verify that such labeling doesn't exist for any k.

Illustration

For the graph in the figure the smallest k = 2.

Task

Write a program that for each data set from a sequence of several data sets:

Input

The first line of the input file contains one positive integer d not larger than 10. This is the number of data sets. The data sets follow. Each data set is described in two consecutive lines of the input file. In the first line there are two integers n and m separated by a single space. The number n is the number of vertices of G and m is the number of edges of G. Numbers n and m satisfy the inequalities: 1 <= n <= 1000, 0 <= m <= 10000. The vertices are numbered with integers from 1 to n and are identified by these numbers. There are no parallel edges and self-loops in the graph. (Two different edges u1 -> v1 and u2 -> v2 are parallel iff u1 = u2 and v1 = v2.) There are 3m integers separated by single spaces in the second line. The numbers at positions 3i-2 and 3i-1, 1 <= i <= m, are the ends of the i-th edge, the beginning and the end, respectively, whereas the number at position 3i is a number from the set {-1,0,1} and it is the label of the i-th edge: -1 represents '<', 0 represents '=' and 1 represents '>'.

Output

For the i-th data set, 1 <= i <= d, your program should write one word NO in the i-th line of the output file if a k-correct labeling doesn't exist for any k, or the smallest integer k for which such a labeling exists.

Example

Sample input:

4 
4 4 
1 2 -1 2 3 0 2 4 -1 3 4 -1 
2 2 
1 2 -1 2 1 -1 
2 2 
1 2 -1 2 1 1 
3 3 
1 2 0 3 2 0 3 1 0 

Sample output:

2 
NO 
1 
0 

Added by:Adrian Kosowski
Date:2004-06-08
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:III Polish Collegiate Team Programming Contest (AMPPZ), 1998









SPOJ Problem Set (classical)

71. Tree

Problem code: TREE1

Consider an n-vertex binary search tree T containing n keys 1,2,...,n. A permutation p = [p1,...,pn] of the integers 1,2,...,n is said to be consistent with the tree T if the tree can be built from the empty one as the result of inserting integers p1,p2,...,pn. Find how many permutations are consistent with the tree T.

Illustration

Exactly 2 permutations are consistent with the tree in the figure below.

Task

Write a program that for each data set from a sequence of several data sets:

Input

The first line of the input file contains one positive integer d not larger than 10. This is the number of data sets. The data sets follow. Each set of data occupies two consecutive lines of the input file. The first line contains only one integer n, 1 <= n <= 30. This is the number of vertices of the tree. The second line contains a sequence of n integers separated by single spaces. The integers are keys in the input tree given in the prefix order. The first integer in the sequence is the key from the root of the tree. It is followed by the keys from the left subtree written in the prefix order. The sequence ends with the keys from the right subtree, also given in the prefix order.

Output

For each i = 1,...,d, your program should write to the i-th line of output the number of permutations consistent with the tree described in the i-th data set.

Example

Sample input:

5 
3 
2 1 3 
3 
1 2 3 
1 
1 
4 
2 1 3 4 
4 
1 4 2 3 

Sample output:

2 
1 
1 
3 
1 

Added by:Adrian Kosowski
Date:2004-06-08
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:III Polish Collegiate Team Programming Contest (AMPPZ), 1998









SPOJ Problem Set (classical)

73. Bacterial

Problem code: BAC

In the biology laboratory we are observing several bacterial samples, and under the microscope we have them shaded with different colors to see them expanding their territory on the plate.

It is interesting to know that the bacterial are quite 'friendly' that once they meet each other, they do not expand into each other's occupation any more. The bacterial samples are expanding at similar speeds and we take them as the same speed.

Since the experiment is tedious and lengthy (Oh My God! there are several thousand samples at our pick), we are going to run a simulation based on this reality, taking the variable that these samples may be planted in different starting spots.

We are using rectangular plates and bacterial racing is bounded within the plate.

Input format

There are multiple test cases (about 20000 of them) each taking the following format:

The plate lies in such a coordinating system that the lower-left corner of it is (0,0) and the upper-right corner is (width,height).

A test with zero plate area marks the end of the tests and this one shall not be processed.

Between each input block there is a blank line.

Output format

Generate a report having the samples sorted on their domination, with each line taking the following format:
<sample id> <area occupation>
where: 'sample id' takes 3 columns right justified, with '0' padded to the left as necessary, and 'area occupation' takes 14 columns with 2 digit precision, right justified.

The sample occupying more area shall be reported prior to those occupying less. The input data will ensure enough difference in areas to avoid ambiguity.

Between each output block there shall be a blank line.

Example

Sample input:

10 10
2
5 5
0 0

0 0

Sample output:

001         87.50
002         12.50

Warning: large Input/Output data, be careful with certain languages
Added by:Neal Zane
Date:2004-06-08
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Neal Zane









SPOJ Problem Set ()

75. Editor

Problem code: EDIT1

Have you ever programmed in Brainf**k? If yes, then you know how annoying it is to press the same key several times in a row. So what we all need, is a good editor. Here are the functions that the editor should have:

Please note, that the solution may only be submitted in Brainf**k or Intercal.

Input

There is exactly one test case. You can assume, that there is no key press of 'd' when the line is still empty.

Output

Print the output that the editor described above would produce on the given input. You can assume, that no line is created with more than 150 characters.

Example

Input:

sample-test
-dd-d-dd
end signalled by two newlines

Output: sample-test
--------------------------------------------
enen signalleenen signalle by two newlines


Added by:Adrian Kuegel
Date:2004-06-12
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:BF ICK
Resource:own problem









SPOJ Problem Set ()

76. Editor Inverse

Problem code: EDIT2


You are given a text. Calculate the minimum number of keystrokes needed to produce this text, if the editor described below is used.
If you haven't read the problem "Editor" before, here is a description of the functionality of the editor:

Input

The input consists of exactly ten test cases. Each test case consists of a line with at most 600 characters. The character 'd' is not used in any of the lines, but all other printable ascii characters may occur.

Output

For each test case, first print a line containing the minimum number of key strokes to produce the given line of text. In the next lines, write the keys that are pressed to produce the text. If there are several possibilites with minimum number of keystrokes, you should also minimise the number of lines, if there is still more than one possibility, minimise number of keystrokes before the first '\n', then second '\n', ...

Since 'd' is a costly operation in the editor, for each output line you should minimise the number of 'd' characters as the 2nd criterion after minimising number of keystrokes in this line.

The original input line should be the same as the output of the editor (processing the output you produce), if '\n' characters are ignored.

Notice that you have to terminate the input for the editor with two '\n'.

Example

Here only two test cases.

Input:

00001123444456789
000011234444446789 Output: 18 00d1123444456789 18 00d1123 444d6789

Added by:Adrian Kuegel
Date:2004-06-12
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:own problem









SPOJ Problem Set (classical)

77. New bricks disorder

Problem code: BRICKS

You have n bricks arranged in a line on the table. There is exactly one letter on each of them. Your task is to rearrange those bricks so that letters on them create some specified inscription. While rearanging you can only swap adjacent bricks with specified letters (you are given m pairs (a1,b1),...,(am,bm) and you are only allowed to swap bricks with ai on one of them and bi on the second, for some i=1,..,m). You should check if it is possible to accomplish this - and if it is - calculate minimal needed number of swaps.

Input

There is a single integer c on the first line of input. Then c test cases follow: each of them consists of two lines of small letters (a..z) with lengths not exceeding 100000 (descriptions of starting and ending configurations), one integer m in the next line and then m lines with two letters ai,bi in each of them.

Output

For each test case you should print -1 if it is not possible to rearrange bricks or the minimal number of swaps if it is possible (if so, output this value modulo 232).

Example

Input:
4
ab
ba
0
abc
cba
3
ab
cb
ca
cabbbc
cbabbc
1
ab
abba
baab
1
ab

Output:
-1
3
1
2
Warning: large Input/Output data, be careful with certain languages
Added by:Pawel Gawrychowski
Date:2004-06-17
Time limit:9s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

78. Marbles

Problem code: MARBLES

Hänschen dreams he is in a shop with an infinite amount of marbles. He is allowed to select n marbles. There are marbles of k different colors. From each color there are also infinitely many marbles. Hänschen wants to have at least one marble of each color, but still there are a lot of possibilities for his selection. In his effort to make a decision he wakes up. Now he asks you how many possibilites for his selection he would have had. Assume that marbles of equal color can't be distinguished, and the order of the marbles is irrelevant.

Input

The first line of input contains a number T <= 100 that indicates the number of test cases to follow. Each test case consists of one line containing n and k, where n is the number of marbles Hänschen selects and k is the number of different colors of the marbles. You can assume that 1<=k<=n<=1000000.

Output

For each test case print the number of possibilities that Hänschen would have had. You can assume that this number fits into a signed 64 bit integer.

Example

Input:
2
10 10
30 7

Output:
1
475020

Added by:Adrian Kuegel
Date:2004-06-19
Time limit:1s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:own problem









SPOJ Problem Set ()

82. Easy Problem

Problem code: EASYPIE

Last year there were a lot of complaints concerning the set of problems. Most contestants considered our problems to be too hard to solve. One reason for this is that the team members responsible for the problems are not able to evaluate properly whether a particular problem is easy or hard to solve. (We have created until now so many problems, that all seems quite easy.) Because we want our future contests to be better we would like to be able to evaluate the hardness of our problems after the contest using a history of submissions.

There are a few statistics that we can use for evaluating the hardness of a particular problem: the number of accepted solutions of the problem, the average number of submissions of the problem and the average time consumed to solve it (as "General rules" of the contest state "the time consumed for a solved problem is the time elapsed from the beginning of the contest to the submittal of the accepted run"). For the latter two statistics we consider only the teams which solved this particular problem. Needless to say we ask you to write a program that computes aforementioned statistics for all problems.

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case, the first line of the input contains one integer n (1 <= n <= 2000) being the number of submissions during the contest. Each of the next n lines describes one submission and contains a submission time (measured in seconds from the beginning of the contest), a team identifier, a problem identifier and a result of evaluating the submission separated by single spaces. The submission time is a positive integer not greater then 18000. The team identifier is a non-empty string consisting of at most five small letters or digits. The problem identifier is a capital letter A, B, ..., or I. The result is a capital letter A (the submission is accepted) or R (the submission is rejected).

Submissions are given in nondecreasing order according to submission times and there are 62 teams competing.

Please note that if a problem is accepted all further submission of this problem by the same team are possible but they should not be taken to the statistics.

Output

For each test case the output consists of nine lines. The first line corresponds to problem A, the second line to problem B, and so on. Each line should contain the problem identifier, the number of accepted solutions of the problem, the average number of submissions done by teams that solved that problem and the average time consumed to solve it separated by single spaces. The latter two statistics should be printed only if there was at least one accepted solution of the given problem and should be rounded to two fractional digits (in particular 1.235 should be rounded to 1.24).

Example

Sample input:
1
12 
10 wawu1 B R 
100 chau1 A A 
2000 uwr2 B A 
2010 wawu1 A R 
2020 wawu1 A A 
2020 wawu1 B A 
4000 wawu2 C R 
6000 chau1 A R 
7000 chau1 A A 
8000 pp1 A A 
8000 zil2 B R 
9000 zil2 B A 

Sample output:
A 3 1.33 3373.33 
B 3 1.67 4340.00 
C 0 
D 0 
E 0 
F 0 
G 0 
H 0 
I 0 

Added by:Adrian Kosowski
Date:2004-06-26
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Central European Programming Contest, Warsaw 2003









SPOJ Problem Set (classical)

83. Bundling

Problem code: BUNDLE

Outel, a famous semiconductor company, recently released a new model of microprocessor called Platinium. Like many modern processors, Platinium can execute many instructions in one clock step providing that there are no dependencies between them (instruction I2 is dependent on instruction I1 if for example I2 reads a register that I1 writes to). Some processors are so clever that they calculate on the fly which instructions can be safely executed in parallel. Platinium however expects this information to be explicitly specified. A special marker, called simply a stop, inserted between two instructions indicates that some instructions after the stop are possibly dependent on some instructions before the stop. In other words instructions between two successive stops can be executed in parallel and there should not be dependencies between them.

Another interesting feature of Platinium is that an instruction sequence must be split into groups of one, two or three successive instructions. Each group has to be packed into a container called a bundle. Each bundle has 3 slots and a single instruction can be put into each slot, however some slots may stay empty. Each instruction is categorized into one of 10 instruction types denoted by consecutive capital letters from A to J (instructions of the same type have similar functionality, for example type A groups integer arithmetic instructions and type F groups instructions). Only instructions of certain types are allowed to be packed into one bundle. A template specifies one permissible combination of instruction types within a bundle. A template can also specify a position of a stop in the middle of a bundle (there is at most one such stop allowed). In addition, stops are allowed between any two adjoining bundles. A set of templates is called a bundling profile. When packing instructions into bundles, one has to use templates from bundling profile only.

Although Platinium is equipped with an instruction cache it was found that for maximal performance it is most crucial to pack instructions as densely as possible. Second important thing is to use a small number of stops.

Your task is to write a program for bundling Platinium instructions. For the sake of simplicity we assume that the instructions cannot be reordered.

Task

Write a program that:

Input

The input begins with the integer z, the number of test cases. Then z test cases follow.

The first line of each test case descripition contains two integers t and n separated by a single space. Integer t (1 <= t <= 1500) is the number of templates in the bundling profile. Integer n (1 <= n <= 100000) is the number of instructions to be bundled.

Each of the next t lines specifies one template and contains 3 capital letters t1,t2,t3 with no spaces in between followed by a space and an integer p. Letter ti (A < = ti<= J) is an instruction type allowed in the i-th slot. Integer p (0 <= p <= 2) is the index of the slot after which the stop is positioned (0 means no stop within the bundle).

Each of the next n lines specifies one instruction. The i-th line of these n lines contains one capital letter ci and an integer di, separated by a single space. Letter ci (A <= ci<=J) is the type of the i-th instruction. Integer di (0 < = di < i) is the index of the last instruction (among the previous ones) that the i-th instruction is dependent on (0 means that the instruction is not dependent on any former instruction).

You can assume that for each instruction type c describing an instruction in the instruction sequence there is at least one template containing c.

Output

For each test case, the first and only line of the output contains two integers b and s. Integer b is the minimal number of bundles in a valid packing. Integer s is the minimal number of all stops that are required for the minimal number of bundles.

Example

Sample input:
1
4 9 
ABB 0 
BAD 1 
AAB 0 
ABB 2 
B 0 
B 1 
A 1 
A 1 
B 4 
D 0 
A 0 
B 3 
B 0 

Sample output: 
4 3 
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-26
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2003









SPOJ Problem Set (classical)

84. Shortcut

Problem code: SHORTCUT


Mirek has a favourite way from home to the university that he traverses every working day. The route consists of sections and each section is a straight segment 10 meters long. Each section is either a straight ahead extension of the previous section or it is perpendicular to the previous section. After traversing each section Mirek takes a small break to admire the beauty of the nature. During his walk he never visits the same place twice.

A sample map

Yesterday Mirek stayed up long in the night at the party and today he got up late from bed. He knows that he will miss the first lecture unless he changes his usual route. He plans to make one shortcut but he wants the shortcut to be as short as possible (well, we can tell you in secret that he doesn't want to be on time, he just wants to calm his conscience). The shortcut must be either a horizontal or vertical segment connecting two break points of Mirek's route.

Please help Mirek find the shortest shortcut.

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case, the first line of the input contains one integer n (3 <= n <= 250 000) being the number of sections of the route. The second line of the input contains a sequence of n characters N, E, S or W with no spaces in between. Each character is a description of one section of the route. Character N, E, S or W means that Mirek walks 10 meters north, east, south or west respectively. You may assume that at least one shortcut exists for the given route.

Output

The first and only line of the output contains integers l, b, e and character d separated by single spaces. Integer l is the length of the shortest shortcut (measured in 10 m segments). Integers b and e are the numbers of break points where the shortcut begins and ends respectively (we number break points with consecutive integers from 0 for Mirek's home to n for the university). Character d is the direction of the shortcut. If more than one shortcut of the minimal length exists you should output the one that begins earliest on the route. If more than one shortcut of the minimal length begins at the same break point you should output the one that ends furthest on the route.

Example

Sample input:
1
12 
NNNENNWWWSSW 

Sample output:
2 3 11 W 
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-26
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2003









SPOJ Problem Set (classical)

85. Dice Contest

Problem code: DICE1


Everyone loves gambling in the Dicent City. Every Saturday the whole community meets to attend a dice contest. They started a few years ago with a classic six-sided die with 1 to 6 dots displayed on the sides and had a lot of fun.

A die

However they soon got bored and that's why more sophisticated dice are in use nowadays. They put a sticker on each side and write a positive integer on each sticker.

The contest is run on a strip divided into squares in a chessboard-like manner. The strip is 4 squares wide and infinite to the left and to the right (is anyone going to say it can't exist in the real world, huh?). The rows of the strip are numbered from 1 to 4 from the bottom to the top and the columns are numbered by consecutive integers from the left to the right. Each square is identified by a pair (x,y) where x is a column number and y is a row number.

The game begins with a die placed on a square chosen be a contest committee with one-dot side on the top and two-dots side facing the player. To move the die the player must roll the die over an edge to an adjacent (either horizontally or vertically) square. The number displayed on the top of the die after a roll is the cost of the move. The goal of the game is to roll the die from the starting square to the selected target square so that the sum of costs of all moves is minimal.

Task

Write a program that:

Note: all teams participating in the contest received dice from the organisers.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line of the input contains six integers l1, l2, l3, l4, l5, l6 (1 < = li < = 50) separated by single spaces. Integer li is the number written on a side having originally i dots. The second line of the input contains four integers x1, y1, x2, y2 ( -109 < = x1, x2 < = 109, 1 <= y1, y2 < = 4) separated by single spaces. Integers x1, y1 are the column and the row number of the starting square respectively. Integers x2, y2 are the column and the row number of the target square respectively.

Output

For each test case the first and the only line of the output should contain the minimal cost of rolling the die from the starting square to the target square.

Example

Sample input:
1
1 2 8 3 1 4 
-1 1 0 2 

Sample output:
7 

Added by:Adrian Kosowski
Date:2004-06-26
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Warsaw 2003









SPOJ Problem Set (classical)

86. November Rain

Problem code: RAIN1

Contemporary buildings can have very complicated roofs. If we take a vertical section of such a roof it results in a number of sloping segments. When it is raining the drops are falling down on the roof straight from the sky above. Some segments are completely exposed to the rain but there may be some segments partially or even completely shielded by other segments. All the water falling onto a segment as a stream straight down from the lower end of the segment on the ground or possibly onto some other segment. In particular, if a stream of water is falling on an end of a segment then we consider it to be collected by this segment.

Rooftops

For the purpose of designing a piping system it is desired to compute how much water is down from each segment of the roof. To be prepared for a heavy November rain you should count one liter of rain water falling on a meter of the horizontal plane during one second.

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line of the input contains one integer n (1 <= n < = 40000) being the number of segments of the roof. Each of the next n lines describes one segment of the roof and contains four integers x1, y1, x2, y2 (0 <= x1, y1, x2, y2 < = 1000000, x1 < x2, y1<>y2) separated by single spaces. Integers x1, y1 are respectively the horizontal position and the height of the left end of the segment. Integers x2, y2 are respectively the horizontal position and the height of the right end of the segment. The segments don't have common points and there are no horizontal segments. You can also assume that there are at most 25 segments placed above any point on the ground level.

Output

For each test case the output consists of n lines. The i-th line should contain the amount of water (in liters) down from the i-th segment of the roof in one second.

Example

Sample input:
1
6 
13 7 15 6 
3 8 7 7 
1 7 5 6 
5 5 9 3 
6 3 8 2 
9 6 12 8 

Sample output:
2 
4 
2 
11 
0 
3 
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-26
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2003









SPOJ Problem Set (classical)

87. Football

Problem code: FOOTBALL

Eric has a classic football that is made of 32 pieces of leather: 12 black pentagons and 20 white hexagons. Each pentagon adjoins 5 hexagons and each hexagon adjoins 3 pentagons and 3 hexagons. Eric drew a polygon (i.e. a closed line without intersections) along the edges of the pieces. The polygon divided the ball into two parts and Eric painted one of them green.

Eric's football

He is curious if given a description of the polygon you are able to compute the number of black, white and green pieces?

Task

Write a program that:

Contest note: the first accepted solution will be awarded with the original football used for preparing the problem, signed by Eric, the author of the problem!

SPOJ note: the first accepted solution will be awarded some other sphere, without anybody's signatures, sent in PNG format to the author's email address [the offer is invalid, the sphere has already been presented to Robin Nittka, University of Ulm, Germany].

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case, the first line of the input contains one integer n being the number of vertices of the polygon. The second line of the input contains n integers a1, a2,..., an separated by single spaces. Integer ai (equal 1 or 2) is the number of green pieces adjoining the i-th vertex of the polygon. The side of the polygon connecting the n-th and the first vertex always lies between two hexagons.

Output

For each test case the first and only line of the output contains three integers b, w and g - the numbers of black, white and green pieces respectively.

Example

Sample input:
1
21 
1 2 1 2 1 2 1 1 1 2 2 1 1 1 1 2 2 2 1 1 1 

Sample output:
11 15 6 

Added by:Adrian Kosowski
Date:2004-06-26
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2003 (E. Kopczynski)









SPOJ Problem Set (classical)

88. Which is Next

Problem code: TREE2

Every computer science student knows binary trees. Here is one of many possible definitions of binary trees. Binary trees are defined inductively. A binary tree t is either an external node (leaf) o or an ordered pair t = (t1, t2) representing an internal node * with two subtrees attached, left subtree t1 and right subtree t2. Under this definition the number of nodes in any binary tree is odd. Given an odd integer n let B(n) denote the set of all binary trees with n nodes, both internal and external. For instance B(1) consists of only one tree o, B(3) = {(o, o)} and B(5) = {(o, (o, o)), ((o, o), o)}. The trees of B(5) are depicted in the figure below.

The trees B(5)

Denote by |t| the number of nodes in a tree t. Given a tree t we define its unique integer identifier N (t) as follows:

For instance, N (o,o) = 22 + 21 * 0 + 0 = 4, N (o, (o, o)) = 24 + 23 * 0 + 4 = 20,
N ((o, o), o) = 24 + 21 * 4 + 0 = 24.

Consider the following linear order on all binary trees:

1) o < = t
2) (t1, t2) < = (u1, u2) when t1 < u1, or t1 = u1 and t2 < = u2

In this order a single leaf o is the smallest tree and given two nonleaf trees, the smaller one is that with the smaller left tree, if the left subtrees are different, and that with the smaller right subtree, otherwise. Hence for instance (o, (o, o)) < ((o, o), o), since we have o < (o, o). Assume now that the trees in B(n) were sorted using the relation < =. Then, for each tree t in B(n) we define the successor of t as the tree that immediately follows t in B(n). If t is the largest one in B(n) then the successor of t is the smallest tree in set B(n). For instance, the successor of (o, o) in B(3) is the same tree (o, o) and the successor of (o, (o, o)) in B(5) is ((o, o), o). Given the integer identifier of some tree t can you give the identifier of the successor of t in B(|t|)?

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first and only line of the input contains one integer n (0 <= n < = 230) - the identifier of some binary tree t.

Output

For each test case the first and only line of the output should contain one integer s - the identifier of the successor of t in B(|t|).

Example

Sample input:
1
20
 
Sample output:
24

Added by:Adrian Kosowski
Date:2004-06-26
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Warsaw 2003









SPOJ Problem Set (classical)

89. Hang or not to hang

Problem code: HANGLET

Little Tom is learning how to program. He has just written some programs but is afraid to run them, because he does not know if they will ever stop. Please write a program to help him. This task is not as easy as it may seem, because Tom's programs are possibly not deterministic. Given a program written by Tom, your program should tell him whether his program can stop and if so, what is the shortest possible time before it stops.

Tom's computer consists of 32 1-bit registers and the program consists of n instructions. The registers are numbered from 0 to 31 and the instructions are numbered from 0 to n-1.

Below, MEM[a] stands for the contents of the a-th register, 0 <= a, b < 32, 0 <= x < n, 0 <= c <= 1.

The instruction set is as follows:


Instruction Semantics
AND a b MEM[a] := MEM[a] and MEM[b] OR a b MEM[a] := MEM[a] or MEM[b] XOR a b MEM[a] := MEM[a] xor MEM[b] NOT a MEM[a] := not MEM[a] MOV a b MEM[a] := MEM[b] SET a c MEM[a] := c RANDOM a MEM[a] := random value (0 or 1) JMP x jump to the instruction with the number x JZ x a jump to the instruction with the number x if MEM[a] = 0 STOP stop the program

The last instruction of a program is always STOP (although there can be more than one STOP instruction). Every program starts with the instruction number 0. Before the start, the contents of the registers can be arbitrary values. Each instruction (including STOP) takes 1 processor cycle to execute.

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line of the input contains an integer n (1 <= n <= 16) being the number of instructions of the program. Each of the next n lines contains one instruction of the program in the format given above. You may assume that the only white characters in the program are single spaces between successive tokens of each instruction.

Output

For each test case the first and only line of the output should contain the shortest possible running time of the program, measured in processor cycles. If the program cannot stop, output should contain the word HANGS.

Example

Sample input:
2
5 
SET 0 1 
JZ 4 0 
RANDOM 0 
JMP 1 
STOP 
5 
MOV 3 5 
NOT 3 
AND 3 5 
JZ 0 3 
STOP 
Sample output:
6 
HANGS

Added by:Adrian Kosowski
Date:2004-06-26
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2003









SPOJ Problem Set (classical)

90. Minimizing maximizer

Problem code: MINIMAX

The company Chris Ltd. is preparing a new sorting hardware called Maximizer. Maximizer has n inputs numbered from 1 to n. Each input represents one integer. Maximizer has one output which represents the maximum value present on Maximizer's inputs.

Maximizer is implemented as a pipeline of sorters Sorter(i1, j1), ... , Sorter(ik, jk). Each sorter has n inputs and n outputs. Sorter(i, j) sorts values on inputs i, i+1,... , j in non-decreasing order and lets the other inputs pass through unchanged. The n-th output of the last sorter is the output of the Maximizer.

An intern (a former ACM contestant) observed that some sorters could be excluded from the pipeline and Maximizer would still produce the correct result. What is the length of the shortest subsequence of the given sequence of sorters in the pipeline still producing correct results for all possible combinations of input values?

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line of the input contains two integers n and m (2 <= n <= 50000, 1 <= m <= 500000) separated by a single space. Integer n is the number of inputs and integer m is the number of sorters in the pipeline. The initial sequence of sorters is described in the next m lines. The k-th of these lines contains the parameters of the k-th sorter: two integers ik and jk (1 <= ik < jk <= n) separated by a single space.

Output

For each test case the output consists of only one line containing an integer equal to the length of the shortest subsequence of the initial sequence of sorters still producing correct results for all possible data.

Example

Sample input:
1
40 6 
20 30 
1 10 
10 20 
20 30 
15 25 
30 40 

Sample output:
4 
Warning: enormous Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-06-26
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2003









SPOJ Problem Set (classical)

91. Two squares or not two squares

Problem code: TWOSQRS

Given integer n decide if it is possible to represent it as a sum of two squares of integers.

Input

First line of input contains one integer c<=100 - number of test cases. Then c lines follow, each of them consisting of exactly one integer 0<=n<=10^12.

Output

For each test case output Yes if it is possible to represent given number as a sum of two squares and No if it is not possible.

Example

Input:
10
1
2
7
14
49
9
17
76
2888
27

Output:
Yes
Yes
No
No
Yes
Yes
Yes
No
Yes
No

Added by:Pawel Gawrychowski
Date:2004-06-29
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All









SPOJ Problem Set ()

92. Cutting off Squares

Problem code: CUTSQRS

Two players take it in turns to cut off squares from a rectangle. If the lengths of the sides of the rectangle are a and b (a<=b) at the beginning of a player's turn, he may cut off as many squares with a side of length a as he likes (but at least 1 square), provided the square he is cutting off has at least three of its sides lying on the sides of the rectangle he is trimming. After every cut, the cut off square is removed from the rectangle. When the last part of the rectangle is removed, the game ends and the person who cut it off wins.

Michael, a friend of the players', is taking down a log of the games they are playing in the form of a sequence of consecutive numbers, each number denoting how many squares a player cut off in his turn. Since the game is rather slow, Michael is getting a little bored and he has started writing a detailed analysis of the game in his notebook. For given starting dimensions a and b, he always writes down:

After writing for several hours Michael began to worry whether he had enough room left in his notebook for all the information he wanted to write down. Please help him answer this question.

Input

An integer t denoting the number of test cases, (t<=10000) followed by t pairs of integers a, b, (1<=a<=b<=109) given in separate lines.

Output

For each test case, output the number of characters Michael has to write down (excluding spaces).

Example

Sample input:
2
1 1
2 3

Sample output:
7
8

(In the first case Michael has to write '1 1 first', in the second case '2 1 second'.)


Added by:Adrian Kosowski
Date:2004-06-22
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:DASM Programming League 2004 (problemset 1)









SPOJ Problem Set (classical)

94. Numeral System of the Maya

Problem code: MAYA

The Maya lived in Central America during the first millennium. In many regards, they consituted one of the most developed and most fascinating cultures of this epoch. Even though draught animals and the wheel were unknown to the Mayas, they excelled in the fields of weaving, architecture and pottery. But truely breath-taking were their achievements in the fields of astronomy and mathematics. Whilst Europe was trudging through the dark Middle Ages, the Maya determined the solar year to 365.242 days (modern-day measurement: 365.242198) and the lunar cycle to 29.5302 days (modern-day measurement: 29.53059). Such astonishingly precise findings were hardly possible without a powerful numeral system. In this task we will explore the Maya's numeral system.

Maya priests and astronomers used a numerical system to the base of 20. Unusual to their time, their system also included the concepts of digits and of the zero. Both concepts were completely unknown to the Europeans at this time. The first nineteen numbers of the vigesimal system were represented by dots and dashes according to the following table:

The zero was written down as a symbol resembling a shell. Multi-digit numbers (i.e. the numbers bigger than 19) were written in vertical arrangement, with the highest-value digit on top. For example, the number 79 was written as

As can be seen, the second digit possesses a value of 20.

Due to an interference of the two calendar systems of the Maya, the third digit did not hold the value 400 (20x20), as would be expected, but 360. All the following digits were again treated regularly, i.e. the fourth digit counted 7200 (360x20), the fifth 144000 (7200x20), and so on.

Hence, the number 13495 (=1x7200+17x360+8x20+15) was written as follows:

Write a program to convert Maya numbers to decimal numbers!

Input

The input file contains a list of numbers written down in Maya fashion. Of course, dots are represented as points (.), and dashes are represented as hyphens (-). The zero digit, the shell symbol, is written as a capital letter S (S). Description of a Maya number starts with n - the number of the Maya digits. The following n lines contain one digit each. One digit is written from top to bottom using spaces as vertical separators.

One number will not have more than seven digits. Each two numbers are separated by a blank line. Input terminates with n = 0

Output

Your program has to output the value of the number in the input file in the nowadays more common decimal system. One number per line.

Example

Sample input:
1
..

5
... -
. - -
S
S
S

0
Sample output:
2
1231200

Added by:Micha³ Czuczman
Date:2004-07-11
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Swiss Olympiad in Informatics 2004









SPOJ Problem Set (classical)

95. Street Parade

Problem code: STPAR

For sure, the love mobiles will roll again on this summer's street parade. Each year, the organisers decide on a fixed order for the decorated trucks. Experience taught them to keep free a side street to be able to bring the trucks into order.

The side street is so narrow that no two cars can pass each other. Thus, the love mobile that enters the side street last must necessarily leave the side street first. Because the trucks and the ravers move up closely, a truck cannot drive back and re-enter the side street or the approach street.

You are given the order in which the love mobiles arrive. Write a program that decides if the love mobiles can be brought into the order that the organisers want them to be.

Input

There are several test cases. The first line of each test case contains a single number n, the number of love mobiles. The second line contains the numbers 1 to n in an arbitrary order. All the numbers are separated by single spaces. These numbers indicate the order in which the trucks arrive in the approach street. No more than 1000 love mobiles participate in the street parade. Input ends with number 0.

Output

For each test case your program has to output a line containing a single word yes if the love mobiles can be re-ordered with the help of the side street, and a single word no in the opposite case.

Example

Sample input:
5
5 1 2 4 3 
0

Sample output:
yes

Illustration

The sample input reflects the following situation:

The five trucks can be re-ordered in the following way:


Added by:Patryk Pomykalski
Date:2004-07-01
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Swiss Olympiad in Informatics 2004









SPOJ Problem Set (classical)

96. Shopping

Problem code: SHOP

Crowd in the supermarketThe old tube screen to your computer turned out to be the cause of your chronic headaches. You therefore decide to buy one of these new flat TFT monitors. At the entrance of the computer shop you see that it is quite full with customers.

In fact, the shop is rather packed with customers and moving inside involves a certain amount of elbowing. Since you want to return home quickly to complete your half finished SPOJ tasks, you want to sidestep the crowd as much as possible. You examine the situation somewhat closer and realise that the crowding is less in some parts of the shop. Thus, there is reason for hope that you can reach your goal in due time, provided that you take the shortest way. But which way is the shortest way?

You sketch the situation on a piece of paper but even so, it is still a tricky affair. You take out your notebook from your pocket and start to write a program which will find the shortest way for you.

Input

The first line of the input specifies the width w and height h of the shop. Neither dimension exceeds 25.

The following h lines contain w characters each. A letter X symbolises a shelf, the letter S marks your starting position, and the letter D marks the destination (i.e. the square in front of the monitors). All free squares are marked with a digit from 1 to 9, meaning the number of seconds needed to pass this square.

There are many test cases separated by an empty line. Input terminates with width and height equal 0 0.

Output

Your program is to output the minimum number of seconds needed to reach to destination square. Each test case in a separate line. Movements can only be vertical and horizontal. Of course, all movements must take place inside the grid. There will always be a way to reach the destination.

Example

Sample input:
4 3
X1S3
42X4
X1D2

5 5
S5213
2X2X5
51248
4X4X2
1445D

0 0

Sample output:
4
23

Added by:Micha³ Czuczman
Date:2004-07-01
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Swiss Olympiad in Informatics 2004









SPOJ Problem Set (classical)

97. Party Schedule

Problem code: PARTY

You just received another bill which you cannot pay because you lack the money.
Unfortunately, this is not the first time to happen, and now you decide to investigate the cause of your constant monetary shortness. The reason is quite obvious: the lion's share of your money routinely disappears at the entrance of party localities.

You make up your mind to solve the problem where it arises, namely at the parties themselves. You introduce a limit for your party budget and try to have the most possible fun with regard to this limit.

You inquire beforehand about the entrance fee to each party and estimate how much fun you might have there. The list is readily compiled, but how do you actually pick the parties that give you the most fun and do not exceed your budget?

Write a program which finds this optimal set of parties that offer the most fun. Keep in mind that your budget need not necessarily be reached exactly. Achieve the highest possible fun level, and do not spend more money than is absolutely necessary.

Input

The first line of the input specifies your party budget and the number n of parties.

The following n lines contain two numbers each. The first number indicates the entrance fee of each party. Parties cost between 5 and 25 francs. The second number indicates the amount of fun of each party, given as an integer number ranging from 0 to 10.

The budget will not exceed 500 and there will be at most 100 parties. All numbers are separated by a single space.

There are many test cases. Input ends with 0 0.

Output

For each test case your program must output the sum of the entrance fees and the sum of all fun values of an optimal solution. Both numbers must be separated by a single space.

Example

Sample input:

50 10 12 3 15 8 16 9 16 6 10 2 21 9 18 4 12 4 17 8 18 9 50 10 13 8 19 10 16 8 12 9 10 2 12 8 13 5 15 5 11 7 16 2 0 0

Sample output:

49 26 48 32

Added by:Patryk Pomykalski
Date:2004-07-01
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Swiss Olympiad in Informatics 2004









SPOJ Problem Set (classical)

98. Dance Floor

Problem code: DFLOOR


You recently watched a video clip in which a singer danced on a grid of colourful tiles enlightened from below. Each step on a tile flipped the tile's state, i.e. light on or off. In addition to that, all the neighbouring tiles flipped their states, too.

In this task, you are supposed to come up with a short program that decides if it is possible for the singer to switch on the lights of all the tiles, provided that he dances on the appropriate tiles.

The dance floor has rectangular shape. At the beginning, some of the tiles are already alight. Your program may temporarily switch off some tiles, if it deems that necessary to reach its goal. Stepping on a tile toggles its own state as well as the states of the four neighbouring tiles directly above, below, to the left and to the right. Of course, in the case of a peripheral tile, there will be only three or two neighbouring tiles.

Here comes an example:

If the dancer steps on the tile indicated by the brown shoe, all the tiles within the white area change their states. The resulting dance floor is depicted on the right.

You may assume that the singer is fit enough to jump from any tile to any other tile, even if the destination tile lies on the opposite side of the dance floor.

Input

There are several test cases. The first line of each case contains two integer numbers x and y, indicating the width and the height of the dance floor grid. The numbers are separated by a single space and satisfy 3 ≤ x,y ≤ 15.

The following y lines containing xcharacters each describe the initial on/off states of the tiles. A zero means "the tile is switched off", a one digit means "the tile is alight".

Input ends with 0 0.

Output

For each test case your program should output the number of steps needed to switch all the lights on, followed by exactly that many lines with two space-separated numbers i and j. Each individual line commands the singer to step on the i-th tile of the j-th row. Starting with the situation of the input file and executing all the commands in the output file, all the tiles must be switched on.

If more than one solution exist, your program should output an arbitrary one of them. If, on the other hand, no solution exists, your program should write the number "-1".

Example

Sample input

4 3 0111 1010 1000 0 0

Sample output

3 1 2 1 3 4 3

Added by:Micha³ Czuczman
Date:2004-07-01
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Swiss Olympiad in Informatics 2004









SPOJ Problem Set (classical)

99. Bus

Problem code: BUS


The city Buscelona (as the name suggests) has a great bus transport system. All buses have circular lines. The bus drivers in Buscelona like to chat. Fortunately most bus lines have some stops in common. If a bus driver meets a colleague on a bus stop they chat a bit and exchange all news they know.

The operation of buses is highly synchronized. The time necessary to get from one stop to the next stop is always exactly 1 minute.

Each morning each bus driver has some important news that only he knows. When a busdriver meets a colleague he will tell him all news he knows. If two bus drivers share the same start station, they will exchange their news there already (before they start working). Note that exchanging news and stopping does not take any time.

Input

The first line of a test case contains the number of bus lines n (0 < n < 50). The following n lines start with a number s (0 < s < 50) indicating the stops of a busline. On the same line follow s numbers representing a bus station each. A bus starts at the first station. When a bus reaches the last station, the bus will drive to the first station again.

There are many test cases separated by an empty line. Input data terminates with n = 0.

Output

For each test case you should output the time in minutes which it takes until all bus drivers know all news. If that never happens, your program should write the word "NEVER" (without quotes).

Example

Sample input:
3
3 1 2 3
3 2 3 1
4 2 3 4 5

2
2 1 2
2 5 8

0

Sample output:
12
NEVER

Added by:Micha³ Czuczman
Date:2004-07-03
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Swiss Olympiad in Informatics 2004









SPOJ Problem Set (classical)

100. Tower of Babylon

Problem code: BABTWR

Apart from the Hanging Gardens the Babylonians (around 3000-539 b.c.) built the Tower of Babylon as well. The tower was meant to reach the sky, but the project failed because of a confusion of language imposed from much higher above.

For the 2638th anniversary a model of the tower will be rebuilt. n different types of blocks are available. Each one of them may be duplicated as many times as you like. Each type has a height y, a width x and a depth z. The blocks are to be stacked one upon eachother so that the resulting tower is as high as possible. Of course the blocks can be rotated as desired before stacking. However for reasons of stability a block can only be stacked upon another if both of its baselines are shorter.

Input

The number of types of blocks n is located in the first line of each test case. On the subsequent n lines the height yi, the width xi and the depth zi of each type of blocks are given. There are never more than 30 different types available.

There are many test cases, which come one by one. Input terminates with n = 0.

Output

For each test case your program should output one line with the height of the highest possible tower.

Example

Sample input:
5
31 41 59
26 53 58
97 93 23
84 62 64
33 83 27
1
1 1 1
0

Sample output:
342
1

Added by:Micha³ Czuczman
Date:2004-07-06
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Swiss Olympiad in Informatics 2004









SPOJ Problem Set (classical)

101. Fishmonger

Problem code: FISHER

A FishmongerA fishmonger wants to bring his goods from the port to the market. On his route he has to traverse an area with many tiny city states. Of course he has to pay a toll at each border.

Because he is a good business man, he wants to choose the route in such a way that he has to pay as little money for tolls as possible. On the other hand, he has to be at the market within a certain time, otherwise his fish start to smell.

Input

The first line contains the number of states n and available time t. The first state is the port, the last state is the market. After this line there are n lines with n numbers each, specifying for each state the travel time to the i-th state. This table is terminated with an empty line. The table of the tolls follows in the same format.

n is at least 3 and at most 50. The time available is less than 1000. All numbers are integers.

There are many test cases separated by an empty line. Input terminates with number of states and time equal 0 0.

Output

For each test case your program should print on one line the total amount of tolls followed by the actual travelling time.

Example

Sample input:
4 7
0 5 2 3
5 0 2 3
3 1 0 2
3 3 2 0

0 2 2 7
2 0 1 2
2 2 0 5
7 2 5 0

0 0

Sample output:
6 6

This corresponds to the following situation, the connections are labeled with (time, toll):


Added by:Micha³ Czuczman
Date:2004-07-07
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Swiss Olympiad in Informatics 2004









SPOJ Problem Set (classical)

102. GX Light Pipeline Inc

Problem code: LITEPIPE

The GX Light Pipeline Inc. started to prepare bent pipes for the new transgalactic light pipeline. However during the design of the pipeline they ran into the problem of determing how far the light can reach inside the pipe. In order to improve your scarce budget you decided to fill a summer job at the GX Light Pipeline Inc. Now it's your task to create a program which computes how far the light reaches in the pipeline.

The pipeline consists of seamlessly welded together segments made of non-reflecting opaque materials. The upper points of the pipe contour are described by a sequence of points [x1, y1], [x2, y2], [x3, y3], ..., [xn, yn], where xk < xk+1. The bottom points of the pipe contour are the same points with y-coordinate decreased by 1.

The company wants to find the points with maximal x-coordinate that the light will reach. The light is emitted by a segment source with endpoints [x1, y1] and [x1, y1-1] (endpoints are emitting light too). Assume that the light is not bent at the pipe bent points and the bent points do not stop the light beam.

Input

Each test case starts with the number of bent points n. Each of the next n lines contains a pair of real values xi, yi separated by space.

The number of bent points never excedes 200.

There are many test cases. Input terminates with n = 0.

Output

For each test case your program should output on a single line the maximal x-coordinate of the point where the light can reach from the source segment, written with precision of two decimal places. If the light goes trough all the pipe, your program should output xn.

Example

Sample input:
4
0.00 1.00
2.00 2.00
4.00 1.00
6.00 4.00
0

Sample output:
4.67

Added by:Micha³ Czuczman
Date:2004-07-11
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Swiss Olympiad in Informatics 2004









SPOJ Problem Set (classical)

104. Highways

Problem code: HIGH

In some countries building highways takes a lot of time... Maybe that's because there are many possiblities to construct a network of highways and engineers can't make up their minds which one to choose. Suppose we have a list of cities that can be connected directly. Your task is to count how many ways there are to build such a network that between every two cities there exists exactly one path. Two networks differ if there are two cities that are connected directly in the first case and aren't in the second case. At most one highway connects two cities. No highway connects a city to itself. Highways are two-way.

Input

The input begins with the integer t, the number of test cases (equal to about 1000). Then t test cases follow. The first line of each test case contains two integers, the number of cities (1<=n<=12) and the number of direct connections between them. Each next line contains two integers a and b, which are numbers of cities that can be connected. Cities are numbered from 1 to n. Consecutive test cases are separated with one blank line.

Output

The number of ways to build the network, for every test case in a separate line. Assume that when there is only one city, the answer should be 1. The answer will fit in a signed 64-bit integer.

Example

Sample input:
4
4 5
3 4
4 2
2 3
1 2
1 3

2 1
2 1

1 0

3 3
1 2
2 3
3 1

Sample output:
8
1
1
3


Added by:Piotr £owiec
Date:2004-07-02
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All









SPOJ Problem Set (classical)

105. Alice and Bob

Problem code: ALICEBOB

This is a puzzle for two persons, let's say Alice and Bob. Alice draws an n-vertex convex polygon and numbers its vertices with integers 1, 2, ... , n in an arbitrary way. Then she draws a number of noncrossing diagonals (the vertices of the polygon are not considered to be crossing points). She informs Bob about the sides and the diagonals of the polygon but not telling him which are which. Each side and diagonal is specified by its ends. Bob has to guess the order of the vertices on the border of the polygon. Help him solve the puzzle.

If n = 4 and (1,3), (4,2), (1,2), (4,1), (2,3) are the ends of four sides and one diagonal then the order of the vertices on the border of this polygon is 1, 3, 2, 4 (with the accuracy to shifting and reversing).

Task

Write a program that:

Input

The first line of the input contains exactly one positive integer d equal to the number of data sets, 1 <= d <= 20. The data sets follow.

Each data set consists of exactly two consecutive lines.

The first of those lines contains exactly two integers n and m separated by a single space, 3 <= n <= 10 000, 0 <= m <= n-3. Integer n is the number of vertices of a polygon and integer m is the number of its diagonals, respectively.

The second of those lines contains exactly 2(m+n) integers separated by single spaces. Those are ends of all sides and some diagonals of the polygon. Integers aj, bj on positions 2j-1 and 2j, 1 <= j < = m+n, 1 < = aj <= n, 1 < = bj < = n, aj <> bj, specify ends of a side or a diagonal. The sides and the diagonals can be given in an arbitrary order. There are no duplicates. Alice does not cheat, i.e. the puzzle always has a solution.

Output

Line i, 1 <= i < = d, should contain a sequence of n integers separated by single spaces - a permutation of 1, 2, ... , n, i.e. the numbers of subsequent vertices on the border of the polygon from the i-th data set, the sequence should always start from 1 and its second element should be the smaller vertex of the two border neighbours of vertex 1.

Example

Sample input:
1 
4 1 
1 3 4 2 1 2 
4 1 2 3 

Sample output:
1 3 2 4 
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-02
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2001









SPOJ Problem Set ()

106. Binary Stirling Numbers

Problem code: BINSTIRL

The Stirling number of the second kind S(n, m) stands for the number of ways to partition a set of n things into m nonempty subsets. For example, there are seven ways to split a four-element set into two parts: {1, 2, 3} u {4}, {1, 2, 4} u {3}, {1, 3, 4} u {2}, {2, 3, 4} u {1}, {1, 2} u {3, 4}, {1, 3} u {2, 4}, {1, 4} u {2, 3}.

There is a recurrence which allows you to compute S(n, m) for all m and n.
S(0, 0) = 1,
S(n, 0) = 0, for n > 0,
S(0, m) = 0, for m > 0,
S(n, m) = m*S(n-1, m) + S(n-1, m-1), for n, m > 0.

Your task is much "easier". Given integers n and m satisfying 1 <= m <= n, compute the parity of S(n, m), i.e. S(n, m) mod 2.

For instance, S(4, 2) mod 2 = 1.

Task

Write a program that:

Input

The first line of the input contains exactly one positive integer d equal to the number of data sets, 1 <= d <= 200. The data sets follow.

Line i + 1 contains the i-th data set - exactly two integers ni and mi separated by a single space, 1 < = mi < = ni <= 109.

Output

The output should consist of exactly d lines, one line for each data set. Line i, 1 <= i < = d, should contain 0 or 1, the value of S(ni, mi) mod 2.

Example

Sample input:
1 
4 2 

Sample output:
1 

Added by:Adrian Kosowski
Date:2004-07-02
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Central European Programming Contest, Warsaw 2001









SPOJ Problem Set (classical)

107. Calendar of the Maya

Problem code: MAYACAL

The Classical Maya civilization developed in what is today southern Mexico, Guatemala, Belize and northern Honduras. During its height they developed a sophisticated system for time keeping which they used both to record history and for divinatory rituals. Their calendar consisted of 3 components. the Tzolkin, the Haab and the Long Count.

For divinatory purposes the Maya used the Tzolkin which was composed of 20 day names to which numeric coefficients from 1 to 13 were attached giving a total of 260 distinct combinations. This is the size of the Tzolkin, or ritual, year. From Spanish colonial sources, we know the names of the days: Imix, Ik, Akbal, Kan, Chikchan, Kimi, Manik, Lamat, Muluk, Ok, Chuen, Eb, Ben, Ix, Men, Kib, Kaban, Etznab, Kawak, Ajaw. The sequence of days developed as follows (starting for example at 9 Imix):

9 Imix, 10 Ik, 11 Akbal, 12 Kan, 13 Chikchan, 1 Kimi, 2 Manik, ...

The Haab calendar was an astronomical one. It had 365 days divided into 19 months each with 20 days, except the last one which had only 5 days. In a manner similar to the Tzolkin each month name had a number from 1 to 20 indicating the day number within the month. Again, from Spanish colonial sources, we know the names of the months: Pohp, Wo, Sip, Zotz, Sek, Xul, Yaxkin, Mol, Chen, Yax, Sak, Keh, Mak, Kankin, Muan, Pax, Kayab, Kumku, Wayeb. The month Wayeb had just 5 days and was considered an unlucky time of the year.

The Tzolkin and Haab were combined in the inscriptions to create the Calendar Round, combining the 260 day cycle of the Tzolkin and the 365 day cycle of the Haab. A typical Calendar Round date in the inscriptions might be. 3 Lamat 6 Pax. Note that not all of the combination of days, months and coefficients are possible.

A typical sequence of days in the Calendar Round (starting for example at 3 Lamat 6 Pax):

3 Lamat 6 Pax, 4 Muluk 7 Pax, 5 Ok 8 Pax, 6 Chuen 9 Pax, 7 Eb 10 Pax, 
8 Ben 11 Pax, 9 Ix 12 Pax, 10 Men 13 Pax, 11 Kib 14 Pax, 12 Kaban 15 Pax, 
13 Etznab 16 Pax, 1 Kawak 17 Pax, 2 Ajaw 18 Pax, 3 Imix 19 Pax, 4 Ik 20 Pax, 
5 Akbal 1 Kayab, 6 Kan 2 Kayab, ... 

Finally, at the beginning of the Classic Period (AD 200 - 900), the Maya developed an absolute calendar called Long Count which counted the days from a fixed date in the past (the date when the current world was created according to Maya belief). Dates in the Long Count are given (for simplicity) in 5-tuples of the form. 9.2.3.4.5. Such a date one reads "9 baktuns 2 katuns 3 tuns 4 winals 5 kins since the zero date". A "kin" is just one day. A winal is a group of 20 days. A tun is a group of 18 winals (thus a tun has 20*18 = 360 days, 5 days short of a year). From here on all units come in multiples of 20. Thus a katun is equal to 20 tuns (almost 20 years) and a baktun means 20 katuns (almost 400 years). Thus 9.2.3.4.5 really means "9*144000+2*7200+3*360+4*20+5 days since the zero date". Note that for every Long Count date b.k.t.w.i we have 0 <= k < 20; 0 <= t < 20; 0 <= w < 18; 0 <= i < 20. Given the periodicity of the Calendar Round, a legal date such as 3 Lamat 6 Pax has multiple occurrences in the Long Count. Thus, one difficulty in reading inscriptions is in establishing a date for the inscription when the date is given only in terms of a Calendar Round (very common). In this case one must compute "all" the possible Long Count dates associated with the particular Calendar Round and based in some other context information deduce (for example, the text mentions a king for which other dates are known) which one applies.

We limit our interest to the Long Count dates in the baktuns 8 and 9 (they cover all the Classic Period). We know that the Long Count date 8.0.0.0.0 fell on the Calendar Round 9 Ajaw 3 Sip.

Task

Write a program that:

Input

The first line of the input contains exactly one positive integer d equal to the number of data sets, 1 <= d <= 30. The data sets follow.

Each data set consists of exactly one line that contains exactly one Calendar Round date (maybe illegal). Tzolkin day number, Tzolkin day name, Haab day number and Haab month name separated by single spaces.

Output

For every data set your program must output an ascending sequence of Long Count dates computed for a given Calendar Round date. The first line of the output for the given input set should contain exactly one integer n equal to the length of the sequence (0, if the input date is illegal).

Each of the next n lines should contain exactly one Long Count date specified by exactly 5 integers (meaning the numbers of baktuns, katuns, tuns, winals and kins respectively) separated by single dots.

Example

Sample input:
2 
3 Lamat 6 Pax 
1 Ajaw 9 Chen 

Sample output:
15 
8.0.17.17.8 
8.3.10.12.8 
8.6.3.7.8 
8.8.16.2.8 
8.11.8.15.8 
8.14.1.10.8 
8.16.14.5.8 
8.19.7.0.8 
9.1.19.13.8 
9.4.12.8.8 
9.7.5.3.8 
9.9.17.16.8 
9.12.10.11.8 
9.15.3.6.8 
9.17.16.1.8 
0 


Added by:Adrian Kosowski
Date:2004-07-02
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2001









SPOJ Problem Set (classical)

108. Decoding Morse Sequences

Problem code: MORSE


Before the digital age, the most common "binary" code for radio communication was the Morse code. In Morse code, symbols are encoded as sequences of short and long pulses (called dots and dashes respectively). The following table reproduces the Morse code for the alphabet, where dots and dashes are represented as ASCII characters "." and "-":

A .-   B -... C -.-. D -.. 
E .    F ..-. G --.  H .... 
I ..   J .--- K -.-  L .-.. 
M --   N -.   O ---  P .--. 
Q --.- R .-.  S ...  T - 
U ..-  V ...- W .--  X -..- 
Y -.-- Z --..

Notice that in the absence of pauses between letters there might be multiple interpretations of a Morse sequence. For example, the sequence -.-..-- could be decoded both as CAT or NXT (among others). A human Morse operator would use other context information (such as a language dictionary) to decide the appropriate decoding. But even provided with such dictionary one can obtain multiple phrases from a single Morse sequence.

Task

Write a program that:

Notice that we are interested in full matches, i.e. the complete Morse sequence must be matched to words in the dictionary.

Input

The first line of the input contains exactly one positive integer d equal to the number of data sets, 1 <= d <= 20. The data sets follow.

The first line of each data set contains a Morse sequence - a nonempty sequence of at most 10000 characters "." and "-" with no spaces in between.

The second line contains exactly one integer n, 1 <= n <= 10000, equal to the number of words in a dictionary. Each of the following n lines contains one dictionary word - a nonempty sequence of at most 20 capital letters from "A" to "Z". No word occurs in the dictionary more than once.

Output

The output should consist of exactly d lines, one line for each data set. Line i should contain one integer equal to the number of distinct phrases into which the Morse sequence from the i-th data set can be parsed. You may assume that this number is at most 2*109 for every single data set.

Example

Sample input:
1 
.---.--.-.-.-.---...-.---. 
6 
AT 
TACK 
TICK 
ATTACK 
DAWN 
DUSK 

Sample output:
2 

Added by:Adrian Kosowski
Date:2004-07-02
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2001









SPOJ Problem Set ()

109. Exchanges

Problem code: EXCHNG

Given n integer registers r1, r2, ... , rn we define a Compare-Exchange Instruction CE(a,b), where a, b are register indices (1 <= a < b <= n):

CE(a, b):: 
  if content(ra) >  content(rb) then 
     exchange the contents of registers ra and rb; 

A Compare-Exchange program (shortly CE-program) is any finite sequence of Compare-Exchange instructions. A CE-program is called a Minimum-Finding program if after its execution the register r1 always contains the smallest value among all values in the registers. Such a program is called reliable if it remains a Minimum-Finding program after removing any single Compare-Exchange instruction. Given a CE-program P, what is the smallest number of instructions that should be added at the end of program P in order to get a reliable Minimum-Finding program?

For instance, consider the following CE-program for 3 registers: CE(1, 2), CE(2, 3), CE(1, 2). In order to make this program a reliable Minimum-Finding program it is sufficient to add only two instructions: CE(1, 3) and CE(1, 2).

Task

Write a program that:

Input

The first line of the input contains exactly one positive integer d equal to the number of data sets, 1 <= d <= 10. The data sets follow.

Each data set consists of exactly two consecutive lines. The first of those lines contains exactly two integers n and m separated by a single space, 2 <= n <= 10000, 0 <= m <= 25000. Integer n is the number of registers and integer m is the number of program instructions.

The second of those lines contains exactly 2m integers separated by single spaces - the program itself. Integers aj, bj on positions 2j-1 and 2j, 1 <= j < = m, 1 < = aj < bj <= n, are parameters of the j-th instruction in the program.

Output

The output should consist of exactly d lines, one line for each data set. Line i, 1 <= i <= d, should contain only one integer - the smallest number of instructions that should be added at the end of the i-th input program in order to make this program a reliable Minimum-Finding program.

Example

Sample input:
1 
3 3 
1 2 2 3 1 2

Sample output:
2 

Added by:Adrian Kosowski
Date:2004-07-02
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2001









SPOJ Problem Set (classical)

110. Fill the Cisterns

Problem code: CISTFILL


During the next century certain regions on earth will experience severe water shortages. The old town of Uqbar has already started to prepare itself for the worst. Recently they created a network of pipes connecting the cisterns that distribute water in each neighbourhood, making it easier to fill them at once from a single source of water. But in case of water shortage the cisterns above a certain level will be empty since the water will flow to the cisterns below.

Example of cistern arrangement

You have been asked to write a program to compute the level to which cisterns will be filled with a certain volume of water, given the dimensions and position of each cistern. To simplify we will neglect the volume of water in the pipes.

Task

Write a program that:

Input

The first line of the input contains the number of data sets k, 1 <= k <= 30. The data sets follow.

The first line of each data set contains one integer n, the number of cisterns, 1 <= n <= 50000. Each of the following n lines consists of 4 nonnegative integers, separated by single spaces: b, h, w, d - the base level of the cistern, its height, width and depth in meters, respectively. The integers satisfy 0 <= b <= 106 and 1 <= h*w*d <= 40000. The last line of the data set contains an integer V - the volume of water in cubic meters to be injected into the network. Integer V satisfies 1 <= V <= 2*109.

Output

The output should consist of exactly d lines, one line for each data set. Line i, 1 <= i <= d, should contain the level that the water will reach, in meters, rounded to two fractional digits, or the word "OVERFLOW" (without quotes), if the volume of water exceeds the total capacity of the cisterns.

Example

Sample input:
3 
2 
0 1 1 1 
2 1 1 1 
1 
4 
11 7 5 1 
15 6 2 2 
5 8 5 1 
19 4 8 1 
132 
4 
11 7 5 1 
15 6 2 2 
5 8 5 1 
19 4 8 1 
78 

Sample output:
1.00 
OVERFLOW 
17.00 
Warning: enormous Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-02
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2001









SPOJ Problem Set (classical)

112. Horizontally Visible Segments

Problem code: SEGVIS

There is a number of disjoint vertical line segments in the plane. We say that two segments are horizontally visible if they can be connected by a horizontal line segment that does not have any common points with other vertical segments. Three different vertical segments are said to form a triangle of segments if each two of them are horizontally visible. How many triangles can be found in a given set of vertical segments?

Task

Write a program that:

Input

The first line of the input contains exactly one positive integer d equal to the number of data sets, 1 <= d <= 20. The data sets follow.

The first line of each data set contains exactly one integer n, 1 <= n < = 8000, equal to the number of vertical line segments.

Each of the following n lines consists of exactly 3 nonnegative integers separated by single spaces: y'i, y''i, xi(that is the y-coordinate of the beginning of a segment, y-coordinate of its end and its x-coordinate, respectively). The coordinates satisfy: 0 < = y'i< y''i <= 8000, 0 < = xi <= 8000. The segments are disjoint.

Output

The output should consist of exactly d lines, one line for each data set. Line i should contain exactly one integer equal to the number of triangles in the i-th data set.

Example

Sample input:
1 
5 
0 4 4 
0 3 1 
3 4 2 
0 2 2 
0 2 3 

Sample output:
1 

Added by:Adrian Kosowski
Date:2004-07-02
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2001









SPOJ Problem Set ()

115. Family

Problem code: FAMILY

We want to find out how much related are the members of a family of monsters. Each monster has the same number of genes but the genes themselves may differ from monster to monster. It would be nice to know how many genes any two given monsters have in common. This is impossible, however, since the number of genes is very large. Still, we do know the family tree (well, not actually a tree, but you cannot really blame them, these are monsters, right?) and we do know how the genes are inherited so we can estimate the number of common genes quite well.

The inheritance rule is very simple: if a monster C is a child of monsters A and B then each gene of C is identical to the corresponding gene of either A or B, each with probability 50%. Every gene of every monster is inherited independently.

Let us define the degree of relationship of monsters X and Y as the expected number of common genes. For example consider a family consisting of two completely unrelated (i.e. having no common genes) monsters A and B and their two children C and D. How much are C and D related? Well, each of C's genes comes either from A or from B, both with probability 50%. The same is true for D. Thus, the probability of a given gene of C being the same as the corresponding gene of D is 50%. Therefore the degree of relationship of C and D (the expected number of common genes) is equal to 50% of all the genes. Note that the answer would be different if A and B were related. For if A and B had common genes, these would be necessarily inherited by both C and D.

Your task is to write a program that, given a family graph and a list of pairs of monsters, computes the degree of relationship for each of these pairs.

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line of the input contains two integers n and k separated by a single space. Integer n (2 <= n <= 300) is the number of members in a family. Family members are numbered arbitrarily from 1 to n. Integer k (0 <= k <= n - 2) is the number of monsters that do have parents (all the other monsters were created by gods and are completely unrelated to each other).

Each of the next k lines contains three different integers a, b, c separated by single spaces. The triple a, b, c means that the monster a is a child of monsters b and c.

The next input line contains an integer m (1 <= m < = n2) - the number of pairs of monsters on the list. Each of the next m lines contains two integers separated by a single space - these are the numbers of two monsters.

You may assume that no monster is its own ancestor. You should not make any additional assumptions on the input data. In particular, you should not assume that there exists any valid sex assignment.

Output

For each test case the output consists of m lines. The i-th line corresponds to the i-th pair on the list and should contain single number followed by the percentage sign. The number should be the exact degree of relationship (in percentages) of the monsters in the i-th pair. Unsignificant zeroes are not allowed in the output (please note however that there must be at least one digit before the period sign so for example the leading zero in number 0.1 is significant and you cannot print it as .1). Confront the example output for the details of the output format.

Example

Sample input:
1
7 4
4 1 2
5 2 3
6 4 5
7 5 6
4
1 2
2 6
7 5
3 3

Sample output:
0%
50%
81.25%
100%
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-07
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Warsaw 2002









SPOJ Problem Set (classical)

116. Intervals

Problem code: INTERVAL

You are given n closed integer intervals [ai, bi] and n integers c1, ..., cn.

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line of the input contains an integer n (1 <= n <= 50000) - the number of intervals. The following n lines describe the intervals. Line (i+1) of the input contains three integers ai, bi and ci separated by single spaces and such that 0 < = ai < = bi <= 50000 and 1 < = ci < = bi -ai +1.

Output

For each test case the output contains exactly one integer equal to the minimal size of set Z sharing at least ci elements with interval [ai, bi], for each i= 1, 2, ..., n.

Example

Sample input:
1
5
3 7 3
8 10 3
6 8 1
1 3 1
10 11 1

Sample output:
6
Warning: enormous Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-07
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2002









SPOJ Problem Set ()

118. Rhombs

Problem code: RHOMBS

An unbounded triangular grid is a plane covered by equilateral triangles:

rhombs

Two neighboring triangles in the grid form a rhomb. There are 3 types of such rhombs:

rhombs

A grid polygon is a simple polygon which sides consist entirely of sides of triangles in the grid. We say that a grid polygon is rhombastic if it can be partitioned into internally disjoint rhombs of types A, B and C.

As an example let's consider the following grid hexagon:

rhombs

This hexagon can be partitioned into 4 rhombs of type A, 4 rhombs of type B and 4 rhombs of type C:

rhombs

For a given rhombastic grid polygon P compute the numbers of rhombs of types A, B and C in some correct partition.

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line of the input contains an integer n (3 <= n <= 50000) - the number of sides of a rhombastic grid polygon. Each of the next n lines contains a description of one side of the polygon. The sides are given one by one in the clockwise order. No two consecutive sides of the polygon lie on the same straight line. The description of a side consists of two integers d and k. Integer d says what is the direction of the side according to the following figure:

rhombs

Integer k is the length of the polygon side measured in the number of sides of grid triangles. Sum of all numbers k is not larger than 100000.

Output

For each test case the first and only line of the output contains three integers separated by single spaces denoting the number of rhombs of type A, B and C respectively, in some partition of the input polygon.

Example

Sample input:
1
6 
1 2 
2 2 
3 2 
4 2 
5 2 
6 2 

Sample output:
4 4 4

Added by:Adrian Kosowski
Date:2004-07-07
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Central European Programming Contest, Warsaw 2002









SPOJ Problem Set ()

119. Servers

Problem code: SERVERS


The Kingdom of Byteland decided to develop a large computer network of servers offering various services.

The network is built of n servers connected by bidirectional wires. Two servers can be directly connected by at most one wire. Each server can be directly connected to at most 10 other servers and every two servers are connected with some path in the network. Each wire has a fixed positive data transmission time measured in milliseconds. The distance (in milliseconds) D(V, W) between two servers V and W is defined as the length of the shortest (transmission time-wise) path connecting V and W in the network. For convenience we let D(V, V) = 0 for all V.

Some servers offer more services than others. Therefore each server V is marked with a natural number r(V), called a rank. The bigger the rank the more powerful a server is.

At each server, data about nearby servers should be stored. However, not all servers are interesting. The data about distant servers with low ranks do not have to be stored. More specifically, a server W is interesting for a server V if for every server U such that D(V, U) <= D(V, W) we have r(U) <= r(W).

For example, all servers of the maximal rank are interesting to all servers. If a server V has the maximal rank, then exactly the servers of the maximal rank are interesting for V . Let B(V) denote the set of servers interesting for a server V.

We want to compute the total amount of data about servers that need to be stored in the network being the total sum of sizes of all sets B(V). The Kingdom of Byteland wanted the data to be quite small so it built the network in such a way that this sum does not exceed 30*n.

Task

Write a program that:

Input

The input begins with the integer z, the number of test cases. Then z test cases follow.

For each test case, in the first line there are two natural numbers n, m, where n is the number of servers in the network (1 <= n <= 30000) and m is the number of wires (1 <= m <= 5n). The numbers are separated by single space.

In the next n lines the ranks of the servers are given. Line i contains one integer ri (1 <= ri <= 10) - the rank of i-th server.

In the following m lines the wires are described. Each wire is described by three numbers a, b, t (1 <= t <= 1000, 1 <= a, b <= n, a <> b), where a and b are numbers of the servers connected by the wire and t is the transmission time of the wire in milliseconds.

Output

For each test case the output consists of a single integer equal to the total amount of data about servers that need to be stored in the network.

Example

Sample input:
1
4 3
2
3
1
1
1 4 30
2 3 20
3 4 20

Sample output:
9

(because B(1) = {1, 2}, B(2) = {2}, B(3) = {2, 3}, B(4) = {1, 2, 3, 4})

Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-07
Time limit:12s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Central European Programming Contest, Warsaw 2002









SPOJ Problem Set (classical)

120. Solitaire

Problem code: SOLIT

Solitaire is a game played on an 8x8 chessboard. The rows and columns of the chessboard are numbered from 1 to 8, from the top to the bottom and from left to right respectively.

There are four identical pieces on the board. In one move it is allowed to:

possible moves in solitaire

There are 4 moves allowed for each piece in the configuration shown above. As an example let's consider a piece placed in the row 4, column 4. It can be moved one row up, two rows down, one column left or two columns right.

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case, each of two input lines contains 8 integers a1, a2, ..., a8 separated by single spaces and describes one configuration of pieces on the chessboard. Integers a2j-1 and a2j (1 <= j <= 4) describe the position of one piece - the row number and the column number respectively.

Output

For each test case the output should contain one word for each test case - `YES' if a configuration described in the second input line is reachable from the configuration described in the first input line in at most 8 moves, or one word `NO' otherwise.

Example

Sample input:
1
4 4 4 5 5 4 6 5
2 4 3 3 3 6 4 6

Sample output:
YES

Added by:Adrian Kosowski
Date:2004-07-07
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2002









SPOJ Problem Set (classical)

121. Timetable

Problem code: TTABLE

You are the owner of a railway system between n cities, numbered by integers from 1 to n. Each train travels from the start station to the end station according to a very specific timetable (always on time), not stopping anywhere between. On each station a departure timetable is available. Unfortunately each timetable contains only direct connections. A passenger that wants to travel from city p to city q is not limited to direct connections however - he or she can change trains. Each change takes zero time, but a passenger cannot change from one train to the other if it departs before the first one arrives. People would like to have a timetable of all optimal connections. A connection departing from city p at A o'clock and arriving in city q at B o'clock is called optimal if there is no connection that begins in p not sooner than at A, ends in q not later than at B, and has strictly shorter travel time than the considered connection. We are only interested in connections that can be completed during same day.

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line of the input contains an integer n (2 <= n <= 100000). The following lines contain n timetables for cities 1, 2, ..., n respectively.

The first line of the timetable description contains only one integer m. Each of the following m lines corresponds to one position in the timetable and contains: departure time A, arrival time B (A < B) and destination city number t (1 <= t <= n) separated by single spaces. Departure time A and arrival time B are written in format hh : mm, where hh are two digits representing full hours (00 <= hh <= 23) and mm are two digits representing minutes (00 <= mm <= 59). Positions in the timetable are given in non-decreasing order according to the departure times. The number of all positions in all timetables does not exceed 1000000.

Output

For each test case the first line of the output contains an integer r - the number of positions in the timetable being the solution. Each of the following r lines contains a departure time A and an arrival time B separated by single space. The time format should be like in the input and positions in the timetable should be ordered increasingly according to the departure times. If there is more then one optimal connection with the same departure and arrival time, your program should output just one.

Example

Sample input:
1
3
3
09:00 15:00 3
10:00 12:00 2
11:00 20:00 3
2
11:30 13:00 3
12:30 14:00 3
0

Sample output:
2
10:00 14:00
11:00 20:00
Warning: enormous Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-07
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Central European Programming Contest, Warsaw 2002









SPOJ Problem Set (classical)

122. Voracious Steve

Problem code: STEVE

Steve and Digit bought a box containing a number of donuts. In order to divide them between themselves they play a special game that they created. The players alternately take a certain, positive number of donuts from the box, but no more than some fixed integer. Each player's donuts are gathered on the player's side. The player that empties the box eats his donuts while the other one puts his donuts back into the box and the game continues with the "loser" player starting. The game goes on until all the donuts are eaten. The goal of the game is to eat the most donuts. How many donuts can Steve, who starts the game, count on, assuming the best strategy for both players?

Task

Write a program that:

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first and only line of the input contains exactly two integers n and m separated by a single space, 1 <= m <= n <= 100 - the parameters of the game, where n is the number of donuts in the box at the beginning of the game and m is the upper limit on the number of donuts to be taken by one player in one move.

Output

For each test case the output contains exactly one integer equal to the number of donuts Steve can count on.

Example

Sample input:
1
5 2 

Sample output:
3

Added by:Adrian Kosowski
Date:2004-07-07
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Central European Programming Contest, Warsaw 2002









SPOJ Problem Set (classical)

123. Paying in Byteland

Problem code: PAYING


There are infinitely many coin denominations in the Byteland. They have values of 2^i for i=0,1,2,... . We will say that set of coins c1,c2,...,ck is perfect when it is possible to pay every amount of money between 0 and c1+...+ck using some of them (so {4,2,2,1} is perfect while {8,1} is not). The question is - is it always possible to change given sum n into a perfect set of coins? Of course it is possible ;). Your task will be more complicated: for a sum n you should find minimal number of coins in its perfect representation.

Input

First line of input contains one integer c<=50 - number of test cases. Then c lines follow, each of them consisting of exactly one integer n<=10^1000.

Output

For each test case output minimal number of coins.

Example

Input:
5
507
29
8574
233
149

Output:
14
7
21
11
10

Added by:Pawel Gawrychowski
Date:2004-07-07
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All









SPOJ Problem Set (classical)

130. Rent your airplane and make money

Problem code: RENT

"ABEAS Corp." is a very small company that owns a single airplane. The customers of ABEAS Corp are large airline companies which rent the airplane to accommodate occasional overcapacity.

Customers send renting orders that consist of a time interval and a price that the customer is ready to pay for renting the airplane during the given time period. Orders of all the customers are known in advance. Of course, not all orders can be accommodated and some orders have to be declined. Eugene LAWLER, the Chief Scientific Officer of ABEAS Corp would like to maximize the profit of the company.

You are requested to compute an optimal solution.

Small Example

Consider for instance the case where the company has 4 orders:

The optimal solution consists in declining Order 2 and 3 and the gain is 10+8 = 18.
Note that the solution made of Order 1 and 3 is feasible (the airplane is rented with no interruption from time 0 to time 14) but non-optimal.

Input

The first line of the input contains a number T ≤ 30 that indicates the number of test cases to follow. The first line of each test case contains the number of orders n (n ≤ 10000). In the following n lines the orders are given. Each order is described by 3 integer values: The start time of the order st (0 ≤ st < 1000000), the duration d of the order (0 < d < 1000000), and the price p (0 < p < 100000) the customer is ready to pay for this order.

Output

You are required to compute an optimal solution. For each test case your program has to write the total price paid by the airlines.

Example

Input:
1
4
0 5 10
3 7 14
5 9 7
6 9 8
Output:
18
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kuegel
Date:2004-07-13
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Southwestern European Regional Contest, Paris 2003









SPOJ Problem Set (classical)

131. Square dance

Problem code: SQDANCE

You are hired by french NSA to break the RSA code used on the Pink Card. The easiest way to do that is to factor the public modulus and you have found the fastest algorithm to do that, except that you have to solve a subproblem that can be modeled in the following way.
Let $ cal P$ $ = {p_1,p_2,...,p_n}$be a set of prime numbers. If $ S = {s_1,s_2,...,s_u}$ and $ T = {t_1,...,t_v}$ are formed with elements of $ cal P$, then S*T will denote the quantity

$displaystyle s_1*s_2*cdot cdot cdot *s_u*t_1*t_2*cdot cdot cdot *t_v.$

We call relation a set of two primes p,q, where p and q are distinct elements of $ cal P$. You dispose of a collection of R relations $ S_i = {p_i,q_i}$ and you are interested in finding sequences of these, $ S_{i_1}, S_{i_2}, ..., S_{i_k}$ such that

$displaystyle S_{i_1}*S_{i_2}*cdot cdot cdot *S_{i_k}$

is a perfect square.

The way you look for these squares is the following. The ultimate goal is to count squares that appear in the process. Relations arrive one at a time. You maintain a collection $ cal C$ of relations that do not contain any square subproduct. This is easy: at first, $ cal C$ is empty. Then a relation arrives and $ cal C$ begins to grow. Suppose a new relation $ {p,q}$ arrives. If no square appears when adding $ {p,q}$ to $ cal C$, then $ {p,q}$ is added to the collection. Otherwise, a square is about to appear, we increase the number of squares, but we do not store this relation, hence $ cal C$ keeps the desired property.
Let us consider an example. First arrives $ S_1 = {2,3}$ and we put it in $ cal C$; then arrives $ S_2 = {5,11},S_3 = {3,7}$ and they are stored in $ cal C$. Now enters the relation $ S_4 = {2,7}$. This relation could be used to form the square:

$displaystyle S_1*S_3*S_4 = (2*3)*(3*7)*(2*7) = (2*3*7)^2.$

So we count 1 and do not store $ S_4$ in $ cal C$. Now we consider $ S_5 = {5,11}$ that could make a square with $ S_2$, so we count 1 square more. Then $ S_6 = {2,13}$ is put into $ cal C$. Now $ S_7 = {7,13}$ could make the square $ S_1*S_3*S_6*S_7$. Eventually, we get 3 squares.

Input

The first line of the input contains a number T <= 30 that indicates the number of test cases to follow. Each test case begins with a line containing two integers P and R: $ Ple 10^5$ is the number of primes occurring in the test case; R ($ le 10^5$) is the number of sets of primes that arrive. The subsequent R lines each contain two integers i and j making a set $ {p_i,q_i}(1le i,jle P)$. Note that we actually do not deal with the primes, they are irrelevant to the solution.

Output

For each test case, output the number of squares that can be formed using the preceding rules.

Example

Input:
2
6 7
1 2
3 5
2 4
1 4
3 5
1 6
4 6
2 3
1 2
1 2
1 2

Output:
3
2
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kuegel
Date:2004-07-13
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Southwestern European Regional Contest, Paris 2003









SPOJ Problem Set (classical)

132. Help R2-D2!

Problem code: HELPR2D2

In Episode III of Star Wars (whose alleged title is "How I became Vader"), R2-D2 (Artoo-Detoo) is again confronted to a tedious work. He is responsible for the loading of the republic transport starships in the fastest way. Imagine a huge space area where n starships are parked. Each starship has a capacity of K cubic femtoparsec. Containers Ci arrive one at a time with some volume vi (expressed in cubic femtoparsec). R2-D2 wants to minimize the number of starships used for a given sequence of containers.
Smart as he is, R2-D2 knows for sure that the problem is a hard one, even with the force being around. Here is the heuristics he selected to solve his problem. Start with all starships ready to load, and numbered S0,S1,etc. When a container Cj arrives, select the starship of minimal index i that can contain Cj and put it in Si. In some sense, this heuristic minimizes the move of the container arriving before its loading.
At the end of the n arrivals, R2-D2 counts the number s of starships used and he measures the total waste w of the sequence. For i=0..s-1, the waste in starship i is given by the unused volume.
Your task is to simulate the algorithm of R2-D2.

Input

The first line of the input contains a number T ≤ 10 that indicates the number of test cases to follow. Each test case begins with K on a line (K ≤ 1000), followed by the number of containers in the sequence, n, on the second line (1 ≤ n ≤ 1000000). There are two possible formats for the remaining lines. If it contains one integer, then this is the next vi. If it begins with the character b (for block), it is followed by 2 integers r and v. This means that the r next containers arriving have volume v.

Output

Your program must output the number s of starships used, followed by a blank, followed by the total waste w.
You can assume, that at most 100000 starships are needed, and R2-D2 has to change the starships in which the next container is loaded at most 100000 times.

Example

Input:
2
100
3
50
25
70
100
4
50
b 2 40
20
Output:
2 55
2 50

Added by:Adrian Kuegel
Date:2004-07-14
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Southwestern European Regional Contest, Paris 2003









SPOJ Problem Set ()

134. Phony Primes

Problem code: PHONY

You are chief debugger for Poorly Guarded Privacy, Inc. One of the top selling product, ReallySecureAgent©, seems to have a problem with its prime number generator. It produces from time to time bogus primes N.
After a while, you realize that the problem is due to the way primes are recognized.
Every phony prime N you discover can be characterized as follows. It is odd and has distinct prime factors, say $ N = p_1 * p_2 * ... * p_k$ with $ p_ine p_j$, where the number k of factors is at least 3. Moreover, for all i=1..k, $ p_i-1$ divides N-1. For instance, 561 = 3*11*17 is a phony prime.
Intrigued by this phenomenon, you decide to write a program that enumerates all such N's in a given interval $ [N_{min},N_{max}[$ with $ 1 le N_{min} &amp;amp;amp;amp;lt; N_{max} &amp;amp;amp;amp;lt; 2^31, N_{max}-N_{min} &amp;amp;amp;amp;lt; 10^6$.
Please note, that the source code limit for this problem is 2000 Bytes to avoid precalculated tables.

Input

Each test case contains one line. On this line are written two integers $ N_{min}$ and $ N_{max}$ separated by a blank. The end of the input is signalled by a line containing two zeros. The number of test cases is approximately 2000.

Output

For each test case, output the list of phony primes in increasing order, one per line. If there are no phony primes in the interval, then simply output none on a line.

Example

Input:

10 2000
20000 21000
0 0

Output:

561
1105
1729
none

Added by:Adrian Kuegel
Date:2004-07-15
Time limit:13s
Source limit:2000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Southwestern European Regional Contest, Paris 2003









SPOJ Problem Set (classical)

135. Men at work

Problem code: MAWORK

Every morning you have to drive to your workplace. Unfortunately, roads are under constant repair. Fortunately, administration is aware that this may cause trouble and they enforce a strict rule on roadblocks: roads must be blocked only half of the time. However, contractors are free to schedule their working hours, still they must follow regulations:

Write a program that, given a description of the road network and of contractors schedules outputs the minimal time needed to drive from home to work.

Input

The first line of the input contains a number T ≤ 10 that indicates the number of test cases to follow. The road network is represented on a N x N grid and the first line of each test case consists in the number N, 2 ≤ N ≤ 25.

Then follows N lines of N characters that represent the road network at time zero. Those lines are made of "." (standing for open road) and "*" (standing for roadblock) and they encode the rows of the grid in increasing order, while columns are also presented in increasing order. Conventionally, your home is at the position first row, first column, while your workplace is at the position last row, last column. Furthermore, you leave home at time t=0, that is, your starting position is first row, first column at time zero.

At a given time t, your car must be on some "open road" cell. It takes one time unit to drive to any of the four adjacent cells heading toward north, south, west or east, and you may also choose to stay on the same cell for one time unit. Of course, those five moves are valid if and only if the target cell exists and is free at time t+1.

Finally comes N lines of N characters that represent the contractors schedules. Those lines match the ones of the grid description and are made of N characters 0,1,...,9 that specify the duration of the working (and rest) period for a given cell. Observe that 0 is a bit special, since it means that the corresponding cell status does not change.

Output

The output consist in a single line for each test case, holding either the requested time, or NO, if driving from home to work is not possible.

Example

Input:

2
10
.*********
........**
*.******.*
*.******.*
*.******.*
*........*
*.******.*
*.******.*
*........*
********..
0000000000
0000000000
0000000000
0000000000
0000000000
0123456780
0000000000
0000000000
0123456780
0000000000
3
...
**.
**.
021
002
000

Output:

34
NO

Added by:Adrian Kuegel
Date:2004-07-16
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Southwestern European Regional Contest, Paris 2003









SPOJ Problem Set (classical)

136. Transformation

Problem code: TRANS

You are given two short sequences of numbers, X and Y. Try to determine the minimum number of steps of transformation required to convert sequence X into sequence Y, or determine that such a conversion is impossible.

In every step of transformation of a sequence, you are allowed to replace exactly one occerunce of one of its elements by a sequence of 2 or 3 numbers inserted in its place, according to a rule specified in the input file.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case, the first line of input contains four integers - N, M, U, V (1<=N,M<=50). The next two lines of input contain sequences X and Y, consisting of N and M integers respectively. The next U lines contain three integers: a b c each, signifying that integer a can be converted to the sequence b c in one step of transformation. The next V-U lines contain four integers: a b c d each, signifying that integer a can be converted to the sequence b c d in one step of transformation. With the exception of N and M, all integers provided at input are positive and do not exceed 30.

The format of one set of input data is illustrated below.

Output

For each test case output -1 if it is impossible to convert sequence X into sequence Y, or the minimum number of steps required to achieve this conversion otherwise.

Example

Sample input:
1
3 10 2 3
2 3 1
2 1 1 2 2 1 2 1 2 1
3 1 2
3 3 3
3 1 3 2

Sample output:
6

Added by:Adrian Kosowski
Date:2004-07-18
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:based on a problem from the VI Polish Collegiate Team Programming Contest (AMPPZ), 2001









SPOJ Problem Set (classical)

137. Partition

Problem code: PARTIT

A partition of positive integer m into n components is any sequence a1,...,an of positive integers such that a1+...+an=m and a1<=a2<=...<=an. Your task is to determine the partition, which occupies the k-th position in the lexicographic order of all partitions of m into n components.

The lexicographic order is defined as follows: sequence a1,...,an comes before b1,...,bn iff there exists such an integer i,1<=i<=n, that aj=bj for all j, 1<= j< i, and ai< bi.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the input consists of three lines, containing the positive integers m, n and k respectively (1<=n<= 10, 1<= m<=220, k is not larger than the number of partitions of m into n components).

Output

For each test case output the ordered elements of the sought partition, separated by spaces.

Example

Sample input:
1
9
4
3

Sample output:
1 1 3 4

Added by:Adrian Kosowski
Date:2004-07-19
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:VI Polish Collegiate Team Programming Contest (AMPPZ), 2001









SPOJ Problem Set (main)

138. Election Posters

Problem code: POSTERS

A parliamentary election was being held in Byteland. Its enterprising and orderly citizens decided to limit the entire election campaign to a single dedicated wall, so as not to ruin the panorama with countless posters and billboards. Every politician was allowed to hang exactly one poster on the wall. All posters extend from top to bottom, but are hung at different points of the wall, and may be of different width. The wall is divided horizontally into sections, and a poster completely occupies two or more adjacent sections.

With time, some of the posters were covered (partially or completely) by those of other politicians. Knowing the location of all the posters and the order in which they were hung, determine how many posters have at least one visible section in the end.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

Each test case begins with a line containing integer n - the number of posters (1<=n<=40000). Then n lines follow, the i-th (1<=i<=n) containing exactly two integers li ri, denoting the numbers of the leftmost and rightmost sections covered by the i-th poster (1<=li< ri<= 107). The input order corresponds to the order of hanging posters.

Output

For each test case output a line containing one integer - the number of posters with visible sections.

Example

Sample input:
1
5
1 4
2 6
8 10
3 4
7 10

Sample output:
4

An illustration of the sample input is given below.

The wall with posters


Added by:Adrian Kosowski
Date:2004-07-19
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ F# GO NODEJS PYTH 3.2.3 PYTH 3.2.3 n SED
Resource:VI Polish Collegiate Team Programming Contest (AMPPZ), 2001









SPOJ Problem Set (classical)

139. The Long and Narrow Maze

Problem code: MAZE

Consider a maze consisting of 3 rows of n square blocks each. The passageways in every block match one of three possible patterns, numbered 0 (empty), 1 (straight) and 2 (bent), as depicted below.

Illustration of possible patterns

Your task is to determine whether it is possible to create a passage in a given maze, with an entrance at the left end and an outlet at the right end of the maze, only by rotating some of the squares of the maze by a multiple of 90 degrees.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

Each test case begins with a line containing a single integer n - the number of squares in one row of the maze (1<= n <= 200000). The next n lines contain three integers each, denoting the types of blocks in consecutive columns of the maze. A column description is of the form a b c (0<=a,b,c<=2), where a represents the type of the block in the first row, b - in the second row and c - in the third row.

Output

For each test case output the word yes if it is possible to rotate the squares so as to form a connection between the left and right edge, and the word no in the opposite case.

Example

Sample input:
1
6
1 0 1
1 2 2
2 2 1
2 2 1
2 2 1
1 2 2

Sample output:
yes

Indeed, the sample input corresponds to the following maze:
Input illustration

for which there exists a correct solution to the problem:
Illustration of the solution

Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-19
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:VI Polish Collegiate Team Programming Contest (AMPPZ), 2001









SPOJ Problem Set (classical)

140. The Loner

Problem code: LONER


The loner is a one-dimensional board game for a single player. The board is composed of squares arranged in a single line, some of which initially have pawns on them. The player makes a move by jumping with a pawn over a pawn on an adjacent field, to an empty square two fields to the right or left of its initial position. The pawn that was jumped over is removed directly after the move, as illustrated below.

The two acceptable types of moves

The game is considered won if exactly one pawn remains on the gaming board, and is lost if the player cannot make a move.

Given the initial state of the gaming board, your task is to determine whether it is possible for the player to win the game.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

Each test cases begins with the positive integer n <= 32000, denoting the size of the gaming board. The second and last line of the test case description contains a sequence of n characters 0 or 1, without any white spaces. The i-th square of the board is occupied by a pawn at the start of the game iff the i-th character of this sequence is 1.

Output

For each test case output the word yes if it is possible for the player to win the game for the presented starting configuration, or the word no in the opposite case.

Example

Sample input:
2
7
0110011
6
111001

Sample output:
yes
no

Added by:Adrian Kosowski
Date:2004-07-21
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:VI Polish Collegiate Team Programming Contest (AMPPZ), 2001









SPOJ Problem Set (main)

142. Johnny and the Glue

Problem code: GLUE

Little Johnny decided he needed to stick an open metal box to the floor in the hall of his parents' house, so that all guests coming in would trip on it. He knew that as soon as his parents saw what he had done, they would try to remove it, and he wasn't going to stand for this. So, he chose the strongest glue in his possession and left lots of dabs of it on the floor (from our point of view, these can be regarded as points). Now, the only question that remained was how to stick the box onto the floor. Johnny is very particular about the way he does this: the box is always stuck face down, so that it only touches the floor on the four edges of the rectangle that forms its base. He would like each of these edges to make contact with at least two dabs of glue. Furthermore, he doesn't want any of the dabs to stay outside the box, since this would ruin the fun (there is no way you can trip someone up, if you've glued them to the floor, is there?).

Obviously, Johnny can sometimes reach his objective in more than one way (especially since he has prepared boxes of all possible dimensions for his act of mischief). Depending on how he does this, a different section of floor will be covered by the box. Determine in how many ways Johnny can choose the section of floor to be covered by the box when gluing.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

The first line of each test case contains positive integer n<=10000 - the number of dabs of glue on the floor. The next n lines contain two integers, x y (-15000<=x,y<=15000), representing the x and y coordinates of the dabs (given in the order in which they were placed by Johnny ;).

Output

For each test case output the number of different sections of floor Johnny may choose to cover (possibly 0).

Example

Sample input:
1 
8 
1 0 
1 4 
0 3 
5 4 
5 0 
6 1 
6 3 
0 1 

Sample output:
2

Added by:Adrian Kosowski
Date:2004-07-22
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ F# GO NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SED
Resource:based on a problem from the VI Polish Collegiate Team Programming Contest (AMPPZ), 2001









SPOJ Problem Set (classical)

145. Aliens

Problem code: ALIENS

Aliens visited our planet with an obvious intention to find some new species for their space zoo. After entering Earth's orbit, they positioned themselves over the town of Belgrade, having detected some life-form activity on the ground. As they approached the surface, they saw a group of half-intelligent beings. Those creatures were actually competitors of the Balkan Olympiad in Informatics who were enjoying the excursion after intense contest. Aliens want to abduct all n (2<=n<=100000) competitors since they are very compassionate, and don’t want their creatures to feel lonely in the space zoo.
Aliens use tractor beam to take their prey. Tractor beam works in the following way: it projects a circle-shaped beam from the spacecraft to the ground vertically beneath it, and all beings that are found in that circle or on its boundary are taken. Projecting the tractor beam needs a certain amount of energy to be spent. As the radius of the tractor beam (radius of the circle on the ground) increases, more and more energy is required. Although extremely intelligent, aliens are much more advanced in social sciences than in programming. That’s why they are asking you to help them find the position of their spacecraft so that the energy required to take all of the n competitors is minimal.
Help our alien brothers! Write a program that will find the required minimal radius of tractor beam that contains all n competitors and the optimal spacecraft location - which is the same as the center of the circle on the ground.

Input

First line of input contains one integer c<=20 - number of test cases. Each test case begins with number n (2<=n<=100000). Then n lines follow and i-th of them contains two real numbers xi and yi (-10000.0<=xi,yi<=10000.0) representing coordinates of the i-th competitor.

Output

For each test case output radius of the tractor beam and coordinates of the spacecraft. Numbers should be rounded to two decimal places.

Example

Input:
1
6
8.0 9.0
4.0 7.5
1.0 2.0
5.1 8.7
9.0 2.0
4.5 1.0

Output:
5.00
5.00 5.00
Warning: large Input/Output data, be careful with certain languages
Added by:Pawel Gawrychowski
Date:2004-07-21
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Balkan Olympiad in Informatics 2002









SPOJ Problem Set (classical)

146. Fast Multiplication Again

Problem code: MULTIPLY


After trying to solve Problem Number 31 (Fast Multiplication) with some script languages that support arbitrary large integers and timing out, you wonder what would be the best language to do fast multiplication of integers. And naturally it comes to your mind: Of course it is brainf**k, because there are only very cheap operations in that language.

Input

Two positive integers, ended with a line feed (ASCII 10) each.

Output

The product of the two integers, terminated by a line feed. You may assume that this number will be less than 10000.

Example

Input:
1
2

Output:
2

Added by:Robin Nittka
Date:2004-07-21
Time limit:2s
Source limit:5000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:BF









SPOJ Problem Set ()

147. Tautology

Problem code: TAUT

Write a program that checks if the given logical expression is a tautology. The logical expression is a tautology if it is always true, regardless of logical value of its variables.

Input

On the first line there is the number of expressions to check (at most 35). The expression is in a prefix notation, that means that operator precedes its arguments. The following logical operators will be used:

C - and 
D - or
I - implies
E - if, and only if
N - not

The variables will be lowercase letters (a-z). There will be no more than 16 different letters in the expression. The length of the expression will not exceed 111 characters.

Output

For each expression write one word: YES if it is a tautology, NO in other case.

Example

Sample input:
7
IIpqDpNp
NCNpp
Iaz
NNNNNNNp
IIqrIIpqIpr
Ipp
Ezz


Sample output:
YES
YES
NO
NO
YES
YES
YES

Added by:Piotr £owiec
Date:2004-07-25
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (main)

148. Land for Motorways

Problem code: MLAND


With every year, the plans for the construction of motorways in Poland are more and more advanced. For some time, it seemed as if the building was actually going to start, so the question of purchasing the land under the roads was of some importance. Only certain cities can be connected by a road directly, provided the farmer owning the land under it agrees to sell out. As a result of the constant swing of moods, the price demanded for the land by each farmer changes in a linear fashion, with possibly different coefficients for every road. It may either increase or decrease (and sometimes even be negative, if the owner anticipates future profit from the proximity of a motorway).

It has been decided that the purchase of land will be made at some moment in between two fixed dates. At that moment, the current prices of land will be frozen, and the least costly configuration of bidirectional roads connecting all cities (directly or indirectly) will be chosen. All the land under the selected roads will subsequently be bought at the frozen price. Since business in the proximity of a motorway does have its advantages, some land owners might actually want their land to be bought and they may offer money into the bargain, consequently making the price of purchase negative.

You act as an intermediary for the purchase and charge a steady commission, proportional to the total sum of purchase. Oddly enough, when signing the contract you missed the clause about the possibility of the price being negative and now you begin to wonder whether you won't end up being charged for your own hard work. Since it is one of your tasks to select the moment of purchase, do so in such a way as to maximise your profit (if this is impossible, at least cut your losses as much as possible).

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line contains two integers n m, denoting the number of cities to be connected and the number of available potential roads,respectively(1<=n<= 120,1<=m<=820). The next line contains two integers t1 t2, which stand for the earliest possible and latest possible moments of purchase (-10000<=t1<=t2<=10000). Each of the following m lines contains four integers, the i-th being: ui vi ai bi, which means that the i-th road connects city ui with city vi, and the purchase of the land under it costs bi+j*ai units of currency at moment j (e.g. at moment 0 the land costs bi units). Please note that these integers are chosen from the following ranges: 0<=ui,vi<=n-1, -32000<=ai,bi<=32000.

Output

For each test case output a line with two floating point numbers, accurate to three digits after the decimal point. The first represents the moment of transaction you ought to choose, the second - the total value of the transaction at that moment. If more than one moment fulfills the conditions of the problem, choose the earliest.

Example

Sample input:
2
5 6
0 5
1 0 -6 -4
2 0 3 -3
3 0 1 5
3 1 -2 -3
4 1 -3 -2
4 3 -2 -3
5 7
-20 20
1 0 1 2
2 1 -7 4
3 1 -9 0
3 2 4 9
4 1 0 -2
4 2 2 3
4 3 6 -5

Sample output:
0.000 -13.000
0.111 -1.000

Added by:Adrian Kosowski
Date:2004-07-24
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ F# GO NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SED
Resource:VII Polish Collegiate Team Programming Contest (AMPPZ), 2002









SPOJ Problem Set ()

149. Fencing in the Sheep

Problem code: FSHEEP

A shepherd is having some trouble penning in his flock of sheep. After several hours of ineffectual efforts he gives up, with some of the sheep within their polygon-shaped pen and some outside. Exhausted, he moves to a place within the pen from which he can see the whole interior of the pen (without any fence getting in the way) and begins to count the sheep which are within it. Please assist him in his task.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

The first line of each test case contains two integers n m, denoting the number of vertices of the polygon forming the fence, and the number of sheep in the whole herd (3<=n<=100000, 0<=m<=100000). The next n lines contain two integers each, the i-th being xi yi - the x and y coordinates of the i-th vertex of the fence (given in anti-clockwise order, -32000<=xi,yi<=32000). The next m lines contain two integers each, the j-th being xj yj - the x and y coordinates of the j-th sheep (arranged in decreasing order of seniority, -32000<=xj,yj<=32000). The shepherd's observation point is within the pen and has coordinates (0,0).

Output

For each test case output a line with a single integer - the number of sheep within the pen. The sheep which are sitting back on the fence and enjoying a cigarette should be included in the count.

Example

Sample input:
1
6 5
2 2
4 4
6 6
-3 1
-1 -1
5 1
2 1
3 2
6 6
3 3
-3 0

Sample output:
3

Illustration of the sample test data:

The sheep with their shepherd

Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-24
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:based on a problem from the VII Polish Collegiate Team Programming Contest (AMPPZ), 2002









SPOJ Problem Set (classical)

150. Where to Drink the Plonk?

Problem code: PLONK


Consider a city bounded by a square, whose n horizontal and n vertical streets divide it into (n+1)2 square blocks. However, in tribute to the ancient traditions of the first dwellers (who tended to overindulge in alcohol), all the inhabitants live at crossroads. A group of friends would like to meet for an evening of merriment at the place of residence of one of them. With a good deal of foresight, anticipating the difficulties they might have getting back to their respective homes, they would like to meet in the house of the friend which minimises the total walking distance for all of them. Assume that everybody walks along the streets, turning only at crossroads, and the distance between any pair of adjacent crossroads is 1.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line of input contains the integer n - the number of friends who want to meet (1<=n<=10000). The next n lines contain two integers each, the i-th being xi yi, standing for the x and y coordinates of the crossroads at which the i-th friend lives (0<=xi,yi<=100000).

Output

For each test case output the total distance covered by all friends when walking to the meeting place.

Example

Sample input:
1
7
1 3
3 2
3 5
6 9
10 1
12 4
5 7

Sample output:
39
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-28
Time limit:6s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:based on a problem from the VII Polish Collegiate Team Programming Contest (AMPPZ), 2002









SPOJ Problem Set (classical)

151. The Courier

Problem code: COURIER

Byteland is a scarcely populated country, and residents of different cities seldom communicate with each other. There is no regular postal service and throughout most of the year a one-man courier establishment suffices to transport all freight. However, on Christmas Day there is somewhat more work for the courier than usual, and since he can only transport one parcel at a time on his bicycle, he finds himself riding back and forth among the cities of Byteland.

The courier needs to schedule a route which would allow him to leave his home city, perform the individual orders in arbitrary order (i.e. travel to the city of the sender and transport the parcel to the city of the recipient, carrying no more than one parcel at a time), and finally return home. All roads are bi-directional, but not all cities are connected by roads directly; some pairs of cities may be connected by more than one road. Knowing the lengths of all the roads and the errands to be performed, determine the length of the shortest possible cycling route for the courier.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

Each test case begins with a line containing three integers: n m b, denoting the number of cities in Byteland, the number of roads, and the number of the courier's home city, respectively (1<=n<=100,1<=b<=m<=10000). The next m lines contain three integers each, the i-th being ui vi di, which means that cities ui and vi are connected by a road of length di (1<=ui,vi<=100, 1<=di<= 10000). The following line contains integer z - the number of transport requests the courier has received (1<=z<=5). After that, z lines with the description of the orders follow. Each consists of three integers, the j-th being uj vj bj, which signifies that bj parcels should be transported (individually) from city uj to city vj. The sum of all bj does not exceed 12.

Output

For each test case output a line with a single integer - the length of the shortest possible bicycle route for the courier.

Example

Sample input:
1
5 7 2
1 2 7
1 3 5
1 5 2
2 4 10
2 5 1
3 4 3
3 5 4
3
1 4 2
5 3 1
5 1 1

Sample output:
43

Added by:Adrian Kosowski
Date:2004-07-28
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:based on a problem from the VII Polish Collegiate Team Programming Contest (AMPPZ), 2002









SPOJ Problem Set (classical)

153. Balancing the Stone

Problem code: SCALES

You are given scales for weighing loads. On the left side lies a single stone of known weight W<2N. You own a set of N different weights, weighing 1, 2, 4, ..., 2N-1 units of mass respectively. Determine how many possible ways there are of placing some weights on the sides of the scales, so as to balance them (put them in a state of equilibrium). Output this value modulo a small integer D.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case, the first line contains three integers: N L D, where N denotes the number of weights at your disposal, L is the length of the binary representation of number W, and D is the modulus (1<= L<= N<= 1000000, 2<= D<=100). The second line contains the value of W, encoded in the binary system as a sequence of exactly L characters 0 or 1 without separating spaces.

Output

For each test case, output a single line containing one integer - the calculated number of possible weight placements, modulo D.

Example

Sample input:
2
6 4 6
1000
6 6 100
100110

Sample output:
3
5
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-07-31
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:based on a problem from the VII Polish Collegiate Team Programming Contest (AMPPZ), 2002









SPOJ Problem Set (classical)

154. Sweet and Sour Rock

Problem code: ROCK

A manufacturer of sweets has started production of a new type of sweet called rock. Rock comes in sticks composed of one-centimetre-long segments, some of which are sweet, and the rest are sour. Before sale, the rock is broken up into smaller pieces by splitting it at the connections of some segments.

Today's children are very particular about what they eat, and they will only buy a piece of rock if it contains more sweet segments than sour ones. Try to determine the total length of rock which can be sold after breaking up the rock in the best possible way.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case, the first line of input contains one integer N - the length of the stick in centimetres (1<=N<=200). The next line is a sequence of N characters '0' or '1', describing the segments of the stick from the left end to the right end ('0' denotes a sour segment, '1' - a sweet one).

Output

For each test case output a line with a single integer: the total length of rock that can be sold after breaking up the rock in the best possible way.

Example

Sample input:
2
15
100110001010001
16
0010111101100000

Sample output:
9
13

Added by:Adrian Kosowski
Date:2004-08-03
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:based on a problem from the VII Polish Collegiate Team Programming Contest (AMPPZ), 2002









SPOJ Problem Set (classical)

160. Choosing a Palindromic Sequence

Problem code: PALSEC

Given two sequences of words: X=(x1,...,xn) and Y=(y1,...,yn), determine how many binary sequences P=(p1,...,pn) exist, such that the word concatenation z1z2...zn, where zi=xi iff pi=1 and zi=yi iff pi=0, is a palindrome (a word which is the same when read from left to right and from right to left).

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case the first line contains the positive integer n - the number of words in a sequence (1<=n<=30). The following n lines contain consecutive words of the sequence X, one word per line. The next n lines contain consecutive words of the sequence Y, one word per line. Words consist of lower case letters of the alphabet ('a' to 'z'), are non-empty, and not longer than 400 characters.

Output

For each test case output one line containing a single integer - the number of different possible sequences P.

Example

Sample input:
1
5
ab
a
a
ab
a
a
baaaa
a
a
ba

Sample output:
12

Added by:Adrian Kosowski
Date:2004-08-07
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:IV Polish Olympiad in Informatics (Wojciech Rytter)









SPOJ Problem Set (classical)

174. Paint templates

Problem code: PAINTTMP

The Painter's Studio is preparing mass production of paintings. Paintings are going to be made with aid of square matrices of various sizes. A matrix of size i consists of 2i rows and 2i columns. There are holes on intersections of some rows and columns. Matrix of size 0 has one hole. For i > 0, matrix of size i is built of four squares of size 2(i-1)*2(i-1). Look at the following figure:

Both squares on the right side and the bottom-left square are matrices of size i-1. Top-left square has no holes. Pictures are constructed in the following way. First, we fix three non-negative integers n, x, y. Next, we take two matrices of size n, place one of them onto the other and shift the upper one x columns right and y rows up. We place such a pattern on a white canvas and cover the common part of matrices with the yellow paint. In this way we get yellow stains on the canvas in the places where the holes in both matrices agree.

Example

Consider two matrices of size 2.

The upper matrix was shifted 2 columns right and 2 rows up. There are three places where holes agree.

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line

There is one integer n, 0 <= n <= 100 in the first line of each test case. This number is the size of matrices used for production of paintings. In the second line there is one integer x and in the third line one integer y, where 0 <= x,y <= 2n. The integer x is the number of columns and y is the number of rows that the upper matrix should be shifted by.

Output

For each test case your program should produce one line with exactly one integer - the number of stains on the canvas.

Example

Sample input:
1
2
2
2

Sample output:
3

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Polish Olympiad in Informatics, stage 1 (Wojciech Rytter)









SPOJ Problem Set (classical)

175. Polygon

Problem code: POLY1


We say that two triangles intersect if their interiors have at least one common point. A polygon is called convex if every segment connecting any two of its points is contained in this polygon. A triangle whose vertices are also vertices of a convex polygon is called an elementary triangle of this polygon. A triangulation of a convex polygon is a set of elementary triangles of this polygon, such that no two triangles from the set intersect and a union of all triangles covers the polygon. We are given a polygon and its triangulation. What is the maximal number of triangles in this triangulation that can be intersected by an elementary triangle of this polygon?

Example

Consider the following triangulation:

The elementary triangle (1,3,5) intersects all the triangles in this triangulation.

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line

In the first line of a test case there is a number n, 3 <= n <= 1000, which equals the number of vertices of the polygon. The vertices of the polygon are numbered from 0 to n-1 clockwise. The following n-2 lines describe the triangles in the triangulation. There are three integers separated by single spaces in the (i+1)-st line, where 1 <= i <= n-2. These are the numbers of the vertices of the i-th triangle in the triangulation.

Output

For each test case your program should produce one line with exactly one integer - the maximal number of triangles in the triangulation, that can be intersected by a single elementary triangle of the input polygon.

Example

Sample input:
1
6
0 1 2
2 4 3
0 5 4
2 4 0

Sample output:
4

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Polish Olympiad in Informatics, stage 1 (Krzysztof Diks)









SPOJ Problem Set (classical)

176. Sum of one-sequence

Problem code: SUM1SEQ


We say that a sequence of integers is a one-sequence if the difference between any two consecutive numbers in this sequence is 1 or -1 and its first element is 0. More precisely: [a1, a2, ..., an] is a one-sequence if

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of a test case there is a number n, such that 1 <= n <= 10 000, which is the number of elements in the sequence. In the second line there is a number S, which is the sum of the elements of the sequence, such that |S| <= 50 000 000.

Output

For each test case there should be written n integers (each integer in a separate line) that are the elements of the sequence (k-th element in the k-th line) whose sum is S or the word "No" if such a sequence does not exist. If there is more than one solution your program should output any one.

Consequent test cases should by separated by an empty line.

Example

Sample input:
1
8
4

Sample output:
0
1
2
1
0
-1
0
1

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Polish Olympiad in Informatics, stage 1 (Grzegorz Jakacki)









SPOJ Problem Set (classical)

177. AB-words

Problem code: ABWORDS

Every sequence of small letters a and b (also the empty sequence) is called an ab-word. If X = [x1, ..., xn] is an ab-word and i, j are integers such that 1 <= i <= j <= n then X[i..j] denotes the subword of X consisting of the letters xi, ..., xj. We say that an ab-word X = [x1..xn] is nice if it has as many letters a as b and for all i = 1, ..., n the subword X[1..i] has at least as many letters a as b.

Now, we give the inductive definition of the similarity between nice ab-words.

A level of diversity of a non-empty set S of nice ab-words is the maximal number of ab-words that can be chosen from S in such a way that for each pair w1,w2 of chosen words, w1 is not similar to w2.

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of a test case there is a number n of elements of the set S, 1 <= n <= 1000; in the following n lines there are elements of the set S, i.e. nice ab-words (one word in each line); the first letter of every ab-word is the first symbol in line and there are no spaces between two consecutive letters in the word; the length of every ab-word is an integer from the range [1..200].

Output

For each test case your program should output one line with one integer - the level of diversity of S.

Example

Sample input:
1
3
aabaabbbab
abababaabb
abaaabbabb

Sample output:
2

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:5th Polish Olympiad in Informatics, stage 1 (Krzysztof Diks)









SPOJ Problem Set (classical)

178. Road net

Problem code: ROADNET

A diskette was enclosed to a road map. The diskette contains the table of the shortest ways (distances) between each pair of towns on the map. All the roads are two-way. The location of towns on the map has the following interesting property: if the length of the shortest way from town A to town B equals the sum of the lengths of the shortest ways from A to C and C to B then town C lies on (certain) shortest way from A to B. We say that towns A and B are neighbouring towns if there is no town C such that the length of the shortest way from A to B equals the sum of the lengths of the shortest ways from A to C and C to B. Find all the pairs of neighbouring towns.

Example

For the table of distances:

ABC
A012
B103
C230

the neighbouring towns are A, B and A, C.

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of each test case there is an integer n, 1 <= n <= 200, which equals the number of towns on the map. Towns are numbered from 1 to n.

The table of distances is written in the following n lines. In the (i+1)-th line, 1 <= i <= n, there are n non-negative integers not greater than 200, separated by single spaces. The j-th integer is the distance between towns i and j.

Output

For each test case your program should write all the pairs of the neighbouring towns (i.e. their numbers). There should be one pair in each line. Each pair can appear only once. The numbers in each pair should be given in increasing order. Pairs should be ordered so that if the pair (a, b) precedes the pair (c, d) then a < c or (a = c and b < d).

Consequent test cases should by separated by an empty line.

Example

Sample input:
1
3
0 1 2
1 0 3
2 3 0

Sample output:
1 2
1 3

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:5th Polish Olympiad in Informatics, stage 2 (Piotr Chrz±stowski-Wachtel)









SPOJ Problem Set (classical)

179. Word equations

Problem code: WORDEQ

Every non-empty sequence of elements 0 and 1 is called a binary word. A word equation is an equation of the form x1x2...xl = y1y2...yr, where xi and yj are binary digits (0 or 1) or variables i.e. small letters of English alphabet. For every variable there is a fixed length of the binary words that can be substituted for this variable. This length is called a length of variable. In order to solve a word equation we have to assign binary words of appropriate length to all variables (the length of the word assigned to the variable x has to be equal to the length of this variable) in such a way that if we substitute words for variables then both sides of the equation (which are binary words after substitution) become equal.

For a given equation compute how many distinct solutions it has.

Example

Let a, b, c, d, e be variables and let 4, 2, 4, 4, 2 be their lengths (4 is the length of a, 2 is the length of b etc.). Consider the equation:

1bad1 = acbe

This equation has 16 distinct solutions.

Input

The number of equations t is in the first line of input, then t descriptions of equations follow separated by an empty line.

Each description consists of 6 lines. An equation is described in the following way: in the first line of the description there is an integer k, 0 <= k <= 26, which denotes the number of distinct variables in the equation. We assume that variables are the first k small letters of English alphabet. In the second line there is a sequence of k positive integers separated by single spaces. These numbers denote the lengths of variables a, b, ... from the equation (the first number is the length of a, the second - b, etc.). There is an integer l in the third line of the description, which is the length of the left size of equation, i.e. the length of the word built of digits 0 or 1 and variables (single letters). The left side of the equation is written in the next line as a sequence of digits and variables with no spaces between them. The next two lines contain the description of the right side of the equation. The first of these lines contains a positive integer r, which is the length of the right side of the equation. The second line contains the right side of the equation which is encoded in the same way as the left side. The number of digits plus sum of the lengths of variables (we count all appearances of variables) on each side of the equation is not greater than 10000.

Output

For each equation your program should output one line with the number of distinct solutions.

Example

Sample input:
1
5
4 2 4 4 2
5
1bad1
4
acbe

Sample output:
16

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Polish Olympiad in Informatics, stage 2 (Wojciech Rytter)









SPOJ Problem Set (classical)

180. How to pack containers

Problem code: CONTPACK

Products of a factory are packed into cylindrical boxes. All boxes have the same bases. A height of a box is a non-negative integer being a power of 2, i.e. it is equal to 2i for some i = 0, 1, 2, ... . The number i (exponent) is called a size of a box. All boxes contain the same goods but their value may be different. Goods produced earlier are cheaper. The management decided, that the oldest (cheapest) goods should be sold out first. From the warehouse goods are transported in containers. Containers are also cylindrical. A diameter of each container is a little bigger than a diameter of a box, so that boxes can be easily put into containers. A height of a container is a non-negative power of 2. This number is called a size of a container. For safe transport containers should be tightly packed with boxes, i.e. the sum of heights of boxes placed in a container have to be equal to the height of this container. A set of containers was delivered to the warehouse. Check if it is possible to pack all the containers tight with boxes that are currently stored in the warehouse. If so, find the minimal value of goods that can be tightly packed into these containers.

Consider a warehouse with 5 boxes. Their sizes and values of their contents are given below:

1 3
1 2
3 5
2 1
1 4

Two containers of size 1 and 2 can be tightly packed with two boxes of total value 3, 4 or 5, or three boxes with total value 9. The container of size 5 cannot be tightly packed with boxes from the warehouse.

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of a test case there is an integer n, 1 <= n <= 10000, which is the number of boxes in the warehouse. In each of the following n lines there are written two non-negative integers separated by a single space. These numbers describe a single box. First of them is the size of the box and the second - the value of goods contained in this box. The size is not greater than 1000 and the value is not greater than 10000. The next line contains a positive integer q, which is the number of different sizes of containers delivered to the warehouse. In each of the following q lines there are two positive integers separated by a single space. The first integer is the size of a container and the second one is the number of containers of this size. The maximal number of containers is 5000, a size of a container is not greater than 1000.

Output

For each test case your program should output exactly one line containing:

Example

Sample input:
1
5
1 3
1 2
3 5
2 1
1 4
2
1 1
2 1

Sample output:
3

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Polish Olympiad in Informatics, stage 2 (Wojciech Rytter)









SPOJ Problem Set (classical)

181. Scuba diver

Problem code: SCUBADIV

A scuba diver uses a special equipment for diving. He has a cylinder with two containers: one with oxygen and the other with nitrogen. Depending on the time he wants to stay under water and the depth of diving the scuba diver needs various amount of oxygen and nitrogen. The scuba diver has at his disposal a certain number of cylinders. Each cylinder can be described by its weight and the volume of gas it contains. In order to complete his task the scuba diver needs specific amount of oxygen and nitrogen. What is the minimal total weight of cylinders he has to take to complete the task?

Example

The scuba diver has at his disposal 5 cylinders described below. Each description consists of: volume of oxygen, volume of nitrogen (both values are given in litres) and weight of the cylinder (given in decagrams):

3 36 120
10 25 129
5 50 250
1 45 130
4 20 119

If the scuba diver needs 5 litres of oxygen and 60 litres of nitrogen then he has to take two cylinders of total weight 249 (for example the first and the second ones or the fourth and the fifth ones).

Task

Write a program that for each test case:

Note: the given set of cylinders always allows to complete the given task.

Input

The number of test cases c is in the first line of input, then c test cases follow separated by an empty line.

In the first line of a test case there are two integers t, a separated by a single space, 1 <= t <= 21 and 1 <= a <= 79. They denote volumes of oxygen and nitrogen respectively, needed to complete the task. The second line contains one integer n, 1 <= n <= 1000, which is the number of accessible cylinders. The following n lines contain descriptions of cylinders; i-th line contains three integers ti, ai, wi separated by single spaces, (1 <= ti <= 21, 1 <= ai <= 79, 1 <= wi <= 800). These are respectively: volume of oxygen and nitrogen in the i-th cylinder and the weight of this cylinder.

Output

For each test case your program should output one line with the minimal total weight of cylinders the scuba diver should take to complete the task.

Example

Sample input:
1
5 60
5
3 36 120
10 25 129
5 50 250
1 45 130
4 20 119

Sample output:
249

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Polish Olympiad in Informatics, stage 2









SPOJ Problem Set (classical)

182. Window

Problem code: WINDOW1

We have a polygon chosen in the cartesian coordinate system. Sides of the polygon are parallel to the axes of coordinates. Every two consecutive sides are perpendicular and coordinates of every vertex are integers. We have also given a window that is a rectangle whose sides are parallel to the axes of coordinates. The interior of the polygon (but not its periphery) is coloured red. What is the number of separate red fragments of the polygon that can be seen through the window?

Example

Look at the figure below:

There are two separate fragments of the polygon that can be seen through the window.

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of a test case there are four integers x1, y1, x2, y2 from the range [0..10000], separated by single spaces. The numbers x1, y1 are the coordinates of the top-left corner of the window. The numbers x2, y2 are the coordinates of the bottom-right corner of the window. The next line of the input file contains one integer n, 4 <= n <= 5000, which equals the number of vertices of the polygon. In the following n lines there are coordinates of polygon's vertices given in anticlockwise direction, i.e. the interior of the polygon is on the left side of its periphery when we move along the sides of the polygon according to the given order. Each line contains two integers x, y separated by a single space, 0 <= x <= 10000, 0 <= y <= 10000. The numbers in the i-th line, are coordinates of the i-th vertex of the polygon.

Output

For each test case you should output one line with the number of separate red fragments of the polygon that can be seen through the window.

Example

Sample input:
1
0 5 8 1
24
0 0
4 0
4 2
5 2
5 0
7 0
7 3
3 3
3 2
2 2
2 4
1 4
1 5
2 5
2 6
3 6
3 5
4 5
4 6
5 6
5 4
7 4
7 7
0 7

Sample output:
2

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Polish Olympiad in Informatics, stage 2 (Wojciech Guzicki)









SPOJ Problem Set ()

183. Assembler circuits

Problem code: ASCIRC

Bytetel Company decided to improve computers they produce. They want to replace assembler programs with special systems called assembler circuits. Assembler programs consist solely of assignments. Each assignment is determined by four elements:

We assume that there are at most 26 registers. They are represented by small letters of English alphabet. There are at most 4 elementary operations and they are represented by capital letters A, B, C, D.

An assembler circuit has:

There are gates inside a circuit. Each gate has two inputs and one output. The gate performs an elementary operation on data delivered on its inputs and passes the result to its output. Inputs of gates and outputs of the whole circuit are connected to outputs of other gates or inputs of the circuit. Outputs of gates and inputs of the circuit can be connected to many inputs of other gates or outputs of the circuit. Connections among gates cannot form cycles.

An assembler circuit is equivalent to an assembler program if for any initial state of registers the final state of registers produced by the program and the circuit are the same.

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of each test case there is one integer n (1 <= n <= 1000), which is the number of instructions in the program.

In the following n lines there are descriptions of consecutive instructions in the program. Each description is a four-letter word beginning with an elementary operation symbol: A, B, C or D. The second and the third letter (which are small letters of English alphabet) are names of registers, in which data are placed. The fourth letter is a name of a register, in which the result should be placed.

Output

For each test case you should output one line with the minimal number of gates in an assembler circuit equivalent to the given program.

Example

Sample input:
1
8
Afbc
Bfbd
Cddd
Bcbc
Afcc
Afbf
Cfbb
Dfdb

Sample output:
6

A circuit equivalent to the given program is shown in the figure.


Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:5th Polish Olympiad in Informatics, stage 3 (Marcin Kubica)









SPOJ Problem Set (classical)

184. Automatic Teller Machines

Problem code: ATMS


Every member of Byteland Credit Society is entitled to loan any amount of Bytelandish ducats unless it is 1030 or more, but he has to return the whole amount within seven days. There are 100 ATMs in the Client Service Room of the Society. They are numbered from 0 to 99. Every ATM can perform one action only: it can pay or receive a fixed amount. The i-th ATM pays 2i ducats if i is even or it receives 2i ducats if i is odd. If a client is going to loan a fixed sum of money it is necessary to check if he is able to get the money using every ATM at most once. If so, numbers of ATMs he has to use should be determined. It is also necessary to check if the client can return the money in a similar way, and if so, to determine numbers of ATMs he has to use.

Example

A client who is going to loan 7 ducats gets 16 ducats from the ATM # 4 and 1 ducat from the ATM # 0 and then he returns 8 ducats in the ATM # 3 and 2 ducats in the ATM # 1. In order to return the amount of 7 ducats he receives 1 ducat from the ATM # 0 and then he returns 8 ducats in ATM # 3.

Task

Write a program that:

Input

In the first line of input there is one positive integer n <= 10000, which equals the number of clients.

In each of the following n lines there is one positive integer less than 1030 (at most 30 decimal digits). The number in the i-th line describes the amount of ducats which the client i is going to loan.

Output

For each client you should output two lines with a decreasing sequence of positive integers from the range [0..99] separated by single spaces, or one word "No":

In the first line of the i-th pair of lines there should be numbers of ATMs (in decreasing order) that the client i should use to get his loan or one word "No" if the loan cannot be received according to the rules;

In the second line of the i-th pair there should be numbers of ATMs (in decreasing order) which the client i should use to return his loan or the word "No".

Example

Sample input:
2
7
633825300114114700748351602698

Sample output:
4 3 1 0
3 0
No
99 3 1

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:5th Polish Olympiad in Informatics, stage 3 (Piotr Chrz±stowski-Wachtel)









SPOJ Problem Set (classical)

185. Chase

Problem code: CHASE1

Chase is a two-person board game. A board consists of squares numbered from 1 to n. For each pair of different squares it is known if they are adjacent to one another or they are not. Each player has a piece at his disposal. At the beginning of a game pieces of players are placed on fixed, distinct squares. In one turn a player can leave his piece on the square it stands or move it to an adjacent square.

A game board has the following properties:

A game consists of many turns. In one turn each player makes a single move. Each turn is started by player A. We say that player A is caught by player B if both pieces stand on the same square. Decide, if for a given initial positions of pieces, player B can catch player A, independently of the moves of his opponent. If so, how many turns player B needs to catch player A if both play optimally (i.e. player A tries to run away as long as he can and player B tries to catch him as quickly as possible).

Example

Consider the board in the figure. Adjacent squares (denoted by circles) are connected by edges. If at the beginning of a game pieces of players A and B stand on the squares 9 and 4 respectively, then player B can catch player A in the third turn (if both players move optimally). If game starts with pieces on the squares 8 (player A) and 4 (player B) then player B cannot catch player A (if A plays correctly).

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of a test case there are four integers n, m, a and b separated by single spaces, where 2 <= n <= 3000, n-1 <= m <= 15000, 1 <= a, b <= n. These are (respectively): the number of squares of the board, the number of adjacent (unordered) pairs, the number of the square on which the piece of player A is placed, the number of the square on which the piece of player B is placed. In each of the following lines there are two distinct positive integers separated by a single space, which denote numbers of adjacent squares.

Output

For each test case you should output one line containing:

Example

Sample input:
1
9 11 9 4
1 2
3 2
1 4
4 7
7 5
5 1
6 9
8 5
9 8
5 3
4 8

Sample output:
3

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:5th Polish Olympiad in Informatics, stage 3 (Adam Borowski)









SPOJ Problem Set (classical)

186. The lightest language

Problem code: LITELANG

Alphabet Ak consists of k initial letters of English alphabet. A positive integer called a weight is assigned to each letter of the alphabet. A weight of a word built from the letters of the alphabet Ak is the sum of weights of all letters in this word. A language over an alphabet Ak is any finite set of words built from the letters of this alphabet. A weight of a language is the sum of weights of all its words. We say that the language is prefixless if for each pair of different words w, v from this language w is not a prefix of v.

We want to find out what is the minimal possible weight of an n-element, prefixless language over an alphabet Ak.

Example

Assume that k = 2, the weight of the letter a is W(a) = 2 and the weight of the letter b is W(b) = 5. The weight of the word ab is W(ab) = 2 + 5 = 7. W(aba) = 2 + 5 + 2 = 9. The weight of the language J = {ab, aba, b} is W(J) = 21. The language J is not prefixless, since the word ab is a prefix of aba. The lightest three-element, prefixless language over the alphabet A2 (assuming that weights of the letters are as before) is {b, aa, ab}; its weight is 16.

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of a test case there are two positive integers n and k separated by a single space, (2 <= n <= 10000, 2 <= k <= 26). These are the number of words in a language and the number of letters in an alphabet respectively. The second line contains k positive integers separated by single spaces. Each of them is not greater than 10000. The i-th number is the weight of the i-th letter.

Output

For each test case you should output one line with the weight of the lightest prefixless n-element language over the alphabet Ak.

Example

Sample input:
1
3 2
2 5

Sample output:
16

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Polish Olympiad in Informatics, stage 3 (Wojciech Rytter)









SPOJ Problem Set (classical)

187. Flat broken lines

Problem code: FLBRKLIN

We have a cartesian coordinate system drawn on a sheet of paper. Let us consider broken lines that can be drawn with a single pencil stroke from the left to the right side of the sheet. We also require that for each segment of the line the angle between the straight line containing this segment and the OX axis belongs to [-45°, 45°] range. A broken line fulfilling above conditions is called a flat broken line. Suppose we are given n distinct points with integer coordinates. What is the minimal number of flat broken lines that should be drawn in order to cover all the points (a point is covered by a line if it belongs to this line)?

Example

For 6 points whose coordinates are (1,6), (10,8), (1,5), (2,20), (4,4), (6,2) the minimal number of flat broken lines covering them is 3.

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of a test case there is one positive integer n, not greater than 30000, which denotes the number of points. In the following n lines there are coordinates of points. Each line contains two integers x, y separated by a single space, 0 <= x <= 30000, 0 <= y <= 30000. The numbers in the i-th line are the coordinates of the i-th point.

Output

For each test case you should output one line with the minimal number of flat broken lines that should be drawn to cover all the points.

Example

Sample input:
1
6
1 6
10 8
1 5
2 20
4 4
6 2

Sample output:
3

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Polish Olympiad in Informatics, stage 3 (Grzegorz Jakacki, Krzysztof Sobusiak)









SPOJ Problem Set ()

188. Rectangles

Problem code: RECTNG1

There are n rectangles drawn on the plane. Each rectangle has sides parallel to the coordinate axes and integer coordinates of vertices.

We define a block as follows:

Examples

The rectangles in Figure 1 form two separate blocks.

Figure 1

The rectangles in Figure 2 form a single block

Figure 2

Task

Write a program that for each test case:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line.

In the first line of a test case there is an integer n, 1 <= n <= 7000, which is the number of rectangles. In the following n lines there are coordinates of rectangles. Each rectangle is described by four numbers: coordinates x, y of the bottom-left vertex and coordinates x, y of the top-right vertex. All these coordinates are non-negative integers not greater than 10000.

Output

For each test case you should output one line with the number of separate blocks formed by the given rectangles.

Example

Sample input:
1
9
0 3 2 6
4 5 5 7
4 2 6 4
2 0 3 2
5 3 6 4
3 2 5 3
1 4 4 7
0 0 1 4
0 0 4 1

Sample output:
2

Added by:Micha³ Czuczman
Date:2004-08-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:5th Polish Olympiad in Informatics, stage 3 (Wojciech Rytter)









SPOJ Problem Set ()

196. Musketeers

Problem code: MUSKET

In the time of Louis XIII and his powerful minister cardinal Richelieu in the Full Barrel Inn n musketeers had consumed their meal and were drinking wine. Wine had not run short and therefore the musketeers were eager to quarrel, a drunken brawl broke out, in which each musketeer insulted all the others.

A duel was inevitable. But who should fight who and in what order? They decided (for the first time since the brawl they had done something together) that they would stay in a circle and draw lots in order. A drawn musketeer fought against his neighbor to the right. A looser "quit the game" and to be more precise his corpse was taken away by servants. The next musketeer who stood beside the looser became the neighbor of a winner. 

After years, when historians read memories of the winner they realized that a final result depended in a crucial extent on the order of duels. They noticed that a fence practice had indicated, who against who could win a duel. It appeared that (in mathematical language) the relation "A wins B" was not transitive! It could happen that the musketeer A fought better than B, B better than C and C better than A. Of course, among three of them the first duel influenced the final result. If A and B fight as the first, C wins eventually. But if B and C fight as the first, A wins finally. Historians fascinated by their discovery decided to verify which musketeers could survive. The fate of France and the whole civilized Europe indeed depended on that!

Task

N persons with consecutive numbers from 1 to n stay in a circle. They fight n-1 duels. In the first round one of these persons (e.g. with the number i) fights against its neighbor to the right, i.e. against the person numbered i+1 (or, if i=n, against the person numbered 1). A looser quits the game, and the circle is tighten so that the next person in order becomes a winner's neighbor. We are given the table with possible duels results, in the form of a matrix. If Ai,j = 1 then the person with the number i always wins with the person j. If Ai,j = 0 the person i looses with j. We can say that the person k may win the game if there exists such a series of n-1 drawings, that k wins the final duel.
Write a program which:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case integer n which satisfies the inequality 3<=n<=100 is written. In each of the following n lines appears one word consisting of n digits 0 or 1. A digit on j-th position in i-th line denote Ai,j. Of course Ai,j = 1 - Aj,i, for i<>j. We assume that Ai,i = 1, for each i

Output

For each test case in the first line there should be written m - the number of persons, who may win the game. In the following m lines numbers of these persons should be written in ascending order, one number in each line.

Example

Sample input:
1
7
1111101
0101100
0111111
0001101
0000101
1101111
0100001

Sample output:
3
1
3
6

The order of duels: 1-2, 1-3, 5-6, 7-1, 4-6, 6-1 gives a final victory to the person numbered 6. You can also check that only two persons more (1 and 3) may win the game.


Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
Resource:6th Polish Olympiad in Informatics, stage 1









SPOJ Problem Set (classical)

199. Empty Cuboids

Problem code: EMPTY

We call a cuboid regular if:

There is given a set A of points of space, whose coordinates are integers from the interval [1..106]. We try to find a regular cuboid of maximal volume which does not contain any of the points from the set A. A point belongs to the cuboid if it belongs to the interior of the cuboid, i.e. it is a point of the cuboid, but not of its wall.

Task

Write a program which:

Input

Input begins with a line containing integer t<=10, the number of test cases. t test cases follow.

In the first line of each test case one non-negative integer n is written ( n <= 5000). It is the number of elements in the set A. In the following n lines of the input there are triples of integers from the interval [1..106], which are the X, Y and Z coordinates of points from A, repectively. Numbers in each line are separated by single spaces.

Output

For each test case there should be three integers separated by single spaces. These are the X, Y and Z coordinates (respectively) of the vertex of the regular cuboid of maximal volume. If there is more than one such a cuboid, choose whichever. We require that all coordinates be positive.

Example

Sample input:
1
4
3 3 300000
2 200000 5
90000 3 2000
2 2 1000

Sample output:
1000000 200000 1000

Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:6th Polish Olympiad in Informatics, stage 1









SPOJ Problem Set ()

200. Monodigital Representations

Problem code: MONODIG

Let K be a decimal digit different from 0. We say that an arithmetic expression is a K-representation of the integer X if a value of this expression is X and if it contains only numbers composed of a digit K. (All the numbers are of course decimal). The following arithmetical operations are allowed in the expression: addition, subtraction, multiplication and division. Round brackets are allowed too. Division may appear only when a dividend is a multiple of a divisor.

Example

Each of the following expressions is the 5-representation of the number 12:

The length of the K-representation is the number of occurrences of digit K in the expression. In the example above the first two representations have the length 6, the third - 5, and the forth - 4.

Task

Write a program which: 

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. The first line of each test case contains digit K, K is en element of {1,...,9}. The second line contains number n, 1<=n<=10. In the following n lines there is the series of natural numbers a1,...,an, 1<=ai<=32000 (for i=1,..,n), one number in each line. 

Output

The output for each test case composes of n lines. The i-th line should contain: 

Example

Sample input:
1
5
2
12
31168

Sample output
4
NO

Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:6th Polish Olympiad in Informatics, stage 1









SPOJ Problem Set (classical)

201. The Game of Polygons

Problem code: POLYGAME

Two players take part in the game polygons. A convex polygon with n vertices divided by n-3 diagonals into n-2 triangles is necessary. These diagonals may intersect in vertices of the polygon only. One of the triangles is black and the remaining ones are white. Players proceed in alternate turns. Each player, when its turn comes, cuts away one triangle from the polygon. players are allowed to cut off triangles along the given diagonals. The winner is the player who cuts away the black triangle.
NOTE: We call a polygon convex if a segment joining any two points of the polygon is contained in the polygon.

Task

Write a program which: 

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. The first line of each test case contains an integer n, 4 <= n <= 50000. This is the number of vertices in the polygon. The vertices of the polygon are numbered, clockwise, from 0 to n-1.
The next n-2 lines comprise descriptions of triangles in the polygon. In the i+1-th line, 1 <= i <= n-2, there are three non-negative integers a, b, c separated by single spaces. Theses are numbers of vertices of the i-th triangle. The first triangle in a sequence is black.

Output

The output for each test case should have one line with the word:

Example

Sample input:
1
6
0 1 2
2 4 3
4 2 0
0 5 4

Sample output:
YES
Warning: large Input/Output data, be careful with certain languages
Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:6th Polish Olympiad in Informatics, stage 1









SPOJ Problem Set ()

202. Rockets

Problem code: ROCKETS

There are two separate, n-element sets of points of a two dimensional map: R and W. None triple of points from the set RUW is collinear. Rockets earth-to-earth are located on points from the set R. Enemy objects, which should be destroyed, are located on points from the set W. The rockets may fly only in the straight line and their trajectories cannot intersect. We are about to find for each rocket a target to destroy.

Task

Write a program which:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case there is written one integer n, 1<=n<=10000, equal to the number of elements of the sets R and W.

In each of the following 2n lines of the input one pair of integer numbers from the interval [-10000, 10000] is written. Numbers in each pair are separated by a single space. They are coordinates of the point on a map (first coordinate x, then y). The first n lines comprise coordinates of the points from the set R, the last n lines comprise the points from the set W. In the (i+1)-th line there are coordinates of the point ri, in the (i+n+1)-th line there are coordinates of the point wi, 1<= i<= n.

Output

The output for each test case should consist of n lines. In the i-th line there should be one integer k(i), such that the segment ri wk(i) belongs to the set of segments which your program found. (This means that the rocket from the point ri destroys an object in the point wk(i)).

Example

Sample input:
1
4
0 0
1 5
4 2
2 6
1 2
5 4
4 5
3 1

Sample output:
2
1
4
3
Warning: large Input/Output data, be careful with certain languages
Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
Resource:6th Polish Olympiad in Informatics, stage 2









SPOJ Problem Set (classical)

203. Potholers

Problem code: POTHOLE

A team of speleologists organizes a training in the Grate Cave of Byte Mountains. During the training each speleologist explores a route from Top Chamber to Bottom Chamber. The speleologists may move down only, i.e. the level of every consecutive chamber on a route should be lower then the previous one. Moreover, each speleologist has to start from Top Chamber through a different corridor and each of them must enter Bottom Chamber using different corridor. The remaining corridors may be traversed by more then one speleologist. How many speleologists can train simultaneously? 

Task

Write a program which:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case there is one integer n (2<=n<=200), equal to the number of chambers in the cave. The chambers are numbered with integers from 1 to n in descending level order - the chamber of grater number is at the higher level than the chamber of the lower one. (Top Chamber has number 1, and Bottom Chamber has number n). In the following n-1lines (i.e. lines 2,3,...,n) the descriptions of corridors are given. The (i+1)-th line contains numbers of chambers connected by corridors with the i-th chamber. (only chambers with numbers grater then i are mentioned). The first number in a line, m, 0<=m<=(n-i+1), is a number of corridors exiting the chamber being described. Then the following m integers are the numbers of the chambers the corridors are leading to. 

Output

Your program should write one integer for each test case. This number should be equal to the maximal number of speleologists able to train simultaneously,

Example

Sample input:
1
12
4 3 4 2 5
1 8
2 9 7
2 6 11
1 8
2 9 10
2 10 11
1 12
2 10 12
1 12
1 12

Sample output:
3

The sample input corresponds to the following cave:


Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:6th Polish Olympiad in Informatics, stage 2









SPOJ Problem Set (classical)

204. Sleepwalker

Problem code: SLEEP

There is a building with flat square roof of size 3k*3k and sides parallel to north-south and east-west directions. The roof is covered with square tiles of size 1 (with a side of length 1), but one of the tiles has been removed and there is a hole in the roof (big enough to fall in). The tiles form a rectangular mesh on the roof, so their positions may be specified with coordinates. The tile at the southwestern corner has coordinates (1,1). The first coordinate increases while going eastwards, and the second while going northwards.

Sleepwalker wanders across the roof, in each step moving from the tile he is standing on to the adjacent one on the east(E), west(W), south(S), or north(N). The sleepwalker roof ramble starts from the southwestern corner tile. The description of the path is a word dk built of the letters N, S, E, W denoting respectively a step to the north, south, east and west. For k = 1 the word describing the path of sleepwalker is

d1 = EENNWSWN

For k = 2 the word describing the path of sleepwalker is

d2 = NNEESWSEENNEESWSEEEENNWSWNNEENNWSW -
NNEENNWSWNWWWSSENESSSSWWNENWWSSW -
WNENWNEENNWSWN.

(See the picture that shows how the sleepwalker would go across a roof of dimension 3*3 or 9*9.) Generally, if k>=1, the description of a sleepwalker's path on the roof of dimension 3k+1*3k+1 is a word:

dk+1 = a(dk) E a(dk) E dk N d k N dk W c(dk) S b(dk) W b(dk) N dk

where functions a, b and c denote the following permutations of letters specifying directions:
a: E->N W->S N->E S->W 
b: E->S W->N N->W S->E 
c: E->W W->E N->S S->N 

E.g. a(SEN)=WNE, b(SEN)=ESW, c(SEN)=NWS.

We start observing sleepwalker at the time he stands on the tile of coordinates (u1, u2). After how many steps will sleepwalker fall into the hole made after removing the tile of coordinates (v1, v2)?

Example

There are sleepwalker's paths on roofs of dimension 3*3 and 9*9 on the picture below. In the second case, the point at which the observation starts and the hole have been marked. The sleepwalker has exactly 20 steps to the hole (from the moment the observation starts).

Task

Write a program which:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case one integer k, 1<=k<=60, denoting the size of the roof (3k*3k) is written. In each of the following two lines of the test case two natural numbers x, y separated with a space are written, 1<=x<=3^k, 1<=y<=3^k. The numbers in the second line are the coordinates of the tile the sleepwalker is standing on. The numbers in the third line are the coordinates of the hole. You may assume, that with these data the sleepwalker will eventually fall into the hole after some number of steps.

Output

The only line of output for each test case should contain the number of steps on the sleepwalker's path to the hole.

Example

Sample input:
1
2
3 2
7 2

Sample output
20

Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:6th Polish Olympiad in Informatics, stage 2









SPOJ Problem Set ()

205. Icerink

Problem code: ICERINK

A skating competition was organized on the largest icerink in Byteland. The icerink is a square of size 10000 * 10000. A competitor begins skating at the START point chosen by referees and his task is to finish sliding at the FINISH point, also chosen by referees. The points of START and FINISH are different. One can slide in directions parallel to the sides of the icerink. There are some obstacles placed on the icerink. Each obstacle is a prism, which base is a polygon with sides parallel to the sides of the icerink. Each two adjacent sides of the base are always perpendicular. The obstacles do not have common points. Each slide finishes up at the point where a competitor, for the first time, meets the wall of an obstacle, which is perpendicular to the direction of the slide. In other words, one can stop only when he crashes on a wall or in the FINISH point. Falling out of the icerink causes disqualification. Competitor may slide along walls of an obstacle.

Decide, whether a competitor who slides according to the given rules may reach the finish point, assuming he begun sliding from the starting point. If so, what is the minimal number of slides he needs to do?

Task

Write a program which:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. We define a system of coordinates to describe positions of objects on a rink. The rink is a square with vertices (0,0),(10000,0),(10000,10000),(0,10000). In the first line of each test case there are two integers z1 and z2 separated by a single space, 0<=z1, z2<=10000. The pair (z1, z2) denotes coordinates of the START point. In the second line of the file there are two integers t1 and t2 separated by single space, 0<=t1, t2<=10000. The pair (t1, t2) denotes coordinates of the FINISH point. The third line of the file contains one integer s, 1<=s<=2500. This is the number of obstacles. The following lines comprise descriptions of s obstacles. Each description of an obstacle begins with the line containing one positive integer r equal to the number of walls (sides of the base) of the obstacle. In each of the following r lines there are two integers x and y separated by a single space. These are the coordinates of the vertices of the obstacle's base, given in a clockwise order. (i.e. when going around the obstacle in this direction the inside is on the left-hand side). The total number of side walls of the obstacles does not exceed 10000.

Output

Your program should write for each test case:

Example

Sample input:
1
40 10
5 40
3
6
0 15
0 60
20 60
20 55
5 55
5 15
12
30 55
30 60
60 60
60 0
0 0
0 5
55 5
55 35
50 35
50 40
55 40
55 55
6
30 25
15 25
15 30
35 30
35 15
30 15

Sample output:
4

The sample input corresponds to the following situation:

These are the possible sequences of slides of length 4:

Warning: large Input/Output data, be careful with certain languages


Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:6th Polish Olympiad in Informatics, stage 2









SPOJ Problem Set (classical)

206. Bitmap

Problem code: BITMAP

There is given a rectangular bitmap of size n*m. Each pixel of the bitmap is either white or black, but at least one is white. The pixel in i-th line and j-th column is called the pixel (i,j). The distance between two pixels p1=(i1,j1) and p2=(i2,j2) is defined as:

d(p1,p2)=|i1-i2|+|j1-j2|.

Task

Write a program which:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case there is a pair of integer numbers n, m separated by a single space, 1<=n <=182, 1<=m<=182. In each of the following n lines of the test case exactly one zero-one word of length m, the description of one line of the bitmap, is written. On the j-th position in the line (i+1), 1 <= i <= n, 1 <= j <= m, is '1' if, and only if the pixel (i,j) is white.

Output

In the i-th line for each test case, 1<=i<=n, there should be written m integers f(i,1),...,f(i,m) separated by single spaces, where f(i,j) is the distance from the pixel (i,j) to the nearest white pixel.

Example

Sample input:
1
3 4
0001
0011
0110

Sample output:
3 2 1 0
2 1 0 0
1 0 0 1

Added by:Piotr £owiec
Date:2004-09-13
Time limit:4s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:6th Polish Olympiad in Informatics, stage 2









SPOJ Problem Set (classical)

207. Three-coloring of binary trees

Problem code: THREECOL

A tree consists of a node and some (zero, one or two) subtrees connected to it. These subtrees are called children.

A specification of the tree is a sequence of digits. If the number of children in the tree is:

Each of the vertices in the tree must be painted either red or green or blue.
However, we need to obey the following rules:

How many vertices may be painted green?

Task

Write a program which:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. Each test case consists of one word (no longer then 10000 characters), which is a specification of a tree.

Output

Your program should write for each test case exactly two integers separated by a single space, which respectively denote the maximal and the minimal number of vertices that may be painted green.

Example

Sample input:
1
1122002010

Sample output:
5 2

Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:6th Polish Olympiad in Informatics, stage 3









SPOJ Problem Set (classical)

208. Store-keeper

Problem code: STORE

The floor of a store is a rectangle divided into n*m square fields. Two fields are adjacent, if they have a common side. A parcel lays on one of the fields. Each of the remaining fields is either empty, or occupied by a case, which is too heavy to be moved by a store-keeper. The store-keeper has to shift the parcel from the starting field P to the final field K. He can move on the empty fields, going from the field on which he stands to a chosen adjacent field. When the store-keeper stays on a field adjacent to the one with the parcel he may push the parcel so that if moves to the next field (i.e. the field on the other side of the parcel), assuming condition that there are no cases on this field.

Task

Write a program, which:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case two positive integers separated by a single space, n,m<=100, are written. These are dimensions of the store. In each of the following n lines there appears one m-letter word made of letters S, M, P, K, w. A letter on i-th position in j-th word denotes a type of the field with coordinates (i,j) and its meaning is following: 

Each letter M, P and K appears in the test case exactly once.

Output

Your program should write to the standard output for each test case: 

Example

Sample input:
1
10 12
SSSSSSSSSSSS
SwwwwwwwSSSS
SwSSSSwwSSSS
SwSSSSwwSKSS
SwSSSSwwSwSS
SwwwwwPwwwww
SSSSSSSwSwSw
SSSSSSMwSwww
SSSSSSSSSSSS
SSSSSSSSSSSS

Sample output
7

Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:6th Polish Olympiad in Informatics, stage 3









SPOJ Problem Set (classical)

209. The Map

Problem code: MAP

After a new administrative division of Byteland cartographic office works on a new demographic map of the country. Because of technical reasons only a few colors can be used. The map should be colored so that regions with the same or similar population (number of inhabitants) have the same color. For a given color k let A(k) be the number, such that: 

A coloring error of a region is an absolute value of the difference between A(k) and the region's population. A cumulative error is a sum of coloring errors of all regions. We are looking for an optimal coloring of the map (the one with the minimal cumulative error).

Task

Write a program which:

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case an integer n is written, which is the number of regions in Byteland, 10< n <3000. In the second line the number m denoting the number of colors used to color the map is written, 2 <= m <= 10. In each of the following n lines there is one non-negative integer - a population of one of the regions of Byteland. No population exceeds 2^30

Output

Your program should write for each test case one integer number equal to a minimal cumulative error, which can be achieved while the map is colored (optimally).

Example

Sample input:
1
11
3
21
14
6
18
10
2
15
12
3
2
2

Sample output:
15

Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:6th Polish Olympiad in Informatics, stage 3









SPOJ Problem Set (classical)

210. The Altars

Problem code: ALTARS

According to Chinese folk beliefs evil spirits can move only on a straight line. It is of a great importance when temples are built. The temples are constructed on rectangular planes with sides parallel to the north - south or east - west directions. No two of the rectangles have common points. An entrance is situated in the middle of one of four walls and its width is equal to the half of the length of the wall. An altar appears in the center of the temple, where diagonals of the rectangle intersect. If an evil spirit appears in this point, a temple will be profaned. It may happen only if there exists a ray which runs from an altar, through an entrance to infinity and neither intersects nor touches walls of any temple (on a plane parallel to the plane of a construction area), i.e. one can draw at a construction area a line which starts at the altar and runs to the infinity without touching any wall. 

Task

Write a program which: 

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case one integer n, the number of temples 1 <= n <= 1000, is written.

In each of the following n lines there is a description of one temple (in i-th line a description of the i-th temple). The description of a temple consists of four non-negative integers, not greater than 8000 and a letter E, W, S or N. Two first numbers are coordinates of a temple's northern-west corner and two following are coordinates of an opposite southern-east corner. In order to specify coordinates of a point first we give its geographical longitude, which increases from the west to the east, and then its latitude, which increases from the south to the north. The fifth element of the description indicates the wall with the entrance (E - Eastern, W - Western, S - Southern, N - Northern). The elements of the temple's description are separated by single spaces.

Output

In the following lines of the output for each test case your program should write in ascending order numbers of the temples, which may be profaned by an evil spirit. Each number is placed in a separate line. If there are no such numbers, you should write one word: NONE. 

Example

Sample input

6
1 7 4 1 E
3 9 11 8 S
6 7 10 4 N
8 3 10 1 N
11 4 13 1 E
14 8 20 7 W
Sample output
1
2
5
6

The picture shows the temples described in the example. The dashed lines show possible routes of evil spirits.


Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:6th Polish Olympiad in Informatics, stage 3









SPOJ Problem Set ()

211. Primitivus recurencis

Problem code: PRIMIT


A genetic code of the abstract primitivus (Primitivus recurencis) is a series of natural numbers K=(a_1,...,a_n). A feature of primitivus we call each ordered pair of numbers (l,r), which appears successively in the genetic code, i.e. there exists such i that l=a_i, r=a_i+1. There are no (p,p) features in a primitivus' genetic code. 

Task

Write a program which: 

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case one positive integer number n is written. It is the number of different features of the primitivus. In each of the following n lines there is a pair of natural numbers l and r separated by a single space, 1 <= l <= 1000, 1 <= r <= 1000. A pair (l, r) is one of the primitivus' features. The features do not repeat in the input file

Output

Your program should write for each test case exactly one integer number equal to the length of the shortest genetic code of the primitivus, comprising the features from the input.

Example

Sample input:
1
12
2 3
3 9
9 6
8 5
5 7
7 6
4 5
5 1
1 4
4 2
2 8
8 6

Sample output:
15

All the features from the example are written in the following genetic code:
(8, 5, 1, 4, 2, 3, 9, 6, 4, 5, 7, 6, 2, 8, 6)

Warning: enormous Input/Output data, be careful with certain languages
Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:6th Polish Olympiad in Informatics, stage 3









SPOJ Problem Set (classical)

212. Water among Cubes

Problem code: WATER

On a rectangular mesh comprising n*m fields, n*m cuboids were put, one cuboid on each field. A base of each cuboid covers one field and its surface equals to one square inch. Cuboids on adjacent fields adhere one to another so close that there are no gaps between them. A heavy rain pelted on a construction so that in some areas puddles of water appeared. 

Task

Write a program which: 

Input

The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case two positive integers 1 <= n <= 100, 1 <= m <= 100 are written. They are the size of the mesh. In each of the following n lines there are m integers from the interval [1..10000]; i-th number in j-th line denotes a height of a cuboid given in inches put on the field in the i-th column and j-th raw of the chessboard.

Output

Your program should write for each tes case one integer equal to the maximal volume of water (given in cubic inches), which may gather in puddles on the construction. 

Example

Sample input:
1
3 6
3 3 4 4 4 2
3 1 3 2 1 4
7 3 1 6 4 1

Sample output:
5

The picture below shows the mesh after the rain (seen from above). Puddles are drawn in gray.


Added by:Piotr £owiec
Date:2004-09-13
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:6th Polish Olympiad in Informatics, stage 3









SPOJ Problem Set (set2)

215. Panic in the Plazas

Problem code: PANIC

Have you ever heard of the BBFO? The Bytelandian Bit-eating Fanatic Organisation regards itself as a collection of people with slightly unorthodox views on law and order in the world, and is regarded by others as the most wildly dangerous and unpredictable terrorist organisation which afflicts the small and otherwise peaceful country of Byteland.

Intelligence reports claim that the next act of violence to be performed by the BBFO is a widescale, distributed bomb attack in the Bytelandian capital. Therefore, all precautions have been undertaken to prevent any such action. The BBFO, seeing the futility of their original scheme, decided to change the plan of action. The new idea is endowed with devilish simplicity.

The capital of Byteland is a network of plazas, some of which (but not necessarily all) are connected by bidirectional streets of different length. Crowds of people are sitting at all the plazas, sipping coffee and generally relaxing. The terrorists plan to creep up to some of the plazas armed with inflatable paper bags. Then, exactly at midday, all the bags will be burst in such a way as to simulate the bang of a bomb. Panic will ensue at the plazas where the bags were burst, and will spread throughout some of the city. Panic breaks out at a plaza the moment a bag explodes in it, or immediately after a panicking crowd rushes into the plaza from at least one of the side streets. The people in the plaza then split up into crowds, which rush out by all possible streets except those by which people have just run in. After entering a street, a crowd runs along it at constant speed until it reaches the plaza at the other end, causing panic there, etc. If there is no possible way of escape from a plaza, everybody in it perishes. Similarly, if two crowds rushing in opposite directions collide in mid-street, all the people are lethally trampled.

A small illustration

Despite the panic, people in the city retain a little free will. They don't move at all until the panic reaches them, but when they have to escape, they can always choose the escape route from a plaza that suits them best. Assuming you were to sit in one of the plazas of Byteland at noon that fateful day... which plaza would you choose to sit in? All your normal preferences concerning the quality of coffee in the cafes are temporarily forgotten, and your only aim is to survive as long as possible.

Input

The first line of input contains a single integer t<=500, the number of test cases. t test cases follow. Each test case begins with a line containing three integers n m k (1<=n<=50000, 0<=m<=250000, 0<=k<=n) denoting the total number of plazas, the number of streets in the city, and the number of plazas in which bags are planted, respectively. Each of the following m lines contains 4 integers u v tuv tvu (1<=u,v<=n, 1<=tuv,tvu<=1000) representing a single road in the city - leading from plaza u to plaza v and requiring tuv time to cover when running at constant speed from u to v, and tvu time when running the other way. The last line of a test case description contains a list of the k numbers of plazas at which bags explode at noon.

Output

For each test case, the output should contain a single line with a space separated increasing sequence of integers - the numbers of all the plazas which offer the maximum possible survival time to a person sitting there at noon.

Example

Input:
2

4 5 2
1 2 10 10
2 4 30 30
3 2 10 10
4 3 50 5
3 1 5  50
1 2

2 0 1
2

Output:
2 3 4
1

(In the first case the life expectancy is 22.5, in the second case it is more or less infinite.)

Warning: enormous Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-09-27
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:DASM Programming League 2004 (problemset 2)









SPOJ Problem Set (classical)

217. Soldiers on Parade

Problem code: SOPARADE

Protocol is really weird in Byteland. For instance, it is required that, when presenting arms before an officer, soldiers should stand in a single row (at positions numbered from 1 to n). Soldiers may have one of 4 possible ranks, distinguished by the number of squiggles on the epaulets (between 1 and 4). Soldiers standing beside each other must have a difference in rank of at least two squiggles. Moreover, there are additional sets of rules (different for every province). Each rule states that soldiers standing at some given positions of the row must differ in rank by at least a squiggle.

Starting from the new year onwards, some provinces are changing their set of protocol rules. As the Senior Military Secretary of Protocol, it is your task to approve the new rules. To your surprise, some of the provinces have put forward protocol rules which are quite impossible to fulfill, even if the soldiers were to be specially selected for the purpose of presenting arms. Detect all such offending provinces and on no account approve their laws.

Input

The first line of input contains a single positive integer t<=10 - the number of provinces which are proposing new laws. t sets of rules follow, separated by empty lines.

Each set of rule begins with a line containing two non-negative integers n p (n<=100000, p<=100000) - the number of soldiers arranged and the number of rules proposed in the province, respectively. Each of the next p lines contains a single rule: an integer bi (2<=bi<=n), followed by bi integers a1,a2,...,abi (1<=ak<=n). Such a rule means that soldiers standing at positions a1,a2,...,abi must all be of different rank.

Output

For every set of rules presented at input, output a single line containing the word rejected if no unit of soldiers can be arranged in accordance with protocol, or the word approved in the opposite case.

Example

Input:
2

2 1
2 1 2

5 2
3 1 3 2
4 2 3 4 5

Output:
approved
rejected

Added by:Adrian Kosowski
Date:2004-10-08
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004 (problemset 1)









SPOJ Problem Set (set1)

220. Relevant Phrases of Annihilation

Problem code: PHRASES

You are the King of Byteland. Your agents have just intercepted a batch of encrypted enemy messages concerning the date of the planned attack on your island. You immedietaly send for the Bytelandian Cryptographer, but he is currently busy eating popcorn and claims that he may only decrypt the most important part of the text (since the rest would be a waste of his time). You decide to select the fragment of the text which the enemy has strongly emphasised, evidently regarding it as the most important. So, you are looking for a fragment of text which appears in all the messages disjointly at least twice. Since you are not overfond of the cryptographer, try to make this fragment as long as possible.

Input

The first line of input contains a single positive integer t<=10, the number of test cases. t test cases follow. Each test case begins with integer n (n<=10), the number of messages. The next n lines contain the messages, consisting only of between 2 and 10000 characters 'a'-'z', possibly with some additional trailing white space which should be ignored.

Output

For each test case output the length of longest string which appears disjointly at least twice in all of the messages.

Example

Input:
1
4
abbabba
dabddkababa
bacaba
baba

Output:
2

(in the example above, the longest substring which fulfills the requirements is 'ba')


Added by:Adrian Kosowski
Date:2004-10-11
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:DASM Programming League 2004 (problemset 1)









SPOJ Problem Set ()

224. Vonny and her dominos

Problem code: VONNY

Vonny loves playing with dominos. And so she owns a standard set of dominos. A standard set of dominos consists of 28 pieces called bones, tiles or stones. Each bone is a rectangular tile with a line dividing its face into two square ends. Each square is labeled with a number between 0 and 6. The 28 stones are labeled (0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6), (1,1),(1,2),...,(5,5),(5,6),(6,6). Tommy - the brother of Vonny - build a box for Vonny's dominos. This box is sized 7 x 8 squares. Every square is labeled with a number between 0 and 6. You can see a example box here.

0 3 0 2 2 0 2 3 
1 5 6 5 5 1 2 2 
3 4 1 4 5 4 4 4 
6 6 1 0 5 2 3 0 
4 0 3 2 4 1 6 0 
1 4 1 5 6 6 3 0 
1 2 6 5 5 6 3 3 

Now Vonny wants to arrange her 28 stones in such way that her stones cover all squares of the box. A stone can only be placed on two adjacent squares if the numbers of the squares and of the domino stone are equal. Tommy asks Vonny in how many different ways she can arrange the dominos. Tommy assumes that Vonny need a lot of time to answer the question. And so he can take some of Vonny's candies while she solves the task. But Vonny is a smart and clever girl. She asks you to solve the task and keeps an eye on her candies.

Input

The first line of the input contains the number of testcases. Each case consists of 56 numbers (7 rows and 8 cols) between 0 and 6 which represents Tommy's box.

Output

For each testcase output a single line with the number which answers Tommy's question.

Example

Input:
2
0 3 0 2 2 0 2 3 
1 5 6 5 5 1 2 2 
3 4 1 4 5 4 4 4 
6 6 1 0 5 2 3 0 
4 0 3 2 4 1 6 0 
1 4 1 5 6 6 3 0 
1 2 6 5 5 6 3 3 

5 3 1 0 0 1 6 3 
0 2 0 4 1 2 5 2 
1 5 3 5 6 4 6 4 
0 5 0 2 0 4 6 2 
4 5 3 6 0 6 1 1 
2 3 5 3 4 4 5 3 
2 1 1 6 6 2 4 3 

Output:
18
1

Added by:Simon Gog
Date:2004-10-18
Time limit:20s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









SPOJ Problem Set ()

226. Jewelry and Fashion

Problem code: JEWELS

You work for a small jewelers' company, renowned for the exquisite necklaces and multi-colored amber strings it produces. For the last three centuries, the sales of strings alone have been enough to keep business going without a hitch. Now however, the influence of fashion is greater than ever, and you face the prospect of imminent bankruptcy unless you adapt to the needs and fancies of the rather unusual part of society who constitute your main clientele. These elderly ladies have recently decided that fashion has changed: strings are out, and earrings are in. There is nothing to be done about it -- you have to comply and switch to the production of earrings.

One problem remains: what to do with the impressive heap of amber strings piled up in your shop? One of your assistants has a bright idea: he recommends cutting the strings into two parts, removing some stones to make both parts have an identical color pattern (either immediately, or after rotation by 180 degrees), and selling what remains as pairs of earrings. After a moment's thought, you decide to go ahead with the plan. But your careful managerial eye tells you that minimising the number of wasted (removed) stones may not be as easy as it sounds...

Example of string2earring conversion ;)

Input

The first line of input contains a single integer t<=500, the number of test cases. The next t lines contain one test case each, in the form of a string of at most 8000 characters 'a'-'z' (terminated by a new line, optionally preceded by whitespace which should be ignored). The i-th character of the line corresponds to the design on the i-th stone in the amber string it represents. The total length of the input file is not more than 100kB.

Output

For each test case output two numbers: the largest possible total length of the pair of earrings which can be produced from the string, and a positive integer denoting the number of the stone after which the string ought to be cut so as to achieve this. If more than one cutting position is possible, output the leftmost (smallest) one.

Example

Input:
3
abcacdd
acbddabedff
abcbca

Output:
4 3
6 4
4 2

(the first case is illustrated in the figure, in the second case we produce a pair of earrings of the form 'abd', in the third - a pair of earrings which look like 'ab' after rotating the second one by 180 degrees).


Added by:Adrian Kosowski
Date:2004-10-29
Time limit:25s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:DASM Programming League 2004, problemset 2









SPOJ Problem Set (classical)

227. Ordering the Soldiers

Problem code: ORDERS

As you are probably well aware, in Byteland it is always the military officer's main worry to order his soldiers on parade correctly. In Bitland ordering soldiers is not really such a problem. If a platoon consists of n men, all of them have different rank (from 1 - lowest to n - highest) and on parade they should be lined up from left to right in increasing order of rank.

Sounds simple, doesn't it? Well, Msgt Johnny thought the same, until one day he was faced with a new command. He soon discovered that his elite commandos preferred to do the fighting, and leave the thinking to their superiors. So, when at the first rollcall the soldiers lined up in fairly random order it was not because of their lack of discipline, but simply because they couldn't work out how to form a line in correct order of ranks. Msgt Johnny was not at all amused, particularly as he soon found that none of the soldiers even remembered his own rank. Over the years of service every soldier had only learned which of the other soldiers were his superiors. But Msgt Johnny was not a man to give up easily when faced with a true military challenge. After a moment's thought a solution of brilliant simplicity struck him and he issued the following order: "men, starting from the left, one by one, do: (step forward; go left until there is no superior to the left of you; get back in line).". This did indeed get the men sorted in a few minutes. The problem was solved... for the time being.

The next day, the soldiers came in exactly the same order as the day before, and had to be rearranged using the same method. History repeated. After some weeks, Msgt Johnny managed to force each of his soldiers to remember how many men he passed when going left, and thus make the sorting process even faster.

If you know how many positions each man has to walk to the left, can you try to find out what order of ranks the soldiers initially line up in?

Input

The first line of input contains an integer t<=50, the number of test cases. It is followed by t test cases, each consisting of 2 lines. The first line contains a single integer n (1<=n<=200000). The second line contains n space separated integers wi, denoting how far the i-th soldier in line must walk to the left when applying Msgt Johnny's algorithm.

Output

For each test case, output a single line consisting of n space separated integers - the ranks of the soldiers, given from left to right in their initial arrangement.

Example

Input:
2
3
0 1 0
5
0 1 2 0 1

Output:
2 1 3
3 2 1 5 4
Warning: large Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-10-30
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004, problemset 2









SPOJ Problem Set (classical)

228. Shamans

Problem code: SHAMAN

In the far bare land there lives a mysterious tribe. They suffer from drought every year but they stick to their faith in god that they will never leave their home land. To counter the dry weather the shamans in the tribe must pray during the hard time and hope the blessed rain will aid their production of food.

There are 4 chief shamans in the tribe and each of them will choose a summit in the territory to proceed with his praying. The area in which the shamans' spells take effect will be the quadrangle they form, each of them being one of its vertices (which the god will see when he looks down from the high heavens). The land is quite full of pinch and punch and the tribe has selected quite a few peaks for the shamans to pray on. Of course the area of the quadrangle is expected to be as large as possible so before the shamans actually go out, they will have to choose the 4 peaks that best suit their purpose.

Input

One integer in the first line, stating the number of test cases, followed by a blank line. There will be not more than 80 tests.

For each test case, the first line is an integer n (4 <= n <= 2000) stating the number of peaks. Then n lines follow, each presenting the position of a peak, with two integers x, y (-20000 <= x, y <= 20000).

The test cases will be separated by a single blank line.

Output

A floating point number with exactly 1 digit precision: the maximum area the shamans can cover.

Example

Input:
2

4
0 0
1 0
1 1
0 1

4
0 0
0 1
1 1
1 0

Output:
1.0
1.0

Added by:Neal Zane
Date:2004-11-02
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Neal Zane









SPOJ Problem Set (classical)

229. Sorting is easy

Problem code: SORTING


 

Do you think sorting is easy?

try your luck
in brainfuck

 

For those who don't know that brainfuck is a programming language: Take a look at the converter to C. It will ignore every unknown command, therefore submitting a program in any other language won't necessarily lead to compile error, but certainly not to Accepted.

Input

The input consists of a line of up to 1000 uppercase letters, terminated with a '\n' character (ASCII value 10).

Output

The output should contain a line consisting of the same characters as the input line, but in non-descending order.

Example

Input:

BRAINFUCK

Output:

ABCFIKNRU


Added by:Adrian Kuegel
Date:2004-11-04
Time limit:1s
Source limit:500B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:BF
Resource:own problem









SPOJ Problem Set (classical)

231. The Zebra Crossing

Problem code: ZEBRA

Have you ever wondered why people collide with each other at pedestrian crossings? The reasons are probably difficult to analyse from a scientific point of view, but we can hazard a guess. A part of the problem seems to be that the statistical pedestrian, when faced with a red light, will either cross at once (this category of pedestrians doesn't really interest us, since they tend to collide with cars rather than with each other), or will stop dead and stand still until the light changes. Only when the light turns green does he begin to act rationally and heads for his destination using the shortest possible path. Since this usually involves crossing the road slightly on the bias, he will inevitably bump into someone going across and heading another way.

One day, while you are approaching the traffic lights you usually cross at, you begin to wonder how many other people you could possibly collide with if you really wanted. All the people are standing at different points on the same side of the street as you are. From past observations you can predict the exact angle and speed at which individual pedestrians are going to cross. You can decide at which point along the side of the street you will wait for the green light (any real coordinate other than a place where some other pedestrian is already standing) and at what angle and at what speed you intend to cross. There is an upper bound on the speed you may cross at.

Assume that once the light turns green, all pedestrians start moving along straight lines, at constant speed, and that collisions, however painful they may be, have no effect on their further progress. Since you wouldn't like to arouse anyone's suspicions, you also have to cross in accordance with these rules. A collision only occurs if at a given moment of time you have exactly the same x and y coordinates as some other pedestrian.

Input

Input starts with a single integer t, the number of test cases (t<=100). t test cases follow.

Each test case begins with a line containing three integers n w v, denoting the number of people other than you who wish to cross the street, the width of the street expressed in meters, and the maximum speed you can walk at given in meters per second, respectively (1<=n<=10000, 1<=w<=100, 1<=v<=10000). Each of the next n lines contains three integers xi ti ai, which describe the starting position of the i-th pedestrian measured in meters, the time (in seconds) he takes to cross the street, and the angle at which he is walking with respect to the line normal to the sides of the street, expressed in 1/60 parts of a degree (-10000<=xi<=10000, 1<=ti<=10000, -5000<=ai<=5000).

Illustration of problem input

Output

For each test case output a single integer -- the maximum number of people you can collide with by the time you reach the opposite side of the street.

Example

Input:
1
5 20 2
-20 10 2700
20 10 -2700
-5 1 4000
-4 1 4000
5 1 -4000

Output:
2

(In the example, due to the imposed speed limit, it is only possible to collide with the first two pedestrians while crossing the street, at the last possible moment.)


Added by:Adrian Kosowski
Date:2004-11-13
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004, problemset 7









SPOJ Problem Set (classical)

234. Getting Rid of the Holidays (Act I)

Problem code: HOLIDAY1


King Johnny of Byteland has in his short period of sovereignty established quite a few national holidays (close on thirty, in fact) in honour of... more or less anything he could think of. Each of these holidays occurs every a fixed number of days (possibly different for every holiday), and is accompanied by feasts, cabaret shows, and general merrymaking. Sometimes more than one holiday occurs on a single day, and once in a while all holidays take place on the same day. If this happens, the celebrations are combined and even more festive. After one such party, king Johnny started behaving strangely and had to be temporarily isolated from society.

For the period of king Johnny's absence (about 48 hours) you have been appointed Regent of Byteland. As a true patriot, you know that holidays are not good for the people, and would like to remove some before king Johnny returns (he won't mind, he never remembers anything after a party anyway). The people however, very sadly, don't know what is good for them, and will revolt if you remove more than k holidays. Try to choose the holidays you remove in such a way as to guarantee that the number of days which elapse between two consecutive holiday parties is as long as possible.

Solve the problem in at most 4kB of source code.

Input

The first line of input contains a single integer t<=200 - the number of test cases. t test case descriptions follow.

For each test case, the first line contains two space separated integers n k (1<=k < n<=30), denoting the total number of holidays and the number of holidays to be removed. The next line contains n space separated integers, the i-th being ti (1<=ti<=1018) - the number of days every which the i-th holiday occurs.

Output

For each test case, output one line containing an increasing sequence of exactly k integers - the numbers of the holidays to be removed (holidays are numbered in the input order from 1 to n).

Example

Input:
1
5 2
6 13 10 15 7

Output:
2 5

(The shortest period between two successive holiday parties is 2 days.)


Added by:Adrian Kosowski
Date:2004-11-25
Time limit:17s
Source limit:4096B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004, problemset 4









SPOJ Problem Set (classical)

235. Very Fast Multiplication

Problem code: VFMUL


 

Multiply the given numbers.

Input

 

n [the number of multiplications <= 101]

l1 l2 [numbers to multiply (at most 300000 decimal digits each)]

Text grouped in [ ] does not appear in the input file.

 

Output

 

The results of multiplications.

 

Example

Input:
5
4 2
123 43
324 342
0 12
9999 12345

Output:
8
5289
110808
0
123437655

Warning: large Input/Output data, be careful with certain languages


Added by:Darek Dereniowski
Date:2004-11-27
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:PAL









SPOJ Problem Set ()

236. Converting number formats

Problem code: ROMAN

Given the number n of test cases, convert n positive integers less than 2^32 (given one per line) from one representation to another. For convenience, n is given in the same format as the other numbers.

Input

Input is given by spelling the number in english digits (all upper case letters). Thus the range of (32-bit) input values permissible extends from ZERO (or OH) through FOUR TWO NINE FOUR NINE SIX SEVEN TWO NINE FIVE.

Output

Output 2 lines for each test case. Output is in the form of "extended" Roman numerals (also called "butchered" Roman numerals), with an overline (see sample for details) indicating the value below is "times 1000", and lower-case letters indicating "times 1000000". Thus, the range of (32-bit) output values possible is from through ivccxcivCMLXVIICCXCV, where there is a line above iv and CMLXVII. Note: For values whose residues modulo 1000000 are less than 4000, M is used to represent 1000; for values whose residues are 4000 or greater, I is used. Thus 3999 would read out as MMMCMXCIX while 4000 would readout as IV with an overline. Similar rules apply to the use of M and i for 1000000, and to that of m and i for 1000000000.

WARNING: This problem has a somewhat strict source limit

Example

Input:
THREE
FOUR OH
ONE NINE NINE NINE NINE NINE NINE NINE NINE NINE
ONE TWO THREE ZERO FOUR FIVE

Output:
  
XL
       ______      
mcmxcixCMXCIXCMXCIX
___      
CXXMMMXLV

Added by:Robin Nittka
Date:2004-11-30
Time limit:9s
Source limit:2048B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









SPOJ Problem Set (classical)

237. Sums in a Triangle

Problem code: SUMITR

Let us consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:

Take care about your fingers, do not use more than 256 bytes of code.

Input

In the first line integer n - the number of test cases (equal to about 1000). Then n test cases follow. Each test case starts with the number of lines which is followed by their content.

Output

For each test case write the determined value in a separate line.

Example

Input:
2
3
1
2 1
1 2 3
4 
1 
1 2 
4 1 2
2 3 1 1 

Output:
5
9
Warning: large Input/Output data, be careful with certain languages
Added by:£ukasz Kuszner
Date:2004-12-01
Time limit:2s
Source limit:256B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:6-th International Olympiad In Informatics July 3-10. 1994. Stockholm - Sweden, Problem 1









SPOJ Problem Set (classical)

238. Getting Rid of the Holidays (Act II)

Problem code: HOLIDAY2

As King Johnny's temporary indisposition lengthens from days to weeks, and you still hold the office of Regent of Byteland, you begin to feel that acting king is not all that much fun. You encounter various absurdly weird problems. For instance, you find that contrary to your expectations the recent removal of holidays brought about a decrease in the efficiency of the kingdom's workforce.

There appears to be only one rational explanation for all this. It seems that although every holiday occurs every a fixed number of days, the periods between consecutive holidays are long and very irregular. And it is the lack of regularity that is the root of the problem.

So, you decide it is time to tackle the problem once again, and solve it properly this time. Your main purpose is to establish an r-day working rhythm (for some integer r). Workers will work for (r-1) days, have a single day off, work for another (r-1) days, and so on. The rhythm must be arranged in such a way that holidays only ever occur on the day off work. Choose exactly k of the n holidays to remove in such a way as to be able to establish a working rhythm of the maximum possible length r.

Solve the problem in at most 4kB of source code.

Input

The first line of input contains a single integer t<=100 - the number of test cases. t test case descriptions follow.

For each test case, the first line contains two space separated integers n k (1<=k < n<=100), denoting the total number of holidays and the number of holidays to be removed. The next line contains n space separated integers, the i-th being ti (1<=ti<=1018) - the number of days every which the i-th holiday occurs.

Output

For each test case, output one line containing an increasing sequence of exactly k integers - the numbers of the holidays to be removed (holidays are numbered in the input order from 1 to n).

Example

Input:
2
6 4
1 3 4 5 6 1
8 4
200 125 200 999 380 500 200 500

Output:
1 3 4 6
2 4 5 6

(In the first test case r is equal to 3 days, in the second case it is equal to 100 days. For the second test case the output '1 2 4 5', '2 3 4 5', '2 4 5 6', '2 4 5 7' or '2 4 5 8' is also correct.)


Added by:Adrian Kosowski
Date:2004-12-07
Time limit:17s
Source limit:4096B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004, problemset 4









SPOJ Problem Set (set4)

239. Tour de Byteland

Problem code: BTOUR

As the mayor of Byteland's term of office draws to a close, he starts his preparations for reelection. For the first time in the 40 years of his political career his chances of victory seem somewhat uncertain. His main cause of worry are the disturbing results of an opinion poll which state that over 90% of the citizens regard the mayor as a portly, heavily smoking individual who sleeps in his armchair more or less all day.

After careful consultation with his public relations director, the mayor has decided to change his image. He is going to organise, sponsor and compete in... Byteland's first bicycle race! Quite naturally, the only relevant part of the race is the media coverage of the mayor; everything else is to be done at minimum cost. The street-map of Byteland consists of a not necessarily planar system of bi-directional street segments connecting intersections, in such a way that between 0 and 4 street segments meet at an intersection. The cyclists are to ride round and round a simple loop (a fixed, closed route consisting of several street segments, such that a cyclist goes along a street and through an intersection exactly once in each round). For innumerable reasons (not so difficult to guess at) the mayor would like to choose the shortest possible route for the race (in the sense of total street length). Help him determine the length of such a loop, and tell him how many different shortest loops he can choose from when organising the race.

Input

The input starts with a line containing a single integer t<=200, the number of test cases. t test cases follow.

Each test case begins with a line with two integers n m, denoting the number of intersections and the number of streets in Byteland, respectively (1<=n<=1000). m lines follow, each containing three integers ui vi di, denoting the end points and the length of the i-th street segment, respectively (1<=ui<=vi<=n, 1<=di<=106).

Output

For each test case output a single line containing exactly two space separated non-negative integers d c - the length of the shortest possible race loop, and the number of routes of this length in the graph. Output 0 0 if the race cannot be held.

Example

Input:
2
3 2
1 2 1
1 3 2
4 6
1 2 5
1 4 5
2 3 4
2 4 5
3 4 5
3 1 5

Output:
0 0
14 2

Added by:Krzysztof Kluczek
Date:2004-12-09
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:DASM Programming League 2004, problemset 4









SPOJ Problem Set ()

241. Arranging the Blocks

Problem code: BLOCKS

A group of n children are playing with a set of n2 flat square blocks. Each block is painted from above with one colour, and there are no more than 2 blocks of each colour. The blocks are initially arranged in an n x n square forming some sort of picture.

The children have been provided with some other n x n picture and asked to rearrange the blocks to that form. Since this is not really what they enjoy doing most, they intend to solve the task together and spend as little time on it as possible. Thus, every minute each child chooses a single 1 x n row or n x 1 column of blocks to rearrange. This row/column may never intersect with rows/columns chosen by other children in the same minute. A child takes one minute to perform any rearrangement (permutation) of the blocks within its row/column it likes.

Determine whether the children can perform their task of converting one block image into the other, and if so -- find the minimum possible time in minutes required to achieve this.

Input

The input starts with a line containing a single integer t<=200, the number of test cases. t test cases follow. Each test case begins with a line containing integer n (1<=n<=500). The next n lines contain n integers Pi,j each, forming a bitmap matrix representing the colours of the blocks in their initial configuration (1<=Pi,j<=n2). The following n lines contain n integers Qi,j each, corresponding to the matrix for the final configuration (1<=Qi,j<=n2).

Output

For each test case output a line with a single non-negative integer corresponding to the number of minutes required to transform matrix P into matrix Q, or the word no if no such transformation is possible.

Example

Input:
3
3
1 3 4
2 1 3
2 5 5
3 1 3
2 1 2
4 5 5
3
1 2 3
4 5 6
7 8 9
1 5 6
4 2 9
7 8 3
2
1 2
1 2
1 3
1 2

Output:
2
1
no

The actions taken in the first test case are illustrated below.

2 step transformation: 134 213 255 -> 413 312 255 -> 313 212 455

Warning: enormous Input/Output data, be careful with certain languages
Added by:Adrian Kosowski
Date:2004-12-09
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:DASM Programming League 2004, problemset 4









SPOJ Problem Set (classical)

243. Stable Marriage Problem

Problem code: STABLEMP

There are given n men and n women. Each woman ranks all men in order of her preference (her first choice, her second choice, and so on). Similarly, each man sorts all women according to his preference. The goal is to arrange n marriages in such a way that if a man m prefers some woman w more than his wife, then w likes her husband more than m. In this way, no one leaves his partner to marry somebody else. This problem always has a solution and your task is to find one.

Input

The first line contains a positive integer t<=100 indicating the number of test cases. Each test case is an instance of the stable marriage problem defined above. The first line of each test case is a positive integer n<=500 (the number of marriages to find). The next n lines are the woman's preferences: ith line contains the number i (which means that this is the list given by the ith woman) and the numbers of men (the first choice of ith woman, the second choice,...). Then, the men's preferences follow in the same format.

Output

For each test case print n lines, where each line contains two numbers m and w, which means that the man number m and the woman number w should get married.

Example

Input:
2
4
1 4 3 1 2
2 2 1 3 4
3 1 3 4 2
4 4 3 1 2
1 3 2 4 1
2 2 3 1 4
3 3 1 2 4
4 3 2 4 1
7
1 3 4 2 1 6 7 5
2 6 4 2 3 5 1 7
3 6 3 5 7 2 4 1
4 1 6 3 2 4 7 5
5 1 6 5 3 4 7 2
6 1 7 3 4 5 6 2
7 5 6 2 4 3 7 1
1 4 5 3 7 2 6 1
2 5 6 4 7 3 2 1
3 1 6 5 4 3 7 2
4 3 5 6 7 2 4 1
5 1 7 6 4 3 5 2
6 6 3 7 5 2 4 1
7 1 7 4 2 6 5 3



Output:
1 3
2 2
3 1
4 4
1 4
2 5
3 1
4 3
5 7
6 6
7 2

Warning: large Input/Output data, be careful with certain languages
Added by:Darek Dereniowski
Date:2004-12-13
Time limit:1s-3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:problem known as the Stable Marriage Problem









SPOJ Problem Set ()

245. Square Root

Problem code: SQRROOT

In this problem you have to find the Square Root for given number. You may assume that such a number exist and it will be always an integer.

Solutions to this problem can be submitted in C, C++, Pascal, Algol, Fortran, Ada, Ocaml, Prolog, Whitespace, Brainf**k and Intercal only.

Input

t - the number of test cases [t <= 50]
then t positive numbers follow, each of them have up to 800 digits in decimal representation.

Output

Output must contain exactly t numbers equal to the square root for given numbers. See sample input/output for details.

Example

Input:
3
36
81
226576

Output:
6
9
476

Added by:Roman Sol
Date:2004-12-15
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:ADA DOC ASM BF C C++ 4.0.0-8 C99 strict D FORT ICK CAML PAS fpc PAS gpc PDF PS PRLG SCM guile TEXT WSPC
Resource:ZCon 2005









SPOJ Problem Set ()

247. Chocolate

Problem code: CHOCOLA

We are given a bar of chocolate composed of m*n square pieces. One should break the chocolate into single squares. Parts of the chocolate may be broken along the vertical and horizontal lines as indicated by the broken lines in the picture.

A single break of a part of the chocolate along a chosen vertical or horizontal line divides that part into two smaller ones. Each break of a part of the chocolate is charged a cost expressed by a positive integer. This cost does not depend on the size of the part that is being broken but only depends on the line the break goes along. Let us denote the costs of breaking along consecutive vertical lines with x1, x2, ..., xm-1 and along horizontal lines with y1, y2, ..., yn-1.

The cost of breaking the whole bar into single squares is the sum of the successive breaks. One should compute the minimal cost of breaking the whole chocolate into single squares.

For example, if we break the chocolate presented in the picture first along the horizontal lines, and next each obtained part along vertical lines then the cost of that breaking will be y1+y2+y3+4*(x1+x2+x3+x4+x5).

Task

Write a program that for each test case:

Input

One integer in the first line, stating the number of test cases, followed by a blank line. There will be not more than 20 tests.

For each test case, at the first line there are two positive integers m and n separated by a single space, 2 <= m,n <= 1000. In the successive m-1 lines there are numbers x1, x2, ..., xm-1, one per line, 1 <= xi <= 1000. In the successive n-1 lines there are numbers y1, y2, ..., yn-1, one per line, 1 <= yi <= 1000.

The test cases will be separated by a single blank line.

Output

For each test case : write one integer - the minimal cost of breaking the whole chocolate into single squares.

Example

Input:
1

6 4
2
1
3
1
4
4
1
2

Output:
42

Added by:Thanh-Vy Hua
Date:2004-12-23
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:10th Polish Olympiad in Informatics, stage 1









SPOJ Problem Set (classical)

260. Containers

Problem code: CTAIN

We are given n containers, where 1 <= n <= 4. At the beginning all of them are full of water. The liter capacity of the i-th container is a natural number oi satisfying inequalities 1 <= oi <= 49. 
Three kinds of moves can be made:  

  1. Pouring the whole content of one container into another. This move can be made unless there is too little room in the second container. 
  2. Filling up one container with part of the water from another one.
  3. Pouring away the whole content of one container into a drain. 

Task

Write a program that for each test case:

Input

One integer in the first line, stating the number of test cases, followed by a blank line. There will be not more than 20 tests.

For each test case, at the first line, one positive integer n is written, n <= 4, this is the number of containers. There are n positive integers written in the second line. These are the capacities of the containers (the i-th integer oi denotes the capacity if the i-th  container,1 <= oi <= 49). In the third line there are written n numbers. These are the requested final volumes of water in the containers (the i-th integer wi denotes the requested final volume of water in the i-th container, 0 <= wi <= oi). All integers in the second and the third line are separated by single spaces.

The test cases will be separated by a single blank line.

Output

For each test case : write one integer - the minimal number of moves which lead to the requested final situation or write only one word "NO" if it is not possible to reach the requested final situation making only allowed moves.

Example

Input:
2

3
3 5 5
0 0 4

2
20 25
10 16

Output:
6
NO

Added by:Thanh-Vy Hua
Date:2004-12-24
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:3rd Polish Olympiad in Informatics, stage 1









SPOJ Problem Set (classical)

261. Triangle Partitioning

Problem code: TRIPART


A triangle can be divided into two equal triangles by drawing a median on its largest edge (in the figure below such a division is shown with the red line). Then the smaller two triangles can be divided in similar fashion into equal triangles (shown in the picture below with blue lines). This process can continue forever.

Some mathematicians have found that when we split a triangle into smaller ones using the method specified above we have only some "styles" of triangles that only differ in size. So now given the lengths of the sides of the triangle your job is to find out how many different styles of small triangles we have. (Two triangles are of same style if they are similar.)

Input

First line of the input file contains an integer N (0 < N < 35) that indicates how many lines of input there are.

Each line contains three integers a, b, c (0 < a,b,c < 100) which indicate the sides of a valid triangle. (A valid triangle means a real triangle with positive area.)

Output

For each line of input you should produce an integer T, which indicates the number of different styles of small triangles, formed for the triangle at input. Look at the example for details. You can safely assume that for any triangle T will be less than 100.

Example

Input:
2
3 4 5
12 84 90

Output:
3
41

Added by:Thanh-Vy Hua
Date:2004-12-24
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Thanh Vy Hua Le, special thanks to my friends in EPS









SPOJ Problem Set ()

262. Connections

Problem code: CONNECT

Byteotian Ministry of Infrastructure has decided to create a computer program that helps to find quickly the lengths of routes between arbitrary towns. It would be small wonder if the inhabitants of Byteotia always wanted to find the shortest route. However, it happens that they want to know the k-th shortest route. Moreover, cycles in routes are possible, i.e. routes that have recurring towns.

For example, if there are 4 routes between two towns and their lengths are 2, 4, 4 and 5, then the length of the shortest connection is 2, the second shortest is 4, the third is 4, and the fourth is 5.

Task

Write a program that for each test case:

Input

One integer in the first line, stating the number of test cases, followed by a blank line. There will be not more than 15 tests.

For each test case, at the first line, there are two positive integers n and m, separated by a single space, 1 <= n <= 100, 0 <= m <= n2-n. They are the number of towns in Byteotia and the number of roads connecting the towns, respectively. The towns are numbered from 1 to n.

In each of m successive lines there are three integers separated by single spaces: a, b and l, a <> b, 1 <= l <= 500. Each triple describes one one-way road of length l enabling to move from the town a to b. For each two towns there exist at most one road that enables to move in the given direction.

In the following line there is one integer q, 1 <= q <= 10000, denoting the number of queries. In the successive q lines there are queries written, one per line. Each query has a form of three integers separated by single spaces: c, d and k, 1 <= k <= 100. Such a query refers to the length of the k-th shortest route from the town c to the town d.

The test cases will be separated by a single blank line.

Output

For each test case, your program should write the answers to the queries read, one answer per line. In the i-th line the answer to the i-th query should be written: one integer equal to the length of the route being sought or -1, when such a route does not exist.

Each test case should be separated by a single blank line.

Example

Input:
1

5 5
1 2 3
2 3 2
3 2 1
1 3 10
1 4 1
8
1 3 1
1 3 2
1 3 3
1 4 2
2 5 1
2 2 1
2 2 2
1 1 2

Output:
5
8
10
-1
-1
3
6
-1

Added by:Thanh-Vy Hua
Date:2004-12-25
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:10th Polish Olympiad in Informatics, stage 2









SPOJ Problem Set ()

263. Period

Problem code: PERIOD

For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as AK , that is A concatenated K times, for some string A. Of course, we also want to know the period K.

Input

The first line of the input file will contains only the number T (1 <= T <= 10) of the test cases.

Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – the size of the string S. The second line contains the string S.

Output

For each test case, output “Test case #” and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case.

Example

Input:
2
3
aaa
12
aabaabaabaab

Output:
Test case #1
2 2
3 3

Test case #2
2 2
6 2
9 3
12 4


Added by:Thanh-Vy Hua
Date:2004-12-26
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM South Eastern European Region 2004









SPOJ Problem Set (classical)

264. Corporative Network

Problem code: CORNET

A very big corporation is developing its corporate network. At the beginning, each of the N enterprises of the corporation, numbered from 1 to N, organized its own computing and telecommunication center. Soon, for amelioration of the services, the corporation started to collect some enterprises in clusters, each of them served by a single computing and telecommunication center as follows. The corporation chose one of the existing centers I (serving the cluster A) and one of the enterprises J in some other cluster B (not necessarily the center) and linked them with a telecommunication line. The length of the line between the enterprises I and J is |I J|(mod 1000). In such a way two old clusters are joined to form a new cluster, served by the center of the old cluster B. Unfortunately after each join the sum of the lengths of the lines linking an enterprise to its serving center could be changed and the end users would like to know what is the new length.

Write a program to keep trace of the changes in the organization of the network that is able at each moment to answer the questions of the users.

Input

The first line of the input file will contains only the number T of the test cases (1 <= T <= 5). Each test will start with the number N of enterprises (5<=N<=20000). Then some number of lines (no more than 200000) will follow with one of the commands:

E I– asking the length of the path from the enterprise I to its serving center at the moment; I I J – informing that the serving center I is linked to the enterprise J. The test case finishes with a line containing the word O. There are fewer I commands than N commands.

Output

The output should contain as many lines as the number of E commands in all test cases. Each line must contain a single number – the requested sum of lengths of lines connecting the corresponding enterprise with its serving center.

Example

Input:
1
4
E 3
I 3 1
E 3
I 1 2
E 3
I 2 4
E 3
O

Output:
0
2
3
5

Added by:Thanh-Vy Hua
Date:2004-12-27
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM South Eastern European Region 2004









SPOJ Problem Set (classical)

272. Cave Exploration

Problem code: CAVE

A long time ago one man said that he had explored the corridors of one cave. This means that he was in all corridors of the cave. Corridors are really horizontal or vertical segments. A corridor is treated as visited if he was in at least one point of the corridor.

Now you want to know if this is true. You have a map of the cave, and you know that the explorer used the following algorithm: he turns left if he can, if he can't he goes straight, if he can't he turns right, if he can't he turns back. Exploration ends when the man reaches the entry point for the second time. Your task to count how many corridors weren't visited by explorer.

Input

In the first line there is an integer T (T <= 20) - the number of different maps. For each map in the first line there is an integer N (N <= 1000) - the number of corridors. It is known that no two vertical corridors have a common point and no two horizontal corridors have a common point. The next N lines contain the following information: the line starts with one of the characters 'V' or 'H' - vertical or horizontal corridor. Then one Y-coordinate and two X-coordinates are given for a horizontal corridor or one X-coordinate and two Y-coordinates for a vertical corridor. The last line for each map contains the X and Y coordinates of the entry point (start and end point of travel) and the direction ('W' - left, 'E' - right, 'N' - up and 'S' - down). You may assume that: the entry point is not located at the cross-point of two corridors, and the explorer can always move forward in the direction given in the input. All coordinates are integers and do not exceed 32767 by absolute value and there are no more than 500 vertical corridors and no more than 500 horizontal corridors.

Output

For each map the program has to print the number of unvisited corridors (in a separate line).

Example

Input:
2
6
H 0 6 0
H 2 1 6
V 1 0 4
V 5 3 0
V 3 0 2
H 1 2 4
6 0 W
1
V 0 –5 5
0 0 S

Output:
1
0

An example of a cave


Added by:Thanh-Vy Hua
Date:2004-12-31
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ACM South Eastern European Region 2004









SPOJ Problem Set (set5)

274. Johnny and the Watermelon Plantation

Problem code: WMELON

Shortly after his abdication from the Bytelandian throne Johnny decided to go into farming. Water melons were a natural choice as his first crop ever, since they seemed easy enough to grow and look after. So, he sold all his beer bottles and for the money he purchased a 1km x 1km square field. Here it was that he planted the water melon seeds. (The word 'planted' is really a bit of a euphemism for walking across a field gorging on a water melon and spitting out the pips but, for the sake of politeness, let us leave it this way).

To everyone's surprise a lot of the seeds sprouted stems, and soon enough many of the plants showed signs of fruit (and some had even more than one!). Then quite unexpectedly, when the water melons were still a little too unripe to eat, winter set in. Johnny knows that he has to construct a green house to protect the field but, with his rather limited budget, he cannot afford the glass to cover the whole area. He has decided that it is enough that k fruit survive the ordeal under a glazed roof. For reasons of architectural planning in Byteland it is necessary that the green house be a rectangle with sides parallel to the edges of the plot.

You have been requested to help Johnny minimise investement costs. Since glass is paid for by the square meter, design a green house with the smallest possible area fulfilling the imposed conditions.

Input

The first line of input contains the integer t<=100, the number of test cases. t test cases follow.

Every test case begins with a line containing two integers n k, denoting the total number of plants and the number of water melon fruit to be protected, respectively (1<=n<=1000, 1<=k<=106, k doesn't exceed the total number of fruit in the plantation). Each of the next n lines describes a single plant, the i-th line containing three integers xi yi fi - the X and Y coordinates of the plant, and the number of water melon fruit on it, respectively (1<=xi, yi, fi<=1000).

Output

For each test case output a single integer, denoting the area of the smallest possible rectangular glass house with horizontal and vertical edges, sufficient to cover at least k fruit of the plantation.

Example

Input:
1
6 11
1 1 2
1 2 2
3 1 2
3 2 3
4 2 5
3 3 2

Output:
2

Illustration of sample test data


Added by:Adrian Kosowski
Date:2005-01-03
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:DASM Programming League 2004, problemset 5 (acknowledgement to Thanh Vy Hua Le)









SPOJ Problem Set (classical)

275. The Water Ringroad

Problem code: WATERWAY

There is a land far, far away were the entire population dwells in walled cities at the peaks of mountains on the circumference of a plateau known as The Circle. The High Councillors of the cities developed an intricate system of communication: the cities were connected into a cycle by a perfectly round waterway. If need arose, a small paper boat with a message tied to its sail was released into the waterway and was guided by its solitary crew member (a small tin soldier) from one city to the next, and so on, until it reached its destination. Some segments of the waterway were only passable in one direction (due to waterfalls), and so there may have been pairs of cities for which communication was impossible.

As the centuries went by, the system slowly began to show its weaknesses. The waterway was so narrow that two boats going in opposite directions could never pass each other. To make matters worse, some of the more enterprising cities replaced the tin soldier by a plastic one to increase the speed of the boat, and the faster boats had to queue up behind the slower ones, and everyone got very angry indeed. The councillors gathered to address the problem and found that the best course of action would be to construct two separate channels between every pair of communicating cities A and B: one for carrying messages from A to B, the other from B to A (if communication was impossible in some direction in the old waterway, it needn't be enabled in the new one).

The High Priests of the Circle were the first to protest against the plan. They insisted that any waterway ever built should be circular and go round all the cities in the same manner as the original one, and the route of any boat must always be a perfect arc between any two adjacent cities. So the newly designed channels would in fact have to be composed of sets of adjacent fragments of circles, without any two channels sharing an arc.

The engineers have quite rightly pointed out that the new circles will be prone to the same problem of waterfalls on the same sections as the original waterway. Bearing this in mind, given a map of the old waterway, calculate the smallest possible number of circles the new waterway may consist of.

Input

Input begins with integer t<=100, the number of test cases. t test cases follow.

Each test case consists of two lines. The first contains a single integer n (3<=n<=100000), the number of cities around the Circle. The second line is a description of the old waterway - a sequence of exactly n characters 'A', 'B' or 'C', without separating spaces, terminated by a new line. These characters correspond to the state of the arcs between cities 1 and 2, 2 and 3,..., n-1 and n, n and 1, respectively, and mean: 'A' - the arc is passable when going anticlockwise, 'B' - the arc is passable in both directions, 'C' - the arc is passable when going clockwise.

Output

For each test case output a line, containing a single integer - the number of circles required for the new waterway.

Example

Input:
2
3
AAA
4
BACB

Output:
3
5

A solution to the first test case which requires 3 circles is presented below.

Illustration to test case 1


Added by:Adrian Kosowski
Date:2005-01-03
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004, problemset 5









SPOJ Problem Set (classical)

277. City Game

Problem code: CTGAME


Bob is a strategy game programming specialist. In his new city building game the gaming environment is as follows: a city is built up by areas, in which there are streets, trees, factories and buildings. There is still some space in the area that is unoccupied. The strategic task of his game is to win as much rent money from these free spaces. To win rent money you must erect buildings, that can only be rectangular, as long and wide as you can. Bob is trying to find a way to build the biggest possible building in each area. But he comes across some problems - he is not allowed to destroy already existing buildings, trees, factories and streets in the area he is building in.

Each area has its width and length. The area is divided into a grid of equal square units.The rent paid for each unit on which you're building stands is 3$.

Your task is to help Bob solve this problem. The whole city is divided into K areas. Each one of the areas is rectangular and has a different grid size with its own length M and width N. The existing occupied units are marked with the symbol R. The unoccupied units are marked with the symbol F.

Input

The first line of the input contains an integer K - determining the number of datasets. Next lines contain the area descriptions. One description is defined in the following way: The first line contains two integers-area length M<=1000 and width N<=1000, separated by a blank space. The next M lines contain N symbols that mark the reserved or free grid units,separated by a blank space. The symbols used are:

R - reserved unit

F - free unit

In the end of each area description there is a separating line.

Output

For each data set in the input print on a separate line, on the standard output, the integer that represents the profit obtained by erecting the largest building in the area encoded by the data set.

Example

Input:
2
5 6
R F F F F F
F F F F F F
R R R F F F
F F F F F F
F F F F F F

5 5
R R R R R
R R R R R
R R R R R
R R R R R
R R R R R

Output:
45
0

Added by:Thanh-Vy Hua
Date:2005-01-08
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM South Eastern European Region 2004









SPOJ Problem Set (classical)

278. Bicycle

Problem code: BICYCLE

Peter likes to go to school by bicycle. But going by bicycle on sidewalks is forbidden and going along roads is dangerous. That's why Peter travels only along special bicycle lanes. Fortunately Peter's home and school are in the immediate proximity of such paths. In the city where Peter lives there are only two bycycle lanes. Both lanes have the form of a circle. At the points where they cross it is possible to move from one path to the other. Peter knows the point where he enters the road and the point at which it is necessary to leave to enter the school. Peter is interested in the question: "What is the minimal distance he needs to cover along the lanes to get to school?"

Input

t – the number of test cases [t<=100], then t test cases follow.
The first 2 lines of each test case contain the description of the bicycle lanes:
x1 y1 r1 - 3 integers (x1, y1 - coordinates of the center of the 1st circle, r1 - radius of 1st circle)
x2 y2 r2 - 3 integers (x2, y2 - coordinates of the center of the 2nd circle, r2 - radius of 2nd circle)
-200 <= x1, x2, y1, y2 <= 200
0 <= r1, r2 <= 200
Next 2 lines contain the coordinates of Peter's home and school:
px1, py1 - 2 real numbers
px2, py2 - 2 real numbers

You may assume that this points lie on the circle with high accuracy (10-8). Both points may lie on the same circle.

Output

For each test case output the minimum distance that Peter needs to go from home to get to school. The precision of the answer must be under 0.0001. If it's impossible to get to school using the bicycle lanes output -1.

Example

Input:
3

0 0 5
4 0 3
3.0 4.0
1.878679656440357 -2.121320343559643

0 0 5
4 0 3
4.0 3.0
4.0 -3.0

0 0 4
10 0 4
4.0 0.0
6.0 0.0

Output:
8.4875540166
6.4350110879
-1
Illustration of sample test data
Added by:Roman Sol
Date:2005-01-13
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Russian National Command Olympiad for schoolboys in programming









SPOJ Problem Set (classical)

279. Interesting number

Problem code: INUMBER

For the given number n find the minimal positive integer divisable by n, with the sum of digits equal to n.

Input

t – the number of test cases, then t test cases follow. (t <= 50)
Test case description:
n - integer such that 0 < n <= 1000

Output

For each test case output the required number (without leading zeros).

Example

Input:
2
1
10

Output:
1
190

Added by:Roman Sol
Date:2005-01-13
Time limit:7s
Source limit:4096B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:XII team championship of St.-Petersburg in programming









SPOJ Problem Set (classical)

280. Lifts

Problem code: LIFTS

Serj likes old games very much. Recently he has found one arcade game in his computer. When controlling the hero it is necessary to move on a map and collect various items. At a certain stage of the game Serj has faced an unexpected problem. To continue his adventures the hero should get past over a chasm. For this purpose it is possible to use consistently located lifts which look like horizontal platforms. Each lift moves up-down vertically between some levels. The hero can pass between the next adjacent platform, however it can be done only at the moment when they are at the same level. Similarly, passing from the edge of a chasm onto the lift and vice versa is only possible at the moment when the lift appears on the level of the edge.

Each lift has a width equal to 4 meters. At the beginning the hero is in at a distance of two meters from the edge of a chasm. He should finish travel two meters after the opposite edge of the chasm. The hero moves at a speed of 2 meters a second. Thus, if the hero is in the initial position or in the center of the lift and wishes to pass to the next lift (or to descend from last lift onto the opposite edge of a chasm), he should begin movement exactly one second before they meet at one level. In two seconds the hero appears in the center of the next lift (or in the final position on the other side).

The edges of the chasm are at the same level. For each lift the range of heights between which it moves, its initial position and the direction of movement at the initial moment are given. All lifts move with a speed of one meter a second. Find out whether the hero can get over to the opposite edge of the chasm, and if so what the minimal time required for this purpose is.

A sample illustration

Input

t – the number of test cases, then t test cases follows.
[empty line]
A test case begins with n - the number of lifts, a positive integer (n <= 100), then n lines follow. The i-th line (0 < i <= n) contains four integers li ui si di, where: li - lowest position of the lift, ui - highest position of the lift, si - initial position of the lift, di - initial direction of movement (1 means up, -1 means down); (-100 <= li <= si <= ui <= 100, l1 < ui).

Output

For each test case output the minmal time in seconds, required to get to the opposite edge of the chasm. If it is impossible output -1.

Example

Input:
1

4
-1 2 1 -1
0 3 0 1
-4 0 0 -1
-2 1 0 -1
Output:
29

Added by:Roman Sol
Date:2005-01-17
Time limit:3s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:5th Russian National Command Olympiad for schoolboys in programming









SPOJ Problem Set (classical)

282. Muddy Fields

Problem code: MUDDY

Rain has pummeled on the cows' field, a rectangular grid of R rows and C columns (1 <= R <= 50, 1 <= C <= 50). While good for the grass, the rain makes some patches of bare earth quite muddy. The cows, being meticulous grazers, don't want to get their hooves dirty while they eat.

To prevent those muddy hooves, Farmer John will place a number of wooden boards over the muddy parts of the cows' field. Each of the boards is 1 unit wide, and can be any length long. Each board must be aligned parallel to one of the sides of the field.

Farmer John wishes to minimize the number of boards needed to cover the muddy spots, some of which might require more than one board to cover. The boards may not cover any grass and deprive the cows of grazing area but they can overlap each other.

Compute the minimum number of boards FJ requires to cover all the mud in the field.

Input

t – the number of test cases, then t test cases follows.
Each test case is of the following form:
Two space-separated integers: R and C, then R lines follows
Each line contains a string of C characters, with '*' representing a muddy patch, and '.' representing a grassy patch. No spaces are present.

Output

For each test case output a single integer representing the number of boards FJ needs.

Example

Input:
1
4 4
*.*.
.***
***.
..*.

Output:
4

Output details:
Boards 1, 2, 3 and 4 are placed as follows:
1.2.
.333
444.
..2.
Board 2 overlaps boards 3 and 4.

Added by:Roman Sol
Date:2005-01-19
Time limit:5s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:USACO January 2005 Gold Division









SPOJ Problem Set (classical)

283. Naptime

Problem code: NAPTIME

Goneril is a very sleep-deprived cow. Her day is partitioned into N (3 <= N <= 3,830) equal time periods but she can spend only B (2 <= B < N) not necessarily contiguous periods in bed. Due to her bovine hormone levels, each period has its own utility U_i (0 <= U_i <= 200,000), which is the amount of rest derived from sleeping during that period. These utility values are fixed and are independent of what Goneril chooses to do, including when she decides to be in bed.

With the help of her alarm clock, she can choose exactly which periods to spend in bed and which periods to spend doing more critical items such as writing papers or watching baseball. However, she can only get in or out of bed on the boundaries of a period.

She wants to choose her sleeping periods to maximize the sum of the utilities over the periods during which she is in bed. Unfortunately, every time she climbs in bed, she has to spend the first period falling asleep and gets no sleep utility from that period.

The periods wrap around in a circle; if Goneril spends both periods N and 1 in bed, then she does get sleep utility out of period 1.

What is the maximum total sleep utility Goneril can achieve?

Input

t – the number of test cases, then t test cases follow.
Each test case takes the following form:
Two space-separated integers: N and B, then N lines follows
Each line contains a single integer, U_i, between 0 and 200,000 inclusive

Output

For each test case output a single integer, the maximum total sleep utility Goneril can achieve.

Example

Input:
1
5 3
2
0
3
1
4

Output:
6

Input/Output details:
The day is divided into 5 periods, with utilities 2, 0, 3, 1, 4 in that 
order. Goneril must pick 3 periods.

Goneril can get total utility 6 by being in bed during periods 4,
5, and 1, with utilities 0 [getting to sleep], 4, and 2
respectively.

Added by:Roman Sol
Date:2005-01-19
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:USACO January 2005 Gold Division









SPOJ Problem Set ()

286. Selfish Cities

Problem code: SCITIES

Far, far away there is a world known as Selfishland because of the nature of its inhabitants. Hard times have forced the cities of Selfishland to exchange goods among each other. C1 cities are willing to sell some goods and the other C2 cities are willing to buy some goods (each city can either sell or buy goods, but not both). There would be no problem if not for the selfishness of the cities. Each selling city will sell its goods to one city only, and each buying city will buy goods from one city only.

Your goal is to connect the selfish cities in such a way that the amount of exchanged goods is maximalized.

Input

The first line contains a positive integer t<=1000 indicating the number of test cases. Each test case is an instance of the problem defined above. The first line of each test case is a pair of positive integers C1 and C2 (the number of cities wanting to sell their goods C1<=100 and the number of cities wanting to buy goods C2<=100). The lines that follow contain a sequence of (c1,c2,g) trios ending with three zeros. (c1,c2,g) means that the city c1 can offer the city c2 the amount of g<=100 goods.

Output

For each test case print the maximal amount of goods exchanged.

Example

Input:
3
3 2
1 1 10
2 1 19
2 2 11
3 2 1
0 0 0
4 4
1 1 6
1 2 6
2 1 8
2 3 9
2 4 8
3 2 8
4 3 7
0 0 0
3 2
1 1 10
2 1 21
2 2 11
3 2 1
0 0 0

Output:
21
29
22

Added by:Tomasz Niedzwiecki
Date:2005-01-22
Time limit:8s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









SPOJ Problem Set (classical)

287. Smart Network Administrator

Problem code: NETADMIN

The citizens of a small village are tired of being the only inhabitants around without a connection to the Internet. After nominating the future network administrator, his house was connected to the global network. All users that want to have access to the Internet must be connected directly to the admin's house by a single cable (every cable may run underground along streets only, from the admin's house to the user's house). Since the newly appointed administrator wants to have everything under control, he demands that cables of different colors should be used. Moreover, to make troubleshooting easier, he requires that no two cables of the same color go along one stretch of street.

Your goal is to find the minimum number of cable colors that must be used in order to connect every willing person to the Internet.

Input

t [the number of test cases, t<=500]
n m k [n <=500 the number of houses (the index of the admin's house is 1)]
[m the number of streets, k the number of houses to connect]
h1 h2 ... hk [a list of k houses wanting to be conected to the network, 2<=hi<=n]
[The next m lines contain pairs of house numbers describing street ends]
e11 e12
e21 e22
...
em1 em2
[next cases]

Output

For each test case print the minimal number of cable colors necessary to make all the required connections.

Example

Input:
2
5 5 4
2 3 4 5
1 2
1 3
2 3
2 4
3 5
8 8 3
4 5 7
1 2
1 8
8 7
1 3
3 6
3 2
2 4
2 5

Output:
2
1

Illustration to the first example

Warning: large Input/Output data, be careful with certain languages
Added by:Tomasz Niedzwiecki
Date:2005-01-23
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004, problemset 6









SPOJ Problem Set ()

288. Prime or Not

Problem code: PON

Given the number, you are to answer the question: "Is it prime?"

Solutions to this problem can be submitted in C, C++, Pascal, Perl, Python, Ruby, Lisp, Hask, Ocaml, Prolog, Whitespace, Brainf**k and Intercal only.

Input

t – the number of test cases, then t test cases follows. [t <= 500]
Each line contains one integer: N [2 <= N <= 2^63-1]

Output

For each test case output string "YES" if given number is prime and "NO" otherwise.

Example

Input:
5
2
3
4
5
6

Output:
YES
YES
NO
YES
NO

Added by:Roman Sol
Date:2005-01-24
Time limit:21s
Source limit:5000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ADA ASM BASH C# CLPS D ERL FORT ICON JAR JAVA JS LUA NEM NICE PHP PIKE ST
Resource:ZCon 2005









SPOJ Problem Set (classical)

290. Polynomial Equations

Problem code: POLYEQ

You are given the polynomial F(x) as the sum of monomials. Each monomial has the form:
[coefficient*]x[^degree] or [coefficient],
where coefficient and degree are integers such that -30000 <= coefficient <= 30000, 0 <= degree <= 6. The parameters given in [] can be skipped.
In this problem you have to find all solutions of the equation: F(x)=0.

Input

t – the number of test cases, then t test cases follow. [t <= 100]
Each line contains one polynomial F(x) given as string s in the form described above.
The length of string s is not more than 300 characters.

Output

For each test case output all solutions (including repeated) of the given equation in non-decreasing order. All solutions lie within the interval [-100.0; 100.0]. Each solution must be given with an error of not more than 0.01. It's guaranteed that all solutions are real, not complex.

Example

Input:
2
x^4-6*x^3+11*x^2-6*x
-x^2+2*x-1

Output:
0.00 1.00 2.00 3.00
1.00 1.00

Added by:Roman Sol
Date:2005-01-27
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS
Resource:ZCon 2005









SPOJ Problem Set (classical)

291. Cube Root

Problem code: CUBERT

Your task is to calculate the cube root of a given positive integer. We can not remember why exactly we need this, but it has something in common with a princess, a young peasant, kissing and half of a kingdom (a huge one, we can assure you).

Write a program to solve this crucial task.

Input

The input starts with a line containing a single integer t <= 20, the number of test cases. t test cases follow.

The next lines consist of large positive integers of up to 150 decimal digits. Each number is on its own separate line of the input file. The input file may contain empty lines. Numbers can be preceded or followed by whitespaces but no line exceeds 255 characters.

Output

For each number in the input file your program should output a line consisting of two values separated by single space. The second value is the cube root of the given number, truncated (not rounded!) after the 10th decimal place. First value is a checksum of all printed digits of the cube root, calculated as the sum of the printed digits modulo 10.

Example

Input:
5
1

8

1000

2 33076161

Output: 1 1.0000000000 2 2.0000000000 1 10.0000000000 0 1.2599210498 6 321.0000000000

Added by:Thanh-Vy Hua
Date:2005-01-29
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM South Eastern European Region 2004









SPOJ Problem Set ()

292. Alibaba

Problem code: ALIBB

Alibaba the famous character of our childhood stories would like to be immortal in order to keep bringing happiness to children. In order to reach this status he needs to prove that he is still able to do some unusual things. There are n treasures, (n <= 10000) each in a different place located along a straight road. Each treasure has a time limit, after that it vanishes. Alibaba must take all the n treasures, and he must do it quickly. So he needs to figure out the order in which he should take the treasures before their deadlines starting from the most favorable position. Alibaba has the list of places and deadlines of the treasures. A place i is located at distance di from the leftmost end of the road. The time it takes to take a treasure is instantaneous.

Alibaba must find the smallest time by which he can take all the treasures.

Input

The first line of the input contains an integer K <= 10 - determining the number of datasets

Each data set in the input stands for a particular set of treasures. For each set of treasures the input contains the number of treasures, and the list of pairs place - deadline in increasing order of the locations. White spaces can occur freely between the numbers in the input.The input data are correct.

Output

For each set of data the program prints the result to the standard output on a separate line. The solution is represented by the smallest time by which Alibaba can take all the treasures before they vanish. If this is not possible then the output is "No solution".

Example

Input:
2
5
1 3
3 1
5 8
8 19
10 15
5
1 5
2 1
3 4
4 2
5 3

Output:
11
No solution

Added by:Thanh-Vy Hua
Date:2005-01-29
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM South Eastern European Region 2004









SPOJ Problem Set ()

293. Officers on the Beat

Problem code: OFBEAT

In the Middle Ages the capital of Byteland was surrounded by stout walls to protect the citizens from intruders. The gates of the city were well guarded and the drawbridge was lifted for the night, and everyone felt pretty happy and secure. At least, for a while.

With time the usual disadvantages of a walled city became apparent. As the population increased, crime flourished in the cramped living space. Eventually it all became so bad that the mayor decided to intervene. Some of the guards were reassigned from their usual occupation of reading newspapers in the guard posts near the gates, and told to start patrolling the city. Many of the officers were rather unhappy about all this, especially after the first men to go on the beat returned with bleeding noses and bumps on their heads. Sensing the low morale of the men, the Captain of the Guard, a bright young individual, decided to reinterpret the order he had received from the mayor. He decided that patrol officers would only go out in large groups and armed to the teeth, and would only move along a few carefully chosen streets from which they could see everything that was going on in the city without actually getting involved.

The city is laid out on a regular grid, with each street running North-South or East-West from one end of the city to the other (as far as the walls allow). Every point with integer coordinates is at an intersection of two streets, one leading North-South, the other East-West. The walls that surround the city form a simple polygon whose sides run directly alongside sections of some streets of the city.

Every street in the set of 'patrolled streets' chosen by the Captain intersects with at least one other patrolled street. Furthermore, if a point belongs to one of the streets of the city then it is visible from some point of one of the patrolled street (points see each other iff the line segment connecting them is a fragment of a street). Finally, the set of patrolled streets chosen by the Captain consists of the minimum possible number of streets.

Given a description of the capital of Byteland, find out how many of its streets were actually patrolled by guards after the Captain issued his order.

Input

The first line of input contains t - the number of test cases. t test cases follow.

For each test case, the first line contains a single integer n - the number of sections the city wall consists of (4 <= n <= 2000). The second line contains exactly n integers a1,...,an describing successive sections of wall (1<=|ai|<=100000). Any two successive sections of wall are perpendicular to each other. The length of the i-th section is the absolute value of ai, while its direction is described by the sign of ai (positive means northbound or eastbound, negative - southbound or westbound when traversing the walls clockwise).

Output

For each test case output a single integer k - the number of elements of the patrolled set of streets selected by the Captain.

Example

Input:
1
14
+2 +2 +2 +2 -4 +2 +1 +2 -3 +2 -2 -8 +4 -2

Output:
4
Illustration of the sample test data. Blue lines indicate the set of patrolled streets
Added by:Adrian Kosowski
Date:2005-02-05
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:DASM Programming League 2004, problemset 6









SPOJ Problem Set (classical)

296. Teamwork is Crucial

Problem code: TWORK

In the late Middle Ages the University of Byteland was no different than any other university of the day. One of those gloomy places where philosophers brooded over the essence of life, theologians did likewise and quaralled with philosophers, while alchemists developed new caustic types of green shampoo in their futile search for gold. The thing that worried the Chancellor most was that none of the staff seemed to be in the least capable of making money in any form. When he complained about this to the Director of Human Resources, the Director came up with a brilliantly simple theory. He claimed that this lack of productivity was the direct consequence of the isolated model of work, and that wonders could be achieved by promoting teamwork.

The Director intends to assign every scientist to some 3-person workgroup. The members of the workgroup should then select which of them is to act as the group leader. And this of course is the root of the problem. Every scientist will tolerate either himself or one of his acquaintances as the leader of his group, but will never allow anyone else to have this privilege. So when creating workgroups it is necessary to bear in mind that every group should have at least one suitable candidate for the role of group leader, accepted by all its members.

Although everyone at the University knows of everyone else indirectly (as acquaintances of acquaintances of acquaintances of...), the number of direct acquaintances that every scientist has is relatively small - either equal to 2, or to 3. Even so, it ought to be possible to assign the vast majority of scientists to workgroups. Quite naturally, the dubious pleasure of performing this task has been left to you, the Acting University Algorithmist.

Input

Input starts with a single integer t, the number of test cases (t<=100). t test cases follow.

Each test case begins with a line containing two integers n m (4<=n<=m<=20000, n is the number of scientists and is divisible by 4). Exactly m lines follow containing a pair of integers ai bi each which denote that scientists ai and bi are acquaintances (1<=ai, bi<=n, each scientist has either 2 or 3 acquaintances). Acquaintanceship is mutual.

Output

For each test case, output a line containing a single integer k - the number of workgroups you have formed. In each of the next k lines output exactly 3 integers, representing the numbers of scientists belonging to respective workgroups.

Your solution will be regarded as incorrect if for some test case more than 25% of all scientists are left without a valid assignment to a workgroup.

Example

Input:
1
8 10
1 2
1 3
2 5
4 6
3 7
2 3
5 6
6 7
7 8
8 4

Output:
2
1 3 7
4 5 6

Added by:Adrian Kosowski
Date:2005-02-14
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004, problemset 7









SPOJ Problem Set (classical)

297. Aggressive cows

Problem code: AGGRCOW

Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).

His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?

Input

t – the number of test cases, then t test cases follows.
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi

Output

For each test case output one integer: the largest minimum distance.

Example

Input:

1
5 3
1
2
8
4
9

Output:

3

Output details:

FJ can put his 3 cows in the stalls at positions 1, 4 and 8,
resulting in a minimum distance of 3.


Added by:Roman Sol
Date:2005-02-16
Time limit:2s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:USACO February 2005 Gold Division









SPOJ Problem Set (classical)

300. Cable TV Network

Problem code: CABLETV

The interconnection of the relays in a cable TV network is bi-directional. The network is connected if there is at least one interconnection path between each pair of relays present in the network. Otherwise the network is disconnected. An empty network or a network with a single relay is considered connected. The safety factor f of a network with n relays is:

1. n, if the net remains connected regardless the number of relays removed from the net.
2. The minimal number of relays that disconnect the network when removed.

Exemplary illustration

For example, consider the nets from figure 1, where the circles mark the relays and the solid lines correspond to interconnection cables. The network (a) is connected regardless the number of relays that are removed and, according to rule (1), f=n=3. The network (b) is disconnected when 0 relays are removed, hence f=0 by rule (2). The network (c) is disconnected when the relays 1 and 2 or 1 and 3 are removed. The safety factor is 2.

Input

The input starts with a line containing a single integer t <= 20, the number of test cases. t test cases follow.

Write a program that computes the safety factor for the cable networks encoded by the data sets. Each data set starts with two integers: 0 <= n <=50,the number of relays in the net, and m, the number of cables in the net. Follow m data pairs (u,v), u < v, where u and v are relay identifiers (integers in the range 0..n-1). The pair (u,v) designates the cable that interconnects the relays u and v. The pairs may occur in any order. Except the (u,v) pairs, which do not contain white spaces, white spaces can occur freely in input. Input data terminate with an end of file and are correct.

Output

For each data set, prints from the beginning of a line, the safety factor of the encoded net.

Example

Input:
5
0 0
1 0
3 3 (0,1) (0,2) (1,2)
2 0
5 7 (0,1) (0,2) (1,3) (1,2) (1,4) (2,3) (3,4)

Output:
0
1
3
0
2

Added by:Thanh-Vy Hua
Date:2005-02-27
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM South Eastern European Region 2004









SPOJ Problem Set (classical)

301. Booklets

Problem code: BOOK

Bob has a difficult job. He must distribute advertising booklets for extra school activities in different schools. The booklets have different number of pages. Bob has a list with the number of pages of each booklet and the number of schools that he must visit. He has to distribute the booklets such that each school gets a number of booklets equal to either the lower integer part (LIP),or the upper integer part (UIP) of the number of booklets divided by the number of schools. Poor Bob must obey other rules too. He must distribute all the UIP number of booklets first and then the LIP number of booklets.

Any booklet A that is distributed to a school S_i must have fewer or at most an equal number of pages that any other booklet B that is distributed to a school S_j, if S_i gets the booklets before S_j (i.e if i < j then pages(A) <= pages(B)). When Bob distributes the booklets to a school he must distribute them in the same relative order in which they are on his list.

Moreover, he must distribute them very fast. When he comes back to the advertising company his boss verifies if he accomplished well his task, by asking him the number of pages of the first booklet distributed to a specific school, following the order in which Bob visited the schools (starting with 0). Difficult job, isn't it? Can you help him?

Input

The input starts with a line containing a single integer t <= 20, the number of test cases. t test cases follow.

Each data set in the input stands for a particular set of bookets. For each set of booklets the input contains the number of schools, the school specified by Bob's boss, the number of booklets (less than 3000), the number of pages of each booklet (fits in integer). White spaces can occur freely between the numbers in the input. The input data are correct.

Output

For each set of data the program prints the result to the standard output on a separate line. The solution is represented by the number of pages of the first booklet distributed to the specified school.

Example

Input:
1
3
2
7
3 5 9 1 11 14 2

Output:
11

Added by:Thanh-Vy Hua
Date:2005-02-27
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM South Eastern European Region 2004









SPOJ Problem Set (classical)

302. Count on Cantor

Problem code: CANTON

One of the famous proofs of modern mathematics is Georg Cantor's demonstration that the set of rational numbers is enumerable. The proof works by using an explicit enumeration of rational numbers as shown in the diagram below.

1/1 1/2 1/3 1/4 1/5 ...
2/1 2/2 2/3 2/4
3/1 3/2 3/3
4/1 4/2
5/1

In the above diagram, the first term is 1/1, the second term is 1/2, the third term is 2/1, the fourth term is 3/1, the fifth term is 2/2, and so on.

Input

The input starts with a line containing a single integer t <= 20, the number of test cases. t test cases follow.

Then, it contains a single number per line.

Output

You are to write a program that will read a list of numbers in the range from 1 to 10^7 and will print for each number the corresponding term in Cantor's enumeration as given below.

Example

Input:
3
3
14
7

Output:
TERM 3 IS 2/1
TERM 14 IS 2/4
TERM 7 IS 1/4

Added by:Thanh-Vy Hua
Date:2005-02-27
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ACM South Eastern European Region 2004









SPOJ Problem Set (classical)

303. The Unstable Cube

Problem code: UCUBE


A large cube (of size NxNxN) is given. At the beginning it consists of small blocks (1x1x1) and each block is painted in some color (different blocks may have the same color). But in the process of exploitation some blocks have disappeared. Given 6 photos of the unstable cube you have to calculate the maximum possible number of blocks that still remain in the unstable cube. It is possible that the unstable cube consists of more than one part.

Input

t – the number of test cases, then t test cases follow.
N - size of the big cube [1 <= N <= 10]
In the next N lines views of the cube from 6 sides are described (in the following order: from the front, left, back, right, from above, from below). Each such view is represented by a table of size NxN in which different letters denote different colors, and the symbol "." (point) means that it is possible to see all the way through the cube at this point. Consecutive views are separated by exactly one space.

The bottom border of the top view corresponds to the top border of the front view, and the top border of the bottom view - to the bottom border of the front view. For the front, back, left and right views the top and bottom sides of a view correspond to the top and bottom of the cube.

The input file is correct, i.e. each test case describes a possible configuration.

Output

For each test case output one integer: the required maximum number of blocks remaining in the unstable cube.

Example

Input:
2
3
.R. YYR .Y. RYY .Y. .R.
GRB YGR BYG RBY GYB GRB
.R. YRR .Y. RRY .R. .Y.
2
ZZ ZZ ZZ ZZ ZZ ZZ
ZZ ZZ ZZ ZZ ZZ ZZ

Output:
11
8

Added by:Roman Sol
Date:2005-03-01
Time limit:1s
Source limit:20000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:The Moscow Olympiad on computer science 2004/05. Correspondence round.









SPOJ Problem Set (classical)

309. The Room Pattern

Problem code: RATTERN

It was decided to make a parquet floor in a room of size NxM. The idea is to lay out some pattern on the floor. The parquet tiles with which the floor of the room looks best consist of squares 1x1, each of which can be either white or black. The required color of each square of the room is specified on the map of the room.

There are four different forms of parquet tiles:

Illustration of parquet tiles

Squares of one parquet tile can be painted differently. Some types of tiles can be of identical shape, but painted differently. Tiles of different types can have different cost. The number of available tiles of each type is not limited. Tiles are allowed to be turned around somehow (by an angle which is a multiple of 90 degrees), but it is not permitted to break a tile or to put it face sheet downwards. Initially, any part of the floor can be already laid out by tiles. You are requested to calculate the minimal cost of the tiles necessary to pave the remaining part of the room.

Input

t – the number of test cases, then t test cases follow.
In the first line of each test case three numbers are written: N, M (the sizes of the room) and K (number of accessible types of tiles). [1<= N, M <= 8], [1 <= K <= 10]. Next there is a description of the desired painting of the floor. The description is given in the form of N lines of M numbers each, where 0 denotes the color white, 1 - the color black, 2 - a square which has already been covered by a tile. In the last K lines the descriptions of available types of tiles are given in the following format:
[Form] [cost] [painting] where:
[Form] is a number from 1 to 4, describing the form of a tile (see figure above)
[Cost] is an integer not larger than 10000, describing the cost of one tile of the type.
[Painting] is a sequence of between one and three numbers 0 or 1. Its length is the same as the number of squares of which the tile consists, and the respective numbers describe colors of square tiles in the order in which the squares are numbered in the figure.

Output

For each test case output one integer: the minimal cost of laying the remaining part of the parquet, or -1 if the task cannot be performed.

Example

Input:

1
4 3 3
2 2 2
2 0 0
2 1 2
2 2 2
2 10 0 0
1 5 1
4 6 0 0 1

Output:

15

Added by:Roman Sol
Date:2005-03-05
Time limit:17s
Source limit:20000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:The Moscow Olympiad on computer science 2004/05. Correspondence round.









SPOJ Problem Set (classical)

318. Pythagorean Legacy

Problem code: PITPAIR

It is necessary to find a minimal integer value R which is equal to the length of the hypotenuse (the side opposite the right angle) of N non-identical rectangular triangles with integer lengths of sides.

Input

t - number of test cases [t <= 100], than t lines follow, each line contains one integer - N, equal to the required number of different rectangular triangles. [1 <= N <= 2000]

Output

For each test case your program should output a number R in a separate line (R fits in a 64-bit integer), equal to the minimal integer value of a hypotenuse for which exactly N different rectangular triangles can be constructed; then in separate lines follow exactly N numbers equal to the shorter cathetus (side adjacent to the right angle) of each of the rectangular triangles, in ascending order.

Example

Input:
2
1
2

Output:
5
3
25
7
15

Added by:Roman Sol
Date:2005-03-01
Time limit:9s
Source limit:8192B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ZCon 2005









SPOJ Problem Set (classical)

325. The Tall Windmills

Problem code: WINDMILL

In the later days of his career Johnny purchased a long and narrow strip of land on which he intended to erect a row of windmills, and live off the electrical energy produced by his little power plant. To his dismay, he soon discovered that he had been badly cheated - throughout most of the year the wind blew lengthwise through the strip, rather than in a perpendicular direction. As a result, the wind was certain to lose most of its force on the first windmill it encountered, leaving all the others idle. Johnny could only see one way of coping with this problem, namely - to vary the height of windmills situated relatively close to each other. More precisely, Johnny intends to build exactly n windmills along a straight line, with equal spacing (of one Bytelandian furlong) between adjacent windmills. It has been established by a team of experts that if two windmills are k Bytelandian furlongs apart from each other, their height must differ by at least n-k Bytelandian yards. No windmill may ever be lower than 1 Bytelandian yard, and some, obviously, may need to be considerably higher. But tall windmills are far more expensive to construct, and thus you have been asked to choose the heights of Johnny's windmills in such a way as to guarantee that the tallest windmill has the minimum possible height.

Input

Input starts with a single integer t, the number of test cases (t<=100). t test cases follow.

Each test case consists of exactly one integer n (1<=n<=100) - the number of windmills Johnny intends to construct.

Output

For each test case output a line with exactly n numbers, denoting the heights of successive windmills given in the order in which they are arranged along the road.

Example

Input:
3
1
2
3

Output:
1
1 2
2 4 1

Added by:Adrian Kosowski
Date:2005-04-13
Time limit:17s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:DASM Programming League 2004, problemset 9









SPOJ Problem Set (classical)

327. Platon and Socrates

Problem code: PLATON

Platon and Socrates one day decided to play a new game. They asked their friend to think of two numbers between 1 and 5000, not equal. Then they asked him to tell the product to Platon and the sum to Socrates. After that they tried to figure out what these numbers are. They played a lot of times but none of them could guess these numbers. Finally they made it!! Here is the dialogue:

Your task is to find all pairs Platon and Socrates could have been thinking about. Numbers are limited to the given range.

Input

Input starts with a single integer t, the number of test cases (t<=2000). t test cases follow. Each test case consists of one line containing two integers l r seperated by a single space, denoting the range of numbers ( 1<= l < r <=5000, r-l < 200 ).

Output

For the i-th test case output a line with the text case i. In the next line print n - number of pairs from range (l,r). Then exactly n lines follow with two numbers seperated by single space. The first number is not greater than the second. Pairs are printed in increasing sum order.

Example

Input
2
1 10
2 8

Output
case 1
0
case 2
0

Added by:Bogus³aw K. Osuch
Date:2005-04-14
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource::P









SPOJ Problem Set (classical)

328. Bishops

Problem code: BISHOPS

Yesterday was Sam's birthday. The most interesting gift was definitely the chessboard. Sam quickly learned the rules of chess and defeated his father, all his friends, his little sister, and now no one wants to play with him any more.

So he decided to play with another birthday gift – a Book of Math Problems for Young Mathematicians. He opened the book somewhere in the middle and read the following problem: "How many knights can be placed on a chessboard without threatening each other?" After a while he realized that this was trivial and moved on to the next problem: "How many bishops can be placed on a chessboard without threatening each other?". Sam is in trouble here. He is not able to solve this problem and needs your help.

Sam's chessboard has size N x N. A bishop can move to any distance in any of the four diagonal directions. A bishop threatens another bishop if it can move to the other bishop's position. Your task is to compute the maximum number of bishops that can be placed on a chessboard in such a way that no two bishops threaten each other.

Input

The input file consists of several lines. The line number i contains a single number N representing the size of the i-th chessboard. [N <= 10^100]

Output

The output file should contain the same number of lines as the input file. The i-th line should contain one number – the maximum number of bishops that can be placed on i-th chessboard without threatening each other.

Example

Input:
2
3

Output:
2
4


Added by:Roman Sol
Date:2005-04-17
Time limit:1s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:IPSC 2004









SPOJ Problem Set (classical)

329. Calls

Problem code: CALLS

A young archeologist Senoj Anaidni recently made a very important discovery which will make him famous (or at least he thinks so). He found several scraps of paper resembling advertisement flyers of an ancient phone company. His research showed that modern phone companies follow a few basic rules to compose their flyers (and there is no reason to assume that old companies were an exception).

Each company operates certain number of phone lines. Each phone line connects a pair of cities, and it can be used in both directions. The cost of using each line is a fixed positive number. A call from city A to city B may be routed through one or more other cities, in which case the cost of the call is the sum of the costs of all lines used. (In fact, sometimes it is cheaper to route the call through several other cities than to use the direct connection, even if there exists one.)

To make the information comprehensible to the customer, the phone company lists the cost of the cheapest possible call between every pair of cities serviced by the company. To impress the customer even more, the company also lists the number of lines it operates.

Indeed, each of Senoj's ancient flyers start like this: "Using our 47 telephone lines, we serve 10 most important cities of the world! A call from Sparta to Troja costs 12 dennario, Sparta to Athens is 15 dennario, ...". The list of all pairs of cities and the respective costs of the cheapest possible call between them follows.

This supports Senoj's hypothesis about the origin of the papers, but he is not sure whether they are really genuine. Other archeologists often play dirty jokes on him by making ridiculous forgeries in a hope, that he will make a fool of himself. Luckily, they are often not very meticulous, so we can safely assume, that a flyer is a forgery if and only if it could not have been published by any phone company.

Input

The first line of the input file gives the number t of flyers found by Senoj. [t <= 50] Each flyer is described in a separate block starting with a line containing two integers - N and K - where N is the number of cities and K is the number of phone lines. [N <= 300 K <= 1200] The block continues with N-1 lines giving the costs of the cheapest calls between all pairs of cities. In particular, the i-th line contains (N-i) numbers, where j-th number represents the cost of a call between the cities i and (i+j).

Output

For every input block, output a line containing either "YES" or "NO". "YES" should be printed, if it is possible to assign costs to the phone lines operated by the company so that the cheapest calls are as advertised in the flyer. "NO" should be printed if this is not possible.

Example

Input:
2
3 3
1 2
2
3 2
1 2
2


Output:
YES
NO


Added by:Roman Sol
Date:2005-04-17
Time limit:3s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:IPSC 2004









SPOJ Problem Set (classical)

332. Hard Question

Problem code: HARDQ


Students of computer science in Bratislava enjoy hiking and camping during their long summer breaks. They love walking silently in the groves, visiting sparkling waterfalls, exploring dark caves, climbing steep hills, or just sleeping in a tent. Some of them already visited all the national parks in Slovakia and nearby countries.

With no more new national parks to visit, frustrated students decided to set up a new national park (NP) by themselves. After long arguing, they finally agreed on the boundary of the NP. Now they want to purchase all the land needed for NP from present owners. Their funds are limited (after all, they are only students), therefore they do not want to buy any land outside the NP.

The NP can be described as a polygon with N vertices. There is a set P of M rectangular plots of land available for sale by their owners. The rectangles are mutually disjoint and axis-parallel. Your task is to decide whether it is possible to purchase subset of plots P exactly covering the proposed NP.

Input

Input file consists of several test cases separated by a blank line. Each test case starts with two integers N and M. Next N lines contain the coordinates of the vertices of the NP. Each of the following M lines describes one plot. For each plot, the coordinates of two opposite corners of the rectangle are given. The values N=0, M=0 end the input and should not be processed. [N, M <= 3000]

Output

For each test case output either 'YES' or 'NO' depending on whether it is possible to set up the NP using P or not.

Example

Input:
4 2
0 0
0 2
2 2
2 0
1 0 0 2
1 0 2 2

3 1
0 0
2 2
2 0
0 0 1 1

0 0

Output:
YES
NO


Added by:Roman Sol
Date:2005-04-17
Time limit:5s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:IPSC 2004









SPOJ Problem Set (classical)

334. The Philosophical Dispute

Problem code: PHDISP

One day, mathematician and philosopher were engaged in a heated dispute.

Philosopher said:
- Ideal line has only length and no width, therefore, no line can have an area.
Mathematician replied:
- That's as it may be, but still you can ll a square with a line in such a way that there will be no gaps.
And you can't deny that a square has an area, and he grinned.
But Philosopher still wasn't convinced:
- Show me this line, then.
- With pleasure... - responded Mathematician and scribbled some equations on a piece of paper:

- With t increasing, the point (x, y) will move around the square, forming a line.
- So what? - asked Philosopher. How is it going to ll the entire square?
- Indeed, it will, - said Mathematician, - Whichever point inside the square you draw, the line will eventually cross that point.
- No, - replied Philosopher indignantly, - Anyway, I don't believe. When will the line cross this point? - and he put a thick dot inside the square.
Give Philosopher an answer.

Input

t – number of tests [t <= 150], than t test cases follows.
The first line of each test case contains the coordinates (x0, y0) of the dot center (-1 <= x0, y0 <= 1). The second line contains eps <= 0.0001 - the radius of the dot (the dot is essentially a small circle).

Output

For each test case output any value of t in the segment [0, 10^12], which corresponds to the line crossing the dot, or "FAIL", if the line doesn't cross the dot.

Example

Sample input:
1
0.744 0.554
0.01

Sample output:
5.3


Added by:Roman Sol
Date:2005-04-25
Time limit:3s
Source limit:20000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:IX Ural Championship (Round II)









SPOJ Problem Set (classical)

336. Exchange Operations

Problem code: EOPERA


Given a sequence of 12 numbers consisting of 0 and the first 11 natural numbers. Suppose number 0 is in the i-th position of the sequence (positions are numbered from 0 to 11). You can swap it with the number in the j-th position if the following conditions hold:

Your task is to find the minimum number of exchange operations required to sort the sequence in increasing order.

Input

The first line of the input file contains an integer representing the number of test cases to follow. Each test case contains a sequence of twelve numbers consisting of 0,1,2,..,11, separated by single space. You can assume that the given sequence can always be sorted in increasing order by using the exchange operations

Output

For each test case, output the minimum number of exchange operations required to sort the given sequence in increasing order.

Example

Input:
2
1 10 2 3 0 5 7 4 8 6 9 11
6 4 1 0 3 5 9 7 2 10 11 8

Output:
8
9

Added by:Duc
Date:2005-04-28
Time limit:19s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Based on a problem from acm.uva.es









SPOJ Problem Set (classical)

339. Recursive Sequence

Problem code: SEQ

Sequence (ai) of natural numbers is defined as follows:

   ai = bi (for i <= k)
   ai = c1ai-1 + c2ai-2 + ... + ckai-k (for i > k)

where bj and cj are given natural numbers for 1<=j<=k. Your task is to compute an for given n and output it modulo 109.

Input

On the first row there is the number C of test cases (equal to about 50).
Each test contains four lines:
k - number of elements of (c) and (b) (1 <= k <= 10)
b1,...,bk - k natural numbers where 0 <= bj <= 109 separated by spaces c1,...,ck - k natural numbers where 0 <= cj <= 109 separated by spaces
n - natural number (1 <= n <= 109)

Output

Exactly C lines, one for each test case: an modulo 109

Example

Input:
3 
3 
5 8 2 
32 54 6 
2 
3 
1 2 3 
4 5 6 
6 
3 
24 354 6 
56 57 465 
98765432

Output:
8 
714 
257599514

Added by:Pawe³ Dobrzycki
Date:2005-04-29
Time limit:2s
Source limit:8196B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:IV Podlasian Contest in Team Programming









SPOJ Problem Set (classical)

344. Poker

Problem code: POKER

In poker, you have 5 cards. There are 10 kinds of poker hands (from highest to lowest):

Write a program that will help you play poker by telling you what kind of hand you have.

Input

The first line of input contains the number of test cases (no more than 20). Each test case consists of one line - five space separated cards. Each card is represented by a two-letter (or digit) word. The first character is the rank (A,K,Q,J,T,9,8,7,6,5,4,3 or 2), the second character is the suit (S,H,D,C standing for spades, hearts, diamonds and clubs). The cards can be in any order (but they will not repeat).

Output

For each test case output one line describing the type of a hand, exactly like in the list above.

Example

Input:
3
AH KH QH TH JH
KH 5S 3C 5C 7D
QH QD 2S QC 2C

Output:
royal flush
pair
full house

Added by:Tomek Czajka
Date:2005-05-03
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Purdue Programming Contest Training









SPOJ Problem Set (classical)

345. Mixtures

Problem code: MIXTURES

Harry Potter has n mixtures in front of him, arranged in a row. Each mixture has one of 100 different colors (colors have numbers from 0 to 99).

He wants to mix all these mixtures together. At each step, he is going to take two mixtures that stand next to each other and mix them together, and put the resulting mixture in their place.

When mixing two mixtures of colors a and b, the resulting mixture will have the color (a+b) mod 100.

Also, there will be some smoke in the process. The amount of smoke generated when mixing two mixtures of colors a and b is a*b.

Find out what is the minimum amount of smoke that Harry can get when mixing all the mixtures together.

Input

There will be a number of test cases in the input.

The first line of each test case will contain n, the number of mixtures, 1 <= n <= 100.

The second line will contain n integers between 0 and 99 - the initial colors of the mixtures.

Output

For each test case, output the minimum amount of smoke.

Example

Input:
2
18 19
3
40 60 20

Output:
342
2400

In the second test case, there are two possibilities:

The first scenario is a much better way to proceed.


Added by:Tomek Czajka
Date:2005-05-03
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Purdue Programming Contest Training









SPOJ Problem Set (main)

346. Bytelandian gold coins

Problem code: COINS

In Byteland they have a very strange monetary system.

Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit).

You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins.

You have one gold coin. What is the maximum amount of American dollars you can get for it?

Input

The input will contain several test cases (not more than 10). Each testcase is a single line with a number n, 0 <= n <= 1 000 000 000. It is the number written on your coin.

Output

For each test case output a single line, containing the maximum amount of American dollars you can make.

Example

Input:
12
2

Output:
13
2

You can change 12 into 6, 4 and 3, and then change these into $6+$4+$3 = $13. If you try changing the coin 2 into 3 smaller coins, you will get 1, 0 and 0, and later you can get no more than $1 out of them. It is better just to change the 2 coin directly into $2.


Added by:Tomek Czajka
Date:2005-05-03
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:C C++ 4.0.0-8 JAVA PYTH 2.7 RUBY
Resource:Purdue Programming Contest Training









SPOJ Problem Set (classical)

348. Expedition

Problem code: EXPEDI

A group of cows grabbed a truck and ventured on an expedition deep into the jungle. Being rather poor drivers, the cows unfortunately managed to run over a rock and puncture the truck's fuel tank. The truck now leaks one unit of fuel every unit of distance it travels.

To repair the truck, the cows need to drive to the nearest town (no more than 1,000,000 units distant) down a long, winding road. On this road, between the town and the current location of the truck, there are N (1 <= N <= 10,000) fuel stops where the cows can stop to acquire additional fuel (1..100 units at each stop).

The jungle is a dangerous place for humans and is especially dangerous for cows. Therefore, the cows want to make the minimum possible number of stops for fuel on the way to the town. Fortunately, the capacity of the fuel tank on their truck is so large that there is effectively no limit to the amount of fuel it can hold. The truck is currently L units away from the town and has P units of fuel (1 <= P <= 1,000,000).

Determine the minimum number of stops needed to reach the town, or if the cows cannot reach the town at all.

Input

The first line of the input contains an integer t representing the number of test cases. Then t test cases follow. Each test case has the follwing form:

Output

For each test case, output a single integer giving the minimum number of fuel stops necessary to reach the town. If it is not possible to reach the town, output -1.

Example

Input:
1
4
4 4
5 2
11 5
15 10
25 10

Output:
2

Input details
The truck is 25 units away from the town; the truck has 10 units
of fuel.  Along the road, there are 4 fuel stops at distances 4,
5, 11, and 15 from the town (so these are initially at distances
21, 20, 14, and 10 from the truck).  These fuel stops can supply
up to 4, 2, 5, and 10 units of fuel, respectively.

Output details:
Drive 10 units, stop to acquire 10 more units of fuel, drive 4 more
units, stop to acquire 5 more units of fuel, then drive to the town.

Added by:Duc
Date:2005-05-03
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:US Open International 2005 Gold Division









SPOJ Problem Set (classical)

349. Around the world

Problem code: AROUND

Over the years, FJ has made a huge number of farmer friends all around the world. Since he hasn't visited 'Farmer Ted' from England and 'Boer Harms' from Holland for a while, he'd like to visit them.

He knows the longitude of the farm where each of his worldwide friends resides. This longitude is an angle (an integer in the range 0..359) describing the farm's location on the Earth, which we will consider to be a circle instead of the more complex and traditional spherical representation. Except for the obvious discontinuity, longitudes increase when traveling clockwise on this circle.

FJ plans to travel by airplane to visit his N (1 <= N <= 5,000) friends (whose farms are uniquely numbered 1..N). He knows the schedules for M (1 <= M <= 25,000) bidirectional flights connecting the different farms. Airplanes always travel shortest paths on the Earth's surface (i.e., on the shortest arc of a circle).

There will always be a unique shortest path between two farms that are directly connected. No pair of antipodal farms (exactly opposite each other on the circle) is ever directly connected.

Each airplane flight can be described as traveling in clockwise or counterclockwise direction around the Earth's surface. For example, a flight from longitude 30 to longitude 35 would be clockwise, as would be a flight from longitude 350 to longitude 10. However, a flight from longitude 350 to longitude 200 follows a shortest path counterclockwise around the circle.

FJ would find it very cool if he could make a trip around the world, visiting some of his friends along the way. He'd like to know if this is possible and if so, what is the minimum number of flights he can take to do so.

He wants to start and finish his journey at the location of his best friend (the one listed first in the input below). In order to make sure he actually circles the Earth, he wants to ensure that the clockwise distance he travels is different from the counterclockwise distance he travels.

Input

The first line of the input contains an integer t representing the number of test cases. Then t test cases follow. Each test case has the following form:

Output

For each test case, output a single integer specifying the minimum number of flights FJ needs to visit to make a trip around the world. Every time FJ moves from one farm to another counts as one flight. If it is impossible to make such a trip, output the integer -1.

Example

Input:
1
3 3
0
120
240
1 2
2 3
1 3

Output:
3

Input details
Farmer John has three friends at longitudes 0, 120, and 240.  There are
three flights: 0<->120, 120<->240, and 0<->240.  The journey must start and
finish at longitude 0.

Output details
FJ must visit all 3 friends to make a full trip around the world.

Added by:Duc
Date:2005-05-03
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:US Open International 2005 Gold Division









SPOJ Problem Set (classical)

350. Landscaping

Problem code: LANDSCAP

Farmer John is making the difficult transition from raising mountain goats to raising cows. His farm, while ideal for mountain goats, is far too mountainous for cattle and thus needs to be flattened out a bit. Since flattening is an expensive operation, he wants to remove the smallest amount of earth possible.

The farm is long and narrow and is described in a sort of two-dimensional profile by a single array of N (1 <= N <= 1000) integer elevations (range 1..1,000,000) like this:

1 2 3 3 3 2 1 3 2 2 1 2,

which represents the farm's elevations in profile, depicted below with asterisks indicating the heights:

    * * *     *
  * * * * *   * * *   *
* * * * * * * * * * * *
1 2 3 3 3 2 1 3 2 2 1 2

A contiguous range of one or more equal elevations in this array is a "peak" if both the left and right hand sides of the range are either the boundary of the array or an element that is lower in elevation than the peak. The example above has three peaks.

Determine the minimum volume of earth (each unit elevation reduction counts as one unit of volume) that must be removed so that the resulting landscape has no more than K (1 <= K <= 25) peaks. Note well that elevations can be reduced but can never be increased.

If the example above is to be reduced to 1 peak, the optimal solution is to remove 2 + 1 + 1 + 1 = 5 units of earth to obtain this set of elevations:

    * * *     -
  * * * * *   - - -   -
* * * * * * * * * * * *
1 2 3 3 3 2 1 1 1 1 1 1

where '-'s indicate removed earth.

Input

The first line of the input contains integer t representing the number of test cases. Then t test cases follow. Each test case has the following form:

Output

For each test case, output the minimum volume of earth that must be removed to reduce the number of peaks to K.

Example

Input:
1
12 1
1
2
3
3
3
2
1
3
2
2
1
2

Output:
5

Input details
This is the example used above.

Added by:Duc
Date:2005-05-03
Time limit:9s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: US Open International 2005 Gold Division









SPOJ Problem Set (classical)

351. Ha-noi!

Problem code: HAN01

Little Sabrina loves solving puzzles. Last week she got a new puzzle: The "Tower of Hanoi" puzzle. This puzzle is based on an old legend: "The temple priests of hanoi have to transfer a tower consisting of 64 fragile disks of gold from one part of the temple to another, one disk at a time. The disks are arranged in order, no two of them the same size, with the largest on the bottom and the smallest on top. Because of their fragility, a larger disk may never be placed on a smaller one, and there is only one intermediate location where disks can be temporarily placed. It is said that before the priests complete their task the temple will crumble into dust and the world will vanish in a clap of thunder." Sabrina reconstructed the problem with some coins of different size. She solved the puzzle for three coins in 7 steps, for four coins in 15 steps,... after solving the problem with 7 coins she had the hang of it. Yesterday she started to solve the puzzle with 31 coins and her optimal strategy. After hours of moving coins from one pile to the other she was very tired and went to bed. This was a bad idea! Her little brother Robin discovered the towers of coins and - whoops! - threw it on the floor. Then he noticed a sheet of paper: "Don't touch this towers! Steps: 16543". "Oh no!" Robin has to reconstuct the tower because his sister can get very, very angry... Your task is to help Robin to reconstruct the towers. Sabrina started the game with all disks on peg number one and her goal was to move the disks to peg number two. She used her optimal strategy and noted the number of steps she had done.

Input

The first line of input contains one integer t: The number of testcases. t lines follow. Each line contains two integers n (2< n< 61) and k (0< k< 2n). n is the number of disks of the hanoi puzzle and k the number of steps Sabrina had done. Please be careful, the number k can be very large, it may not fit in a 32 bit integer.

Output

Output the reconstructed configuration of the towers after k steps. For each testcase output three lines. One for each tower. Each line consists of the tower identifier (1,2,3) a colon, one space and the disk numbers (n,n-1,...,2,1) which are seperated by a '|'-character.

Example

Input:
3
3 6
32 889397450
31 16543
Output:
1: 1
2: 3|2
3:
1: 32|31|28|25|18|17|14|3
2: 30|29|26|13|12|11|10|9|6|5|2
3: 27|24|23|22|21|20|19|16|15|8|7|4|1
1: 31|30|29|28|27|26|25|24|23|22|21|20|19|18|17|16|7|6
2: 15|8|5|4|3|2|1
3: 14|13|12|11|10|9

Added by:Simon Gog
Date:2005-05-03
Time limit:2s
Source limit:8082B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS PERL 6
Resource:Ulm Algorithm Course SoSe 2005









SPOJ Problem Set (classical)

359. Alpha Centauri Tennis

Problem code: ACT


As you may know, planets of Alpha Centauri (if they indeed do exist) would provide excellent conditions for intelligent life forms.

It is indeed true that there is a small Earthlike planet near Alpha Centauri, inhabited by a population of no particular significance. These humanlike creatures have much in common with us. Living in similar comunities and having similar body structure and behavioral patterns, they unsurprisingly appreciate (approximately) the same time-killing activities as we do. One of these, the second most popular after Alpha Centauri Croquet, is the Alpha Centauri Tennis.

Although its rules differ from Earth Tennis, the two player version of Alpha Centauri Tennis resembles it in many ways. Same as Earth Tennis, it is played on a rectangular court divided into two parts by a net. Two players, standing on opposite sides of it, use a stringed racket to hit a ball back and forth to each other. There are certain rules how to hit the ball. The player who forces his opponent to violate one of these rules wins the current ball. The aim of both players is to win enough balls to win a game, enough games to win a set and enough sets to win the whole match. In the N player version of the Alpha Centauri Tennis a ball can be won by any one of the N players. Although technical details of this can be difficult to imagine, Alpha Centaurians are extremely inventive.

In the general N-player version, players serve in turns, following order determined before the match. Moreover, they shift when starting individual games and sets. For example, the players are A, B and C. They are ordered alphabetically. Player A serves the first ball of the first game. When the ball is won by one of the players, its B's turn to serve. After the game is won by one of the players, player B starts the second game. Finally, when the first set is won by someone, player B starts the second set. This repeats, always shifted by one player, until the match ends.

For three players the serving order looks as follows:
Set 1:
Game 1: A,B,C,A,B,C...
Game 2: B,C,A,....
Game 3: C,A,B,....
Game 4: A,B,C,....
...
Set 2:
Game 1: B,C,A,B,....
Game 2: C,A,B,....
Game 3: A,B,C,A,...
...
There are exact rules for counting the number of balls/games/sets won by a player.

RULES FOR WINNING A GAME
The state of a game can be described by assigning a non-negative number of points to each of the players. At the beginning of a game, the score of each player is zero.

Note: In Earth terminology, 0 points is called "love", 1 point is a "fifteen", 2 points is a "thirty", 3 points is a "forty" and 4 points is an "advantage". Be glad that you don't have to learn the Centaurian terminology :)

When a player P just won a ball, the new score is determined by using the first rule from the list that applies to the situation.

If P currently has 3 points and no other player has more than 2 points, P wins the current game.
If P currently has 4 points, he wins the game.
If any other player currently has 4 points, that player loses one point. P gains a point.

RULES FOR WINNING A SET
The set is won by the first player that at the same time:

won at least 6 games in this set
won at least 2 games more than any other player

RULES FOR WINNING A MATCH
The winner is the first player to win at least three sets. A set in which no other player won a game counts as two won sets.

Problem specification
An observer from the Intergalactic Tennis Federation was watching a tournament in Alpha Centauri Tennis. Being unable to understand Alpha Centaurian language, he only managed to write down the winner of each ball. Now, for each match, knowing the sequence in which the players were winning the balls, he would like to somehow determine its winner.

Input

t - the number of test cases [t <= 150] than t test cases follows, each corresponding to one match. Each line contains the number of players N [N <= 10] and a string S consisting of uppercase letters [2 <= S <= 50000]. The players are represented by the first N letters of the English alphabet. If the i-th letter of S is X, it means the player X won the i-th ball from the beggining of the match. You may assume that the match transcripts are correct and complete.

The order in which the players serve is the same as the order of their letters in the English alphabet.

Output

For each line, output a single character, being the letter of the player who won the corresponding match.

Example

Input:
1
3 BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 

Output:
B

(B has won two sets, each of them by winning 6 games, while A and C won none. Thus each of these sets counts as two and B has won the match.)


Added by:Roman Sol
Date:2005-05-13
Time limit:1s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:IPSC 2005









SPOJ Problem Set (classical)

362. Ignore the Garbage

Problem code: IGARB

Fred works as an IT consultant in an insurance company. As they always had a large amount of customers waiting and arguing at the front desk, management decided to deploy a ticket machine. Each customer would get a ticket with a number and there will be fancy LCD display over each desk showing the number of the next person. Fred was appointed to get this new enhancement working.

Because Fred is lazy when it comes to manual labor and as an IT consultant he wouldn't lower himself to the level of some hardware technician (except when upgrading his own computer), he asked few technicians to install the displays and prepared himself just to plug in the ticket machine and try it out. Unfortunately (for Fred) the technicians, either inspired by Mr.Bean or because of their carelessness, installed the display upside-down.

Being a software guy, Fred decided that the hardware should not be tampered with after it is installed (except for the case if he would be able to get back the technicians to repair it, but they were already angry at him for his nagging). Then he noted that from time to time the display shows a correct number even when it is upside-down. And hey, the ticket machine is an embedded device and contains a small processor! It would be just a sin for an IT guy not to try to meddle with it and try running an own version of Linux. Now we just need to figure out which readable numbers will the display show.

Task specification

In the beginning the display shows the number 1 on its display. Each second the number shown is increased by 1. We see the display upside-down and thus not everything we see will make sense. Your task is to compute the K-th valid number we will see on the display. The digits the display uses are shown on the images below. An upside-down 1 still count as 1. The number we see may have leading zeroes – e.g. turning the number 600 upside down leads to a valid number.

                   

Input

t - the number of test cases [t <= 2200], than t test cses follows. Each test case consist of one integer Ki [0 < Ki <= 10^200].

Output

For each Ki from the input file, output the Ki-th number shown on the display (including the leading zeroes, if there are some).

Example

Input:
8
1
2
3
4
5
6
8
98
Output:
1
2
5
9
8
6
11
002

Added by:Roman Sol
Date:2005-05-15
Time limit:3s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:IPSC 2005









SPOJ Problem Set (classical)

364. Pocket Money

Problem code: LISA

Young people spend a lot of money on things like sweets, music CDs, mobile phones and so on. But most young girls/boys have one problem: Their pocket money is not enough for all these jolly things. Little Lisa Listig is one of these poor girls with a small pocket money budget. Last month her pocket money lasted only one week. So she decided to enter into negotiations with her father. Her father Tomm - a mathematician - had an incredibly ingenious idea: He wrote down some fancy digits with operators (+,*) in between them on a sheet of paper and allowed Lisa to insert brackets. Then he declared that the result of that arithmetic expression is Lisa's new pocket money. Now it's Lisa's task to maximize her pocket money. As her father was surprised what a huge sum of money Lisa got for her result, he decided to minimize the result of the expression for his son Manfred. Now it's your task to calculate the results obtained by Lisa and her father.

Input

The first line of input contains the number of testcases k ( k< 5000 ). Each of the following k lines consists of an arithemtic expression. This expression consists of numbers (0-9) seperated by one of the two operators '*' and '+'. There are no spaces between the characters. Each line contains less than 100 characters.

Output

For each expression output the result obtained by Lisa and the result obtained by her father separated by one space. The results of the calculations are smaller than 264.

Example

Input:
1
1+2*3+4*5

Output:
105 27

Two possible expressions for the first testcase:

105 = (1+2)*(3+4)*5
27  = 1+2*3+4*5

 


Added by:Simon Gog
Date:2005-05-17
Time limit:32s
Source limit:8082B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS
Resource:Ulm Algorithm Course SoSe 2005









SPOJ Problem Set (medium)

365. Phidias

Problem code: PHIDIAS

Famous ancient Greek sculptor Phidias is making preparations to build another marvelous monument. For this purpose he needs rectangular marble plates of sizes W1 x H1, W2 x H2, ..., WN x HN.

Recently, Phidias has received a large rectangular marble slab. He wants to cut the slab to obtain plates of the desired sizes. Any piece of marble (the slab or the plates cut from it) can be cut either horizontally or vertically into two rectangular plates with integral widths andheights, cutting completely through that piece. This is the only way to cut pieces and piecescannot be joined together. Since the marble has a pattern on it, the plates cannot be rotated: if Phidias cuts a plate of size A ? B then it cannot be used as a plate of size B ? A unless A = B. He can make zero or more plates of each desired size. A marble plate is wasted if it is not of any of the desired sizes after all cuts are completed. Phidias wonders how to cut the initial slab so that as little of it as possible will be wasted.

As an example, assume that in the figure below the width of the original slab is 21 and the height of the original slab is 11, and the desired plate sizes are 10 x 4, 6 x 2, 7 x 5, and 15 x 10. The minimum possible area wasted is 10, and the figure shows one sequence of cuts with total waste area of size 10.


Your task is to write a program that, given the size of the original slab and the desired plate sizes, calculates the minimum total area of the original slab that must be wasted.

Input

t - the number of test cases, then t test cases follow [t <= 20]. The first line of each test case contains two integers: first W, the width of the original slab, and then H, the height of the original slab. The second line contains one integer N: the number of desired plate sizes. The following N lines contain the desired plate sizes. Each of these lines contains two integers: first the width Wi and then the height Hi of that desired plate size (1 <= i <= N). [1 <= W <= 600, 1 <= H <= 600, 0 < N <= 200, 1 <= Wi <= W, and 1 <= Hi <= H.]

Output

For each test case output one line with a single integer: the minimum total area of the original slab that must be wasted.

Example

Input:
1
21 11
4
10 4
6 2
7 5
15 10

Output:
10


Added by:Roman Sol
Date:2005-05-20
Time limit:21s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ F# GO NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SED
Resource:IOI 2004









SPOJ Problem Set (classical)

366. Farmer

Problem code: FARMER

A farmer has a set of fields, each of which is surrounded by cypress trees. Also, the farmer has a set of strips of land, each of which has a row of cypress trees. In both fields and strips, between every two consecutive cypress trees is a single olive tree. All of the farmer’s cypress trees either surround a field or are in a strip and all of the farmer’s olive trees are between two consecutive cypress trees in a field or in a strip.

One day the farmer became very ill and he felt that he was going to die. A few days before he passed away he called his eldest son and told him, “I give you any Q cypress trees of your choice and all the olive trees which are between any two consecutive cypress trees you have chosen.” >From each field and from each strip the son can pick any combination of cypress trees. Since the eldest son loves olives he wants to pick the Q cypress trees which will allow him to inherit as many olive trees as possible.


In Figure 1, assume that the son is given Q=17 cypress trees. To maximize his olive inheritance he should choose all the cypress trees in Field 1 and Field 2, inheriting 17 olive trees.

You are to write a program which, given the information about the fields and the strips and the number of cypress trees the son can pick, determines the largest possible number of olive trees the son may inherit.

Input

t - the number of test cases [t <= 20], then t test cses follows. The first line of each test case contains first the integer Q: the number of cypress trees the son is to select; then the integer M, the number of fields; and then the integer K, the number of strips. The second line contains M integers N1, N2,… NM, : the numbers of cypress trees in fields. The third line contains K integers R1, R2,… RK: the numbers of cypress trees in strips.
In all test cases, 0 <= Q <= 150000, 0 <= M <= 2000, 0 <= K <= 2000, 3 <= N1 <= 150, 3 <= N2 <= 150,… 3 <= NM <=150, 2 <= R1 <= 150, 2 <= R2 <= 150,… 2 <= RK <= 150. The total number of cypress trees in the fields and strips is at least Q. Additionally, in 50% of the test cases, Q <= 1500.

Output

For each test case output ont integer: largest possible number of olive trees the son may inherit.

Example

Input:
1
17 3 3 
13 4 8 
4 8 6
Output:
17

Added by:Roman Sol
Date:2005-05-22
Time limit:50s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:IOI 2004









SPOJ Problem Set (classical)

367. Empodia

Problem code: EMPODIA

The ancient mathematician and philosopher Pythagoras believed that reality is mathematical in nature. Present-day biologists study properties of biosequences. A biosequence is a sequence of M integers, which
• contains each of the numbers 0,1,…,M-1,
• starts with 0 and ends with M-1, and
• has no two elements E,E+1 in adjacent positions in this order.
A subsequence consisting of adjacent elements of a biosequence is called a segment..

A segment of a biosequence is called a framed interval if it includes all integers whose values are between the value of the first element, which must be the smallest element in the segment, and the last element, which must be the largest and different from the first. A framed interval is called an empodio if it does not contain any shorter framed intervals.

As an example, consider the biosequence (0,3,5,4,6,2,1,7). The whole biosequence is a framed interval. However, it contains another framed interval (3,5,4,6) and therefore it is not an empodio. The framed interval (3,5,4,6) does not contain a shorter framed interval, so it is an empodio. Furthermore, it is the only empodio in that biosequence.

You are to write a program that, given a biosequence, finds all empodia (plural for empodio) in that biosequence.

Input

t - the number of test cases [t <= 20], then t test cses follows. The first line of each test case contains a single integer M: the number of integers in the input biosequence. The following M lines contain the integers of the biosequence in the order of the sequence. Each of these M lines contains a single integer. In one test case, 1000000 <= M <= 1100000. In all other test cases, 1 <= M <= 60000. Additionally, in 50% of the test cases, M <= 2600.

Output

The first line for each test case is to contain one integer H: the number of empodia in the input biosequence. The following H lines describe all empodia of the input biosequence in the order of appearance of the starting point in the biosequence. Each of these lines is to contain two integers A and B (in that order) separated by a space, where the Ath element of the input biosequence is the first element of the empodio and the Bth element of the input biosequence is the last element of the empodio.

Example

Input:
1
8 
0 
3 
5 
4 
6 
2 
1 
7
Output:
1
2 5

Added by:Roman Sol
Date:2005-05-22
Time limit:40s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:IOI 2004









SPOJ Problem Set (classical)

368. Cobbled streets

Problem code: CSTREET

The municipal chronicals of an unbelievable lordly major town in a land far, far away tell the following story:
Once upon a time the new crowned king Günther decided to visit all towns in his kingdom. The people of the unbelievable lordly major town expected that king Günther would like to see some of the most famous buildings in their town. For the lordly citizens it seemed neccessary that all streets in the town that the king would have to use had to be cobbled with stone. Unfortunately the unbelievable lordly major town had not much money at that time as they used most of their savings to erect the highest cathedral the world had ever seen.
Roumours were afloat that the real reason for their thriftiness was not that the town treasury was empty but that many people believed that king Günther came to the throne by deceiving his father king Erwin and that in his youth he made a pact with the devil. But anyway, the citizens of the unbelievable lordly major town decided to pave only as much streets as were absolutely necessary to reach every major building.
Can you help the citizens of the unbelievable lordly major town to find out which streets should be paved?
It might be usefull to know that all major buildings are either at the end of a street or at an intersection. In addition to that you can assume that all buildings are connected by the given streets.

Input

t [number of testcases (1 <= t <= 100)]
p [price to pave one furlong of street (positive integer)]
n [number of main buildings in the town (1 <= n <= 1000)]
m [number of streets in the town (1 <= m <= 300000)]
a b c [street from building a to building b with length c (lengths are given in furlong and the buildings are numbered from 1 to n)]

Output

For each testcase output the price of the cheapest possibility to reach all main buildings in the city on paved streets. You can assume that the result will be smaller than 2^32.

Example

Input:
1
2
5
7
1 2 1
2 3 2
2 4 6
5 2 1
5 1 3
4 5 2
3 4 3

Output:
12

Added by:Simon Gog
Date:2005-05-24
Time limit:15s
Source limit:32211B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS PERL 6
Resource:Ulm Algorithm Course SoSe 2005









SPOJ Problem Set (classical)

369. Math I

Problem code: MATH1


You are given n integers a1, a2,..., an (0<=ai<=n). The sum a1+ a2+...+ an does not exceeded n. Your task is to find n other integers x1, x2,..., xn (note that xi may be negative numbers) satisfying the following conditions:

Input

The first line of the input file contains an integer t representing the number of test cases (t<=20). Then t test cases follow. Each test case has the following form:

Output

For each test case output a single value: the minimum value of |x1|+|x2|+...+|xn|

Example

Input:
2
4
2 1 0 0
5
0 1 2 2 0

Output:
1
3

Output Details:
In the former case, the optimal solution is (x1=0, x2=0, x3=0, x4=-1)
In the latter case, the optimal solution is (x1=-1, x2=-1, x3=0, x4=1, x5=0)

Added by:Duc
Date:2005-05-25
Time limit:20s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

370. Ones and zeros

Problem code: ONEZERO

Certain positive integers have their decimal representation consisting only of ones and zeros, and having at least one digit one, e.g. 101. If a positive integer does not have such a property, one can try to multiply it by some positive integer to find out whether the product has this property.

Input

Number K of test cases (K is approximately 1000);
in each of the next K lines there is one integer n (1 <= n <= 20000)

Output

For each test case, your program should compute the smallest multiple of the number n consisting only of digits 1 and 0 (beginning with 1).

Example

Input:
3
17
11011
17
Output:
11101
11011
11101

Added by:Pawe³ Dobrzycki
Date:2005-05-26
Time limit:8s
Source limit:4096B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:II Polish Olympiad in Informatics, Ist Stage









SPOJ Problem Set (classical)

372. The Benefactor

Problem code: BENEFACT

Another chapter of the municipal chronicles of a well known unbelievable lordly major town (if this town is not well known to you, you might want to solve problem CSTREET first) tells us the following story:
Once upon a time the citizens of the unbelievable lordly major town decided to elect a major. At that time this was a very new idea and election campaigns were completely unknown. But of course several citizens wanted to become major and it didn't took long for them to find out, that promising nice things that never will become real tends to be useful in such a situation. One candidate to be elected as a major was Ivo sometimes called the benefactor because of his valuable gifts to the unbelievably lordly major towns citizens.
One day before the election day Ivo the benefactor made a promise to the citizens of the town. In case of his victory in the elections he would ensure that on one of the paved streets of the town street lamps would be erected and that he would pay that with his own money. As thrifty as the citizens of the unbelievable lordly major town were, they elected him and one day after the elections they presented him their decision which street should have street lamps. Of course they chose not only the longest of all streets but renamed several streets so that a very long street in the town existed.
Can you find how long this street was? To be more specific, the situation is as follows. You are presented a list of all paved streets in the unbelievable lordly major town. As you might remember from problem CSTREET in the town the streets are paved in a way that between every two points of interest in the town exactly one paved connection exists. Your task is to find the longest distance that exists between any two places of interest in the city.

Input

The first line of input contains the number of testcases t.
The first line of each testcase contains the number of places (2 <=n<=50000) in the town. Each street is given at one line by two places (1<=a,b<=n) and the length of the street (0<=l<20000).

Output

For each testcase output one line which contains the maximum length of the longest street in the city.

Example

Input:
1
6
1 2 3
2 3 4 
2 6 2
6 4 6
6 5 5

Output:

12

Added by:Simon Gog
Date:2005-06-06
Time limit:10s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS PERL 6
Resource:Ulm Algorithm Course SoSe 2005









SPOJ Problem Set (classical)

373. Greedy island

Problem code: GREED

Gon is on Greedy island. He wants to go home. But to get the ticket to leave the game, he has to get N cards labeled in a sequence from 1 to N (the order of the cards in his hand is irrelevant). He already has N cards, but not forming a sequence from 1 to N. So he wants you to help him. For some cards, he can change one card for another for one piece of gold. Help him to get the ticket at the minimum cost (using the minimum number of exchanges).

Input

The first line contains t, the number of tests (1<=t<=10). For each test case:

There is a blank line after each test case.

Output

For each test case, output a line denoting the minimum required cost.

Example

Input:
1
4
1
2
2
2
2
2 3
3 4

Output:
3

Added by:Le Trong Dao
Date:2005-06-08
Time limit:50s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Mr.Tran Minh Quan









SPOJ Problem Set (classical)

374. Count maximum matrices

Problem code: MATRIX

You are given a matrix A of M rows and N columns, consisting of numbers 0 and 1. For a rectangle in A (sides >= 1), X1 is the number of ones on its sides, X0 is the number of zeros on its sides, and its value is defined as X1 – X0. Let us consider W, the maximum value taken over submatrices of A, and S, the number of submatrices with value W. Your task is to find W and S.

Input

The first line of input contains the number of testcases t (t <= 15). The first line of each testcase contains the numbers M, N (1 <= M, N <= 200) Then M lines follow. In each line, there are N numbers 0 or 1.

Output

For each testcase, you should output a single line with numbers W and S.

Example

Input:
1
5 6
1 1 1 1 1 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

Output:
18 1

Added by:Lê Ðôn Khuê
Date:2005-06-08
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set ()

375. Query on a tree

Problem code: QTREE

You are given a tree (an acyclic undirected connected graph) with N nodes, and edges numbered 1, 2, 3...N-1.

We will ask you to perfrom some instructions of the following form:

Input

The first line of input contains an integer t, the number of test cases (t <= 20). t test cases follow.

For each test case:

There is one blank line between successive tests.

Output

For each "QUERY" operation, write one integer representing its result.

Example

Input:
1

3
1 2 1
2 3 2
QUERY 1 2
CHANGE 1 3
QUERY 1 2
DONE

Output:
1
3

Added by:Thanh-Vy Hua
Date:2005-06-08
Time limit:5s
Source limit:15000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









SPOJ Problem Set (classical)

376. A concrete simulation

Problem code: ACS

You are given a matrix M of type 1234x5678. It is initially filled with integers 1...1234x5678 in row major order. Your task is to process a list of commands manipulating M. There are 4 types of commands:
"R x y" swap the x-th and y-th row of M ;
"C x y" swap the x-th and y-th column of M ;
"Q x y" write out M(x,y) ;
"W z" write out x and y where z=M(x,y).

Input

A list of valid commands. Input terminated by EOF.

Output

For each "Q x y" write out one line with the current value of M(x,y), for each "W z" write out one line with the value of x and y ( interpreted as above ) separated by a space.

Input:
R 1 2
Q 1 1
Q 2 1
W 1
W 5679
C 1 2
Q 1 1
Q 2 1
W 1
W 5679

Output:
5679
1
2 1
1 1
5680
2
2 2
1 2

Added by:Noszály Csaba
Date:2005-06-10
Time limit:7s
Source limit:7777B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Folklore









SPOJ Problem Set (classical)

377. Taxi

Problem code: TAXI

Besides the well known unbelievable lordly major town's history there also current problems in this town. But to understand these problems you should know some facts from the unbelievable lordly major town's history.

Once upon a time the population of the unbelievable lordly major town grew so much that the citizens were in need of building new houses. As it was not allowed to erect houses outside the city wall they decided to found a new little town directly beside the main town. We will refer to this second town as the new unbelievable lordly major town. In the new unbelievable lordly major town all streets were built as straight lines intersecting at right angles at fixed distances (see picture below).

Road map

Knowing this we can leave the town's history and can focus on nowadays problems. One of these problems is directly connected to the "somnolent naggy festival" (SONAFE). Despite its name it's one of the town's most popular events and nearly everybody wants to get a ticket. To give everyone the same chance of getting one of the few tickets the place and time of the advance sale are kept secret until some minutes before the ticket counter opens. Once the opening of the ticket counter is disclosed (by radio to give everyone a fair chance) everyone interested in getting some tickets tries to get to the counter immediately.

One of the most profiting citizens of this ticket selling procedure is the new unbelievable lordly major town's taxi service owner. At the time of the radio announcement all over the town people ring up the taxi central and ask for a ride. The problem for the taxi central is that a lot of people ask for a ride at the same time and that the taxis have to pick up the people very quickly.

Your task is to help the taxi central finding out how many passengers can be transported to the ticket counter. You have to adhere to following constraints:

Input

The first line contains the number of testcases k (k<=250). The first line of each testcase contains the number of persons p (1<=p<=400), the number of taxicabs t (1<=t<=200) the speed s (1<=s<=2000) of the taxis in meters per seconds and the time c to collect a person in seconds (1<=c<=1000000). The next p lines contains the position of the persons. The next t lines contain the position of the taxicabs in the city.

Output

For each testcase output the maximal number of persons that visit the party.

Example

Input:
1
2 3 10 40
2 5
5 2
2 3
4 1
4 4

Output:
2

Added by:Simon Gog
Date:2005-06-20
Time limit:22s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Ulm Algorithm Course SoSe 2005









SPOJ Problem Set (classical)

379. Ambiguous Permutations

Problem code: PERMUT2

Some programming contest problems are really tricky: not only do they require a different output format from what you might have expected, but also the sample output does not show the difference. For an example, let us look at permutations.
A permutation of the integers 1 to n is an ordering of these integers. So the natural way to represent a permutation is to list the integers in this order. With n = 5, a permutation might look like 2, 3, 4, 5, 1.
However, there is another possibility of representing a permutation: You create a list of numbers where the i-th number is the position of the integer i in the permutation. Let us call this second possibility an inverse permutation. The inverse permutation for the sequence above is 5, 1, 2, 3, 4.
An ambiguous permutation is a permutation which cannot be distinguished from its inverse permutation. The permutation 1, 4, 3, 2 for example is ambiguous, because its inverse permutation is the same. To get rid of such annoying sample test cases, you have to write a program which detects if a given permutation is ambiguous or not.

Input Specification

The input contains several test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 100000). Then a permutation of the integers 1 to n follows in the next line. There is exactly one space character between consecutive integers. You can assume that every integer between 1 and n appears exactly once in the permutation.
The last test case is followed by a zero.

Output Specification

For each test case output whether the permutation is ambiguous or not. Adhere to the format shown in the sample output.

Sample Input

4
1 4 3 2
5
2 3 4 5 1
1
1
0

Sample Output

ambiguous
not ambiguous
ambiguous

Added by:Adrian Kuegel
Date:2005-06-24
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:own problem, used in University of Ulm Local Contest 2005









SPOJ Problem Set (classical)

380. Bullshit Bingo

Problem code: BINGO

Bullshit Bingo is a game to make lectures, seminars or meetings less boring. Every player has a card with 5 rows and 5 columns. Each of the 25 cells contains a word (the cell in the middle has always the word "BINGO" written in it). Whenever a player hears a word which is written on his card, he can mark it. The cell in the middle is already marked when the game starts. If a player has marked all the words in a row, a column or a diagonal, he stands up and shouts "BULLSHIT". After this, the game starts over again.

Sitting in a lecture, you observe that some students in the audience are playing Bullshit Bingo. You wonder what the average number of different words is until "BULLSHIT" is exclaimed. For the purpose of this problem, a word consists of letters of the English alphabet ('a' to 'z' or 'A' to 'Z'). Words are separated by characters other than letters (for example spaces, digits or punctuation). Do the comparison of words case-insensitively, i.e. "Bingo" is the same word as "bingo". When counting the number of different words, ignore the word BULLSHIT (indicating the end of the game), and consider only the words of the current game, i.e., if a word has already occurred in a previous game, you may still count it in the current game. If the last game is unfinished, ignore the words of that game.

Input Specification

The input file consists of the text of the lecture, with "BULLSHIT" occurring occasionally. The first game starts with the first word in the input. Each occurrence of "BULLSHIT" indicates the end of one game.
You may assume, that

Output Specification

The output consists of one number: the average number of different words needed to win a game. Write the number as a reduced fraction in the format shown below. Reduced fraction means that there should be no integer greater than 1 which divides both the numerator and denominator. For example if there were 10 games, and the number of different words in each game summed up to 55, print "11 / 2".

Sample Input

Programming languages can be classified BULLSHIT into following types:
- imperative and BULLSHIT procedural languages
- functional languages
- logical BULLSHIT programming languages
- object-oriented BULLSHIT languages

Sample Output

9 / 2

In the sample input, there are 4 completed games. The number of different words is 5, 5, 4 and 4, respectively.
Added by:Adrian Kuegel
Date:2005-06-24
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:University of Ulm Local Contest 2005









SPOJ Problem Set (classical)

381. 106 miles to Chicago

Problem code: CHICAGO

In the movie "Blues Brothers", the orphanage where Elwood and Jake were raised may be sold to the Board of Education if they do not pay 5000 dollars in taxes at the Cook County Assessor's Office in Chicago. After playing a gig in the Palace Hotel ballroom to earn these 5000 dollars, they have to find a way to Chicago. However, this is not so easy as it sounds, since they are chased by the Police, a country band and a group of Nazis. Moreover, it is 106 miles to Chicago, it is dark and they are wearing sunglasses.
As they are on a mission from God, you should help them find the safest way to Chicago. In this problem, the safest way is considered to be the route which maximises the probability that they are not caught.

Input Specification

The input file contains several test cases.
Each test case starts with two integers n and m (2 ≤ n ≤ 100 , 1 ≤ m ≤ n*(n-1)/2). n is the number of intersections, m is the number of streets to be considered.
The next m lines contain the description of the streets. Each street is described by a line containing 3 integers a, b and p (1 ≤ a, b ≤ n , a ≠ b, 1 ≤ p &le 100): a and b are the two end points of the street and p is the probability in percent that the Blues Brothers will manage to use this street without being caught. Each street can be used in both directions. You may assume that there is at most one street between two end points.
The last test case is followed by a zero.

Output Specification

For each test case, calculate the probability of the safest path from intersection 1 (the Palace Hotel) to intersection n (the Honorable Richard J. Daley Plaza in Chicago). You can assume that there is at least one path between intersection 1 and n.
Print the probability as a percentage with exactly 6 digits after the decimal point. The percentage value is considered correct if it differs by at most 10-6 from the judge output. Adhere to the format shown below and print one line for each test case.

Sample Input

5 7
5 2 100
3 5 80
2 3 70
2 1 50
3 4 90
4 1 85
3 1 70
0

Sample Output

61.200000 percent

The safest path for the sample input is 1 -> 4 -> 3 -> 5


Added by:Adrian Kuegel
Date:2005-06-24
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: PERL 6
Resource:University of Ulm Local Contest 2005









SPOJ Problem Set (classical)

382. Decorate the wall

Problem code: DECORATE

After building his huge villa, Mr. Rich cannot help but notice that the interior walls look rather blank. To change that, he starts to hang paintings from his wonderful collection. But soon he realizes that it becomes quite difficult to find a place on the wall where a painting can be placed without overlapping other paintings. Now he needs a program which would tell him, given the already placed paintings, where to place the next painting without moving any other paintings (or indicating that this is impossible). Paintings have a rectangular shape and are to be placed parallel to the side of the wall. If you do not mind a nice reward from Mr. Rich, go on and solve the problem.

Input Specification

The first line of the input file contains a number representing the number of test cases to follow. Each test case starts with a line containing three numbers n, w and h. n is the number of paintings already hanging on the wall, w is the width of the wall and h is the height of the wall.
The next n lines contain 4 integers x1, y1, x2, y2 each (0 ≤ x1 < x2 ≤ w, 0 ≤ y1 < y2 ≤ h); the x-coordinates give the distance to the left end of the wall, the y-coordinates give the distance to the bottom of the wall. (x1, y1) is the position of the lower left corner of a painting, (x2, y2) is the position of the upper right corner. The last line of each test case contains the dimensions of the next painting to be placed, first its width w', then its height h' (1 ≤ w' ≤ w, 1 ≤ h' ≤ h). You are not allowed to rotate the painting.
You can assume that 0 ≤ n ≤ 200 and 1 ≤ w, h ≤ 1000000. Moreover, all paintings already hanging do not overlap.

Output Specification

Produce one line of output for each test case. Write "Fail!" if there is no place left on the wall where the painting could be placed without overlapping other paintings. Otherwise, write the coordinates where the lower left corner of the painting should be placed. In case there is more than one solution, select the solution with a minimum y-coordinate, and break ties using the minimum x-coordinate.

Sample Input

2
1 10 9
5 4 10 9
9 5
2 10 10
5 5 10 10
0 0 4 3
3 4

Sample Output

Fail!
4 0
The following image illustrates the second sample test case:


Added by:Adrian Kuegel
Date:2005-06-24
Time limit:6s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:University of Ulm Local Contest 2005









SPOJ Problem Set (classical)

383. European railroad tracks

Problem code: EUROPEAN

As you may already know, different countries in Europe use different railroad systems. Not only do they use different voltages for their trains, but also the distance between the two rails (gauge) differs. The following table shows some railway gauges used:

Broad gauge (Spain): 1674 mm
Broad gauge (Portugal): 1665 mm
Broad gauge (Ireland): 1600 mm
Broad gauge (Finland): 1524 mm
Broad gauge (former USSR): 1520 mm
Standard gauge: 1435 mm
Narrow gauge (meter gauge): 1000 mm

A museum has trains from several countries. It needs tracks for every train type in order to show visitors the trains in use. However, since only one train is used at a time, a rail can be used by trains of different types. It follows that for n trains, each requiring a different railway gauge, n + 1 rails are sufficient (each train uses the leftmost rail and a rail that has exactly the required distance to it). But sometimes it is possible to save even more rails.

Given the required railway gauges, your task is to construct a railway track that can be used by every train and requires the least number of rails. Note that a train can use any two rails, provided the distance between them is right.

Input Specification

The first line of the input file contains a number representing the number of test cases to follow. Each test case starts with an integer n (the number of different railway gauges required). The next line contains n integers between 1000 and 5000, each defining one required railway gauge.
You can assume that 1 ≤ n ≤ 8. Moreover, for every test case in the input file, there will be a solution requiring at most 5 rails.

Output Specification

The output for each test case consists of three lines:
The first line is of the form "Scenario #X", where X is the test case number starting with 1. The second line describes the solution your program has found; first your program should print how many rails are needed, followed by a colon, then the positions of each rail in increasing order (the first rail should be at position 0). The third line should be blank. If there are several solutions with the minimum number of rails, any one will do.

Sample Input

3
4
1524 1520 1609 1435
3
1000 1520 1600
6
1000 2000 3000 4000 1500 2500

Sample Output

Scenario #1
4: 0 1520 1609 3044

Scenario #2
4: 0 1000 1520 1600

Scenario #3
5: 0 1500 3000 4000 5000


Added by:Adrian Kuegel
Date:2005-06-24
Time limit:1s-10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: PERL 6
Resource:University of Ulm Local Contest 2005









SPOJ Problem Set (classical)

384. Any fool can do it

Problem code: FOOL

Surely you know someone who thinks he is very clever. You decide to let him down with the following problem:

Now you got him! You present him with the following grammar, defining formally the syntax for a set (which was described informally by him):

Set          ::= "{" Elementlist "}"
Elementlist  ::= <empty> | List
List         ::= Element | Element "," List
Element      ::= Atom | Set
Atom         ::= "{" | "}" | ","

<empty> stands for the empty word, i.e. the list in a set can be empty.
Soon he realizes that this task is much harder than he has thought, since the alphabet consists of the characters which are also used for the syntax of the set. So he claims that it is not possible to decide efficiently if a word consisting of "{", "}" and "," is a syntactically correct representation of a set or not.
To disprove him, you need to write an efficient program that will decide this problem.

Input Specification

The first line of the input file contains a number representing the number of lines to follow.
Each line consists of a word, for which your program has to decide if it is a syntactically correct representation of a set. You may assume that each word consists of between 1 and 200 characters from the set { "{", "}", "," }.

Output Specification

Output for each test case whether the word is a set or not. Adhere to the format shown in the sample output.

Sample Input

4
{}
{{}}
{{}},{,}}
{,,}

Sample Output

Word #1: Set
Word #2: Set
Word #3: Set
Word #4: No Set

Added by:Adrian Kuegel
Date:2005-06-24
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:University of Ulm Local Contest 2005









SPOJ Problem Set (classical)

385. Game schedule required

Problem code: GAME

Sheikh Abdul really loves football. So you better don't ask how much money he has spent to make famous teams join the annual tournament. Of course, having spent so much money, he would like to see certain teams play each other. He worked out a complete list of games he would like to see. Now it is your task to distribute these games into rounds according to following rules:

As can be proved by induction, in such a tournament with n teams, there are exactly n - 1 games required until a winner is determined.
Obviously, after round 1, teams may already have been eliminated which should take part in another game. To prevent this, for each game you also have to tell which team should win.

Input Specification

The input file contains several test cases.
Each test case starts with an integer n (2 ≤ n ≤ 1000), the number of teams participating in the tournament. The following n lines contain the names of the teams participating in the tournament. You can assume that each team name consists of up to 25 letters of the English alphabet ('a' to 'z' or 'A' to 'Z').
Then follow n - 1 lines, describing the games the sheikh would like to see (in any order). Each line consists of the two names of the teams which take part in that game. You can assume that it is always possible to find a tournament schedule consisting of the given games.
The last test case is followed by a zero.

Output Specification

For each test case, write the game schedule, distributed in rounds.
For each round, first write "Round #X" (where X is the round number) in a line by itself. Then write the games scheduled in this round in the form: "A defeats B", where A is the name of the advancing team and B is the name of the team being eliminated. You may write the games of a round in any order. If a wildcard is needed for the round, write "A advances with wildcard" after the last game of the round, where A is the name of the team which gets the wildcard. After the last round, write the winner in the format shown below. Print a blank line after each test case.

Sample Input

3
A
B
C
A B
B C
5
A
B
C
D
E
A B
C D
A E
C E
0

Sample Output

Round #1
B defeats A
C advances with wildcard
Round #2
C defeats B
Winner: C

Round #1
A defeats B
C defeats D
E advances with wildcard
Round #2
E defeats A
C advances with wildcard
Round #3
E defeats C
Winner: E


Note that there is always more than one possible game schedule; you may print any of them.
Added by:Adrian Kuegel
Date:2005-06-24
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:own problem, used in University of Ulm Local Contest 2005









SPOJ Problem Set (classical)

386. Help the problem setter

Problem code: HELP

Preparing a problem for a programming contest takes a lot of time. Not only do you have to write the problem description and write a solution, but you also have to create difficult input files. In this problem, you get the chance to help the problem setter to create some input for a certain problem.
For this purpose, let us select the problem which was not solved during last year's local contest. The problem was about finding the optimal binary search tree, given the probabilities that certain nodes are accessed. Your job will be: given the desired optimal binary search tree, find some access probabilities for which this binary search tree is the unique optimal binary search tree. Don't worry if you have not read last year's problem, all required definitions are provided in the following.
Let us define a binary search tree inductively as follows:

Given such a binary search tree, the following search procedure can be used to locate a node in the tree:
Start with the root node. Compare the label of the current node with the desired label. If it is the same, you have found the right node. Otherwise, if the desired label is smaller, search in the left subtree, otherwise search in the right subtree.
The access cost to locate a node is the number of nodes you have to visit until you find the right node. An optimal binary search tree is a binary search tree with the minimum expected access cost.

Input Specification

The input file contains several test cases.
Each test case starts with an integer n (1 ≤ n ≤ 50), the number of nodes in the optimal binary search tree. For simplicity, the labels of the nodes will be integers from 1 to n. The following n lines describe the structure of the tree. The i-th line contains the labels of the roots of the left and right subtree of the node with label i (or -1 for an empty subtree). You can assume that the input always defines a valid binary search tree.
The last test case is followed by a zero.

Output Specification

For each test case, write one line containing the access frequency for each node in increasing order of the labels of the nodes. To avoid problems with floating point precision, the frequencies should be written as integers, meaning the access probability for a node will be the frequency divided by the sum of all frequencies. Make sure that you do not write any integer bigger than 263 - 1 (the maximum value fitting in the C/C++ data type long long or the Java data type long). Otherwise, you may produce any solution ensuring that there is exactly one optimal binary search tree: the binary search tree given in the input.

Sample Input

3
-1 -1
1 3
-1 -1
10
-1 2
-1 3
-1 4
-1 5
-1 6
-1 7
-1 8
-1 9
-1 10
-1 -1
0

Sample Output

1 1 1
512 256 128 64 32 16 8 4 2 1

Note that the first test case in the sample input describes a tree looking like
  2  
 / \ 
1   3

Added by:Adrian Kuegel
Date:2005-06-24
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:own problem, used in University of Ulm Local Contest 2005









SPOJ Problem Set (classical)

387. Travelling tours

Problem code: TOURS

In Hanoi, there are N beauty-spots (2 <= N <= 200), connected by M one-way streets. The length of each street does not exceed 10000. You are the director of a travel agency, and you want to create some tours around the city which satisfy the following conditions:

Input

The first line of input contains the number of testcases t (t <= 15). The first line of each testcase contains the numbers N, M. The next M lines contain three integers U V W which mean that there is one street from U to V of length W.

Output

For each test case you shold output the minimal total length of all tours.

Example

Input:
2
6 9
1 2 5
2 3 5
3 1 10
3 4 12
4 1 8
4 6 11
5 4 7
5 6 9
6 5 4
5 8
1 2 4
2 1 7
1 3 10
3 2 10
3 4 10
4 5 10
5 3 10
5 4 3

Output:
42
40

Detailed explanation:
Test 1:
  Tour #1:  1 - 2 - 3 - 1  --> Length = 20
  Tour #2:  6 - 5 - 4 - 6  --> Length = 22

Test 2:
  Tour #1:  1 - 3 - 2 - 1  --> Length = 27
  Tour #2:  5 - 4 - 5      --> Length = 13


Added by:Lê Ðôn Khuê
Date:2005-06-25
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:2nd round VOI 2004









SPOJ Problem Set (classical)

388. Menu

Problem code: MENU

Alfred wants to plan what to cook in the next days. He can cook various dishes. For each dish the costs of the ingredients and the benefit value is known. If a dish is cooked the second time in a row, the benefit value for the second time is 50 percent of the benefit value of first time, if it is prepared for the third or higher time in a row, the benefit value is 0. For example cooking a dish with benefit value v three times in a row leads to a total benefit value of 1.5*v.
Help him to build the menu which maximizes the benefit value under the constraint that his budget is not exceeded.

Input

The input consists of several test cases. Each test case begins with 3 integers in a line: The number of days k (1 ≤ k ≤ 21) Alfred wants to plan for, the number of dishes n (1 ≤ n ≤ 50) he can cook and his budget m (0 ≤ m ≤ 100). The following n lines describe the dishes Alfred can cook. The i-th line contains two integers: the costs c (1 ≤ c ≤ 50) and the benefit value v (1 ≤ v ≤ 10000) of the i-th dish.
The end of the input is signaled by a test case with k = n = m = 0. You don't need to process this test case.

Output

For each output, print the maximum benefit value reachable with 1 digit after the decimal point. Then print k integers with i-th integer being the number of the dish to cook on day i. Dishes are numbered from 1 to n. Print at least one space or new line character after each integer.
If there are several possible menus reaching the maximum benefit value, select the one with minimum costs, if there are several with minimum costs, you can print any of them.
If every menu exceeds the budget, print only the benefit value of 0.

Example

Input:
2 1 5
3 5
3 5 20
2 5
18 6
1 1
3 3
2 3
0 0 0

Output:
0.0

13.0
1 5 1 

Added by:Adrian Kuegel
Date:2005-07-04
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:own problem









SPOJ Problem Set (classical)

389. Use of Hospital Facilities

Problem code: HOSPITAL


County General Hospital is trying to chart its course through the troubled waters of the economy and shifting population demographics. To support the planning requirements of the hospital, you have been asked to develop a simulation program that will allow the hospital to evaluate alternative configurations of operating rooms, recovery rooms and operations guidelines. Your program will monitor the usage of operating rooms and recovery room beds during the course of one day.

County General Hospital has several operating rooms and recovery room beds. Each surgery patient is assigned to an available operating room and following surgery the patient is assigned to one of the recovery room beds. The amount of time necessary to transport a patient from an operating room to a recovery room is fixed and independent of the patient. Similarly, both the amount of time to prepare an operating room for the next patient and the amount of time to prepare a recovery room bed for a new patient are fixed.

All patients are officially scheduled for surgery at the same time, but the order in which they actually go into the operating rooms depends on the order of the patient roster. A patient entering surgery goes into the lowest numbered operating room available. For example, if rooms 2 and 4 become available simultaneously, the next patient on the roster not yet in surgery goes into room 2 and the next after that goes into room 4 at the same time. After surgery, a patient is taken to the available recovery room bed with the lowest number. A recovery room bed is only available if the preparation is already finished when the patient leaves surgery. If two patients emerge from surgery at the same time, the patient with the lower surgery room number will be the first assigned to a recovery room bed.

Input

The input file contains data for several simulation runs. Each run is separated by a blank line. All numeric data in the input file are integers, and successive integers on the same line are separated by blanks. The first line of each run is the set of hospital configuration parameters to be used for this run. The parameters are, in order:

This initial configuration data will be followed by pairs of lines of patient data as follows:

Patient records in the input file are ordered according to the patient roster, which determines the order in which patients are scheduled for surgery. The number of recovery room beds specified in any configuration will be sufficient to handle patients arriving from surgery (No queuing of patients for recovery room beds will be required). Computed times will not extend past 24:00.

Output

Correct output shows which operating room and which recovery room bed is used by each patient, and the time period that the patient uses the room and bed along with a summary of the utilization of hospital facilities for that day. The output file consists of several sets of two tables each describing the results of the simulation run. The first table is in columnar form with appropriate column labels to show the number of each patient (in the order the patient roster), the patient's last name, the operating room number, the time surgery begins and ends, the recovery bed number and the time the patient enters and leaves the recovery room bed.

The second table will also be in columnar form with appropriate column labels summarizing the utilization of operating rooms and recovery room beds. This summary indicates the facility type (room or bed), the facility number, the number of minutes used and percentage of available time utilized. Available time is defined as the time in minutes from the starting time for 1st surgery of day to the ending time of the last patient in a recovery room bed. Print a blank line after each run. Follow the output format shown on sample output.

Example

Input:

5 12 07 5 15 10 16
Jones
28 140
Smith
120 200
Thompson
23 75
Albright
19 82
Poucher
133 209
Comer
74 101
Perry
93 188
Page
111 223
Roggio
69 122
Brigham
42 79
Nute
22 71
Young
38 140
Bush
26 121
Cates
120 248
Johnson
86 181
White
92 140

Output:

 Patient          Operating Room          Recovery Room
 #  Name     Room#  Begin   End      Bed#  Begin    End
 ------------------------------------------------------
 1  Jones      1    7:00    7:28      3    7:33    9:53
 2  Smith      2    7:00    9:00      1    9:05   12:25
 3  Thompson   3    7:00    7:23      2    7:28    8:43
 4  Albright   4    7:00    7:19      1    7:24    8:46
 5  Poucher    5    7:00    9:13      5    9:18   12:47
 6  Comer      4    7:34    8:48      4    8:53   10:34
 7  Perry      3    7:38    9:11      2    9:16   12:24
 8  Page       1    7:43    9:34      6    9:39   13:22
 9  Roggio     4    9:03   10:12      9   10:17   12:19
10  Brigham    2    9:15    9:57      8   10:02   11:21
11  Nute       3    9:26    9:48      7    9:53   11:04
12  Young      5    9:28   10:06      3   10:11   12:31
13  Bush       1    9:49   10:15     10   10:20   12:21
14  Cates      3   10:03   12:03      8   12:08   16:16
15  Johnson    2   10:12   11:38      4   11:43   14:44
16  White      5   10:21   11:53      7   11:58   14:18

Facility Utilization
Type  # Minutes  % Used
-------------------------
Room  1     165   29.68
Room  2     248   44.60
Room  3     258   46.40
Room  4     162   29.14
Room  5     263   47.30
Bed   1     282   50.72
Bed   2     263   47.30
Bed   3     280   50.36
Bed   4     282   50.72
Bed   5     209   37.59
Bed   6     223   40.11
Bed   7     211   37.95
Bed   8     327   58.81
Bed   9     122   21.94
Bed  10     121   21.76
Bed  11       0    0.00
Bed  12       0    0.00


Added by:Adrian Kuegel
Date:2005-07-04
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM ICPC World Finals 1991









SPOJ Problem Set (classical)

390. Billiard

Problem code: BILLIARD

In a billiard table with horizontal side a inches and vertical side b inches, a ball is launched from the middle of the table. After s > 0 seconds the ball returns to the point from which it was launched, after having made m bounces off the vertical sides and n bounces off the horizontal sides of the table. Find the launching angle A (measured from the horizontal), which will be between 0 and 90 degrees inclusive, and the initial velocity of the ball.

Assume that the collisions with a side are elastic (no energy loss), and thus the velocity component of the ball parallel to each side remains unchanged. Also, assume the ball has a radius of zero. Remember that, unlike pool tables, billiard tables have no pockets.

Input

Input consists of a sequence of lines, each containing five nonnegative integers separated by whitespace. The five numbers are: a, b, s, m, and n, respectively. All numbers are positive integers not greater than 10000.

Input is terminated by a line containing five zeroes.

Output

For each input line except the last, output a line containing two real numbers (accurate to two decimal places) separated by a single space. The first number is the measure of the angle A in degrees and the second is the velocity of the ball measured in inches per second, according to the description above.

Example

Input:

100 100 1 1 1
200 100 5 3 4
201 132 48 1900 156
0 0 0 0 0

Output:

45.00 141.42
33.69 144.22
3.09 7967.81

Added by:Adrian Kuegel
Date:2005-07-04
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:University of Waterloo Local Contest (Spring 1999)









SPOJ Problem Set (classical)

391. Railroads

Problem code: RAILROAD


It's Friday evening and Jill hates two things which are common to all trains:

  1. They are always late.
  2. The schedule is always wrong.

Nevertheless, tomorrow in the early morning hours Jill will have to travel from Hamburg to Darmstadt in order to get to the regional programming contest. Since she is afraid of arriving too late and being excluded from the contest she is looking for the train which gets her to Darmstadt as early as possible. However, she dislikes to get to the station too early, so if there are several schedules with the same arrival time then she will choose the one with the latest departure time.

Jill asks you to help her with her problem. You are given a set of railroad schedules from which you must compute the train with the earliest arrival time and the fastest connection from one location to another. One good thing: Jill is very experienced in changing trains. She can do this instantaneously, i.e., in zero time!!!

Input

The very first line of the input gives the number of scenarios. Each scenario consists of three parts.

Part one lists the names of all cities connected by the railroads. It starts with a number 1 < C ≤ 100, followed by C lines containing city names. These names consist of letters.

Part two describes all the trains running during a day. It starts with a number T ≤ 1000 followed by T train descriptions. Each of them consists of one line with a number ti ≤ 100 and ti more lines with a time and a city name, meaning that passengers can get on or off the train at that time at that city.

Part three consists of three lines: Line one contains the earliest journey's starting time, line two the name of the city where she starts, and line three the destination city. The two cities are always different.

Output

For each scenario print a line containing "Scenario i", where i is the number of the scenario starting at 1.

If a connection exists then print the two lines containing zero padded timestamps and locations as shown in the sample. Use blanks to achieve the indentation. If no connection exists on the same day (i.e., arrival before midnight) then print a line containing "No connection".

After each scenario print a blank line.

Example

Input:

2
3
Hamburg
Frankfurt
Darmstadt
3
2
0949 Hamburg
1006 Frankfurt
2
1325 Hamburg
1550 Darmstadt
2
1205 Frankfurt
1411 Darmstadt
0800
Hamburg
Darmstadt
2
Paris
Tokyo
1
2
0100 Paris
2300 Tokyo
0800
Paris
Tokyo

Output:

Scenario 1
Departure 0949 Hamburg
Arrival   1411 Darmstadt

Scenario 2
No connection


Added by:Adrian Kuegel
Date:2005-07-04
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Southwestern European Regional Contest 2000









SPOJ Problem Set (classical)

392. Spin

Problem code: SPIN


tex2html_wrap62 tex2html_wrap64

A disk can be rotated between horizontal and vertical only if it is positioned over the indentation marked `0' and the disk on its right is vertical . The right-most disk can always rotate if it is in position `0' since it has no disk on its right.

The aim is to free the slide by moving it so its left edge aligns with the `Win' mark:

Your task is to write a program which will take several part-solved puzzles and compute the number of steps needed to move the slide to position `Win' for each puzzle.

Input

There will be several puzzles in the input file. The first line of the file will contain an integer n specifying the number of puzzles. There will then be n lines, each of the form:

length orientations position

where length(length < 30) is an integer indicating the number of disks on the slide, orientations is a string of length characters from the set {h,v} giving the orientation of each disk from left to right (h stands for horizontal, and v for vertical), and position is an integer from 0 to length specifying the numbered mark which aligns with the left edge of the slide.

Output

For each puzzle, your program should output one integer on a line which counts the minimum number of steps needed to win the puzzle. A step is either a movement of the slide, one unit left or right, or the rotation of a disk.

Example

Input:

3
2 vv 2
7 vhhhvhh 4
29 vvvvvvvvvvvvvvvvvvvvvvvvvvvvv 29

Output:

7
357
1073741823

Added by:Adrian Kuegel
Date:2005-07-04
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Northwestern European Regional Contest 1993 (UVA problem 279)









SPOJ Problem Set ()

393. Hexagon

Problem code: HEXAGON

Consider a game board consisting of 19 hexagonal fields, as shown in the figure below. We can easily distinguish three main directions in the shape of the board: from top to bottom, from top-left to bottom-right, and from top-right to bottom-left. For each of these primary directions, the board can be viewed as a series of rows, consisting of 3, 4, 5, 4, and 3 fields, respectively.

The game board has to be completely covered using a set of hexagonal pieces. Each piece carries three numbers, one for every primary board direction. Only three different numbers are used for each direction. Every possible combination of three numbers for all three directions is assigned to a piece, leading to a set of 27 unique pieces. (The board in the above figure is still in the process of being covered.)

The score of a board is calculated as the sum of all 15 row scores (5 rows for each primary direction). The row scores are calculated as follows: if all pieces in a row carry the same number for the direction of the row, the row score is this number multiplied by the number of pieces in the row. Otherwise (the pieces carry different numbers in the row direction) the row score is zero. Note that the pieces may not be rotated. For example, the score of the leftmost row in the figure is 3 . 3 = 9, the score of the row to its right is 4 . 11 = 44.

While in the real game the pieces are chosen randomly and the set of pieces is fixed, we are interested in the highest possible score for a given set of numbers for each direction, when all pieces in a row carry the same number for the direction of the row. This means you have to choose those 19 pieces that result in the highest score under the constraint that each row has a score greater than zero.

Input

 

The first line of the input file contains an integer n which indicates the number of test cases. Each test case consists of three lines containing three different positive integers each. Each of these three lines contains the numbers for a single primary direction. From these numbers the set of pieces is generated.

Output

For each test case output a line containing the number of the case ("Test #1", "Test #2", etc.), followed by a line containing the highest possible score for the given numbers. Add a blank line after each test case.

Example

Input:

1
9 4 3
8 5 2
7 6 1

Output:

Test #1
308


Added by:Adrian Kuegel
Date:2005-07-04
Time limit:40s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Southwestern European Regional Contest 1996









SPOJ Problem Set (classical)

394. Alphacode

Problem code: ACODE

Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages:

Alice: “Let’s just use a very simple code: We’ll assign ‘A’ the code word 1, ‘B’ will be 2, and so on down to ‘Z’ being assigned 26.”

Bob: “That’s a stupid code, Alice. Suppose I send you the word ‘BEAN’ encoded as 25114. You could decode that in many different ways!”

Alice: “Sure you could, but what words would you get? Other than ‘BEAN’, you’d get ‘BEAAD’, ‘YAAD’, ‘YAN’, ‘YKD’ and ‘BEKD’. I think you would be able to figure out the correct decoding. And why would you send me the word ‘BEAN’ anyway?”

Bob: “OK, maybe that’s a bad example, but I bet you that if you got a string of length 5000 there would be tons of different decodings and with that many you would find at least two different ones that would make sense.”

Alice: “How many different decodings?”

Bob: “Jillions!”

For some reason, Alice is still unconvinced by Bob’s argument, so she requires a program that will determine how many decodings there can be for a given string using her code.

Input

Input will consist of multiple input sets. Each set will consist of a single line of at most 5000 digits representing a valid encryption (for example, no line will begin with a 0). There will be no spaces between the digits. An input line of ‘0’ will terminate the input and should not be processed.

Output

For each input set, output the number of possible decodings for the input string. All answers will be within the range of a 64 bit signed integer.

Example

Input:

25114
1111111111
3333333333
0

Output:

6
89
1

Added by:Adrian Kuegel
Date:2005-07-09
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM East Central North America Regional Programming Contest 2004









SPOJ Problem Set ()

395. Anti-prime Sequences

Problem code: APRIME

Given a sequence of consecutive integers n, n+1, n+2,..., m, an anti-prime sequence is a rearrangement of these integers so that each adjacent pair of integers sums to a composite (non-prime) number. For example, if n = 1 and m = 10, one such anti-prime sequence is 1, 3, 5, 4, 2, 6, 9, 7, 8, 10. This is also the lexicographically first such sequence.

We can extend the definition by defining a degree d anti-prime sequence as one where all consecutive subsequences of length 2, 3,..., d sum to a composite number. The sequence above is a degree 2 anti-prime sequence, but not a degree 3, since the subsequence 5, 4, 2 sums to 11. The lexicographically first degree 3 anti-prime sequence for these numbers is 1, 3, 5, 4, 6, 2, 10, 8, 7, 9.

Input

Input will consist of multiple input sets. Each set will consist of three integers, n, m, and d on a single line. The values of n, m and d will satisfy 1 ≤ n < m ≤ 1000, and 2 ≤ d ≤ 10. The line 0 0 0 will indicate end of input and should not be processed.

Output

For each input set, output a single line consisting of a comma-separated list of integers forming a degree d anti-prime sequence (do not insert any spaces and do not split the output over multiple lines). In the case where more than one anti-prime sequence exists, print the lexicographically first one (i.e., output the one with the lowest first value; in case of a tie, the lowest second value, etc.). In the case where no anti-prime sequence exists, output:

No anti-prime sequence exists.

Example

Input:

1 10 2
1 10 3
1 10 5
40 60 7
0 0 0

Output:

1,3,5,4,2,6,9,7,8,10
1,3,5,4,6,2,10,8,7,9
No anti-prime sequence exists.
40,41,43,42,44,46,45,47,48,50,55,53,52,60,56,49,51,59,58,57,54

Added by:Adrian Kuegel
Date:2005-07-09
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM East Central North America Regional Programming Contest 2004









SPOJ Problem Set (classical)

396. Hit or Miss

Problem code: HITOMISS

One very simple type of solitaire game known as “Hit or Miss” (also known as “Frustration,” “Harvest,” “Roll-Call,” “Talkative”, and “Treize”) is played as follows: take a standard deck of 52 playing cards — four sets of cards numbered 1 through 13 (suits do not matter in this game) which have been shuffled — and start counting through the deck 1, 2, 3, . . . , and so on. When your count reaches 13, start over at 1. Each time you count, look at the top card of the deck and do one of two things: if the number you count matches the value of the top card, discard it from the deck; if it does not match it, move that card to the bottom of the deck. You win the game if you are able to remove all cards from the deck (which may take a very long time).

A version of this game can be devised for two or more players. The first player starts as before with a 52 card deck, while the other players have no cards initially. As the first player removes cards from her deck, she gives them to the second player, who then starts playing the same game, starting at count 1. When that player gets a match, he passes his card to the third player, and so on. The last player discards matches rather than passing them to player 1. All players who have cards to play with perform the following 2-step cycle of moves in lockstep:

1. Each player says his or her current count value and checks for a match. If there is no match, the top card is moved to the bottom of the deck; otherwise it is passed to the next player (or discarded if this is the last player).

2. Each player except the first takes a passed card (if there is one) and places it at the bottom of his or her deck.

These rules are repeated over and over until either the game is won (all the cards are discarded by the last player) or an unwinnable position is reached. If any player ever runs out of cards, he waits until he is passed a card and resumes his count from where he left off (e.g., if player 3 passes his last card on a count of 7, he waits until he receives a card from player 2 and resumes his count with 8 at the beginning of the next 2-step cycle).

Input

Input will consist of multiple input sets. The first line of the file will contain a single positive integer n indicating the number of input sets in the file. Each input set will be a single line containing 53 integers: the first integer will indicate the number of players in the game and the remaining 52 values will be the initial layout of the cards in the deck, topmost card first. These values will all lie in the range 1 . . . 13, and the number of players will lie in the range 1 . . . 10.

Output

For each input set, output the input set number (as shown below, starting with 1) and either the phrase “unwinnable” or a list showing the last card discarded by each player. Use a single blank to separate all outputs.

Example

Input: (note that the line break is only in the sample input for displaying purposes)

2
4 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 13
  1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 13
4 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 13 1
  2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 13 1

Output:

Case 1: 13 13 13 13
Case 2: unwinnable

Added by:Adrian Kuegel
Date:2005-07-09
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM East Central North America Regional Programming Contest 2004









SPOJ Problem Set ()

397. I Conduit

Problem code: CONDUIT

Irv Kenneth Diggit works for a company that excavates trenches, digs holes and generally tears up people’s yards. Irv’s job is to make sure that no underground pipe or cable is underneath where excavation is planned. He has several different maps, one for each utility company, showing where their conduits lie, and he needs to draw one large, consolidated map combining them all. One approach would be to simply draw each of the smaller maps one at a time onto the large map. However, this often wastes time, not to mention ink for the pen-plotter in the office, since in many cases portions of the conduits overlap with each other (albeit at different depths underground). What Irv wants is a way to determine the minimum number of line segments to draw given all the line segments from the separate maps.

Input

Input will consist of multiple input sets. Each set will start with a single line containing a positive integer n indicating the total number of line segments from all the smaller maps. Each of the next n lines will contain a description of one segment in the format

x1 y1 x2 y2

where (x1,y1) are the coordinates of one endpoint and (x2,y2) are the coordinates of the other. Coordinate values are floating point values in the range 0 ...1001 specified to at most two decimal places. The maximum number of line segments will be 10000 and all segments will have non-zero length. Following the last input set there will be a line containing a 0 indicating end of input; it should not be processed.

Output

For each input set, output on a single line the minimum number of line segments that need to be drawn on the larger, consolidated map.

Example

Input:

3
1.0 10.0 3.0 14.0
0.0 0.0 20.0 20.0
10.0 28.0 2.0 12.0
2
0.0 0.0 1.0 1.0
1.0 1.0 2.15 2.15
2
0.0 0.0 1.0 1.0
1.0 1.0 2.15 2.16
0

Output:

2
1
2

Added by:Adrian Kuegel
Date:2005-07-09
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM East Central North America Regional Programming Contest 2004









SPOJ Problem Set ()

398. Roll Playing Games

Problem code: RPGAMES

Phil Kropotnik is a game maker, and one common problem he runs into is determining the set of dice to use in a game. In many current games, non-traditional dice are often required, that is, dice with more or fewer sides than the traditional 6-sided cube. Typically, Phil will pick random values for all but the last die, then try to determine specific values to put on the last die so that certain sums can be rolled with certain probabilities (actually, instead of dealing with probabilities, Phil just deals with the total number of different ways a given sum can be obtained by rolling all the dice). Currently he makes this determination by hand, but needless to say he would love to see this process automated. That is your task.

For example, suppose Phil starts with a 4-sided die with face values 1, 10, 15, and 20 and he wishes to determine how to label a 5-sided die so that there are a) 3 ways to obtain a sum of 2, b) 1 way to obtain a sum of 3, c) 3 ways to obtain 11, d) 4 ways to obtain 16, and e)1 way to obtain 26. To get these results he should label the faces of his 5-sided die with the values 1, 1, 1, 2, and 6. (For instance, the sum 16 may be obtained as 10 +6 or as 15 +1, with three different “1” faces to choose from on the second die, for a total of 4 different ways.) Note that he sometimes only cares about a subset of the sums reachable by rolling all the dices (like in the previous example).

Input

Input will consist of multiple input sets. Each input set will start with a single line containing an integer n indicating the number of dice that are already specified. Each of the next n lines describes one of these dice. Each of these lines will start with an integer f (indicating the number of faces on the die) followed by f integers indicating the value of each face. The last line of each problem instance will have the form

r m v1 c1 v2 c2 v3 c3 ··· vm cm

where r is the number of faces required on the unspecified die, m is the number of sums of interest, v1,...,vsm are these sums, and c1,...,cm are the counts of the desired number of different ways in which to achieve each of the respective sums.

Input values will satisfy the following constraints: 1 ≤ n ≤ 20, 3 ≤ f ≤ 20, 1 ≤ m ≤ 10, and 1 ≤ r ≤ 6. Values on the faces of all dice, both the specified ones and the unknown die, will be integers in the range 1 ...50, and values for the vi’s and ci’s are all non-negative and are strictly less than the maximum value of a 32-bit signed integer.

The last input set is followed by a line containing a single 0; it should not be processed.

Output

For each input set, output a single line containing either the phrase “Final die face values are” followed by the r face values in non-descending order, or the phrase “Impossible” if no die can be found meeting the specifications of the problem. If there are multiple dice which will solve the problem, choose the one whose lowest face value is the smallest; if there is still a tie, choose the one whose second-lowest face value is smallest, etc.

Example

Input:

1
4 1 10 15 20
5 5 2 3 3 1 11 3 16 4 26 1
1
6 1 2 3 4 5 6
6 3 7 6 2 1 13 1
4
6 1 2 3 4 5 6
4 1 2 2 3
3 3 7 9
8 1 4 5 9 23 24 30 38
4 4 48 57 51 37 56 31 63 11
0

Output:

Final die face values are 1 1 1 2 6
Impossible
Final die face values are 3 7 9 9

Added by:Adrian Kuegel
Date:2005-07-09
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM East Central North America Regional Programming Contest 2004









SPOJ Problem Set (classical)

399. Team Rankings

Problem code: TRANK


It’s preseason and the local newspaper wants to publish a preseason ranking of the teams in the local amateur basketball league. The teams are the Ants, the Buckets, the Cats, the Dribblers, and the Elephants. When Scoop McGee, sports editor of the paper, gets the rankings from the selected local experts down at the hardware store, he’s dismayed to find that there doesn’t appear to be total agreement and so he’s wondering what ranking to publish that would most accurately re ect the rankings he got from the experts. He’s found that finding the median ranking from among all possible rankings is one way to go.

The median ranking is computed as follows: Given any two rankings, for instance ACDBE and ABCDE, the distance between the two rankings is defined as the total number of pairs of teams that are given different relative orderings. In our example, the pair B, C is given a different ordering by the two rankings. (The first ranking has C above B while the second ranking has the opposite.) The only other pair that the two rankings disagree on is B, D; thus, the distance between these two rankings is 2. The median ranking of a set of rankings is that ranking whose sum of distances to all the given rankings is minimal. (Note we could have more than one median ranking.) The median ranking may or may not be one of the given rankings.

Suppose there are 4 voters that have given the rankings: ABDCE, BACDE, ABCED and ACBDE. Consider two candidate median rankings ABCDE and CDEAB. The sum of distances from the ranking ABCDE to the four voted rankings is 1 + 1 + 1 + 1 = 4. We’ll call this sum the value of the ranking ABCDE. The value of the ranking CDEAB is 7 + 7+ 7 + 5 = 26. It turns out that ABCDE is in fact the median ranking with a value of 4.

Input

There will be multiple input sets. Input for each set is a positive integer n on a line by itself, followed by n lines (n no more than 100), each containing a permutation of the letters A, B, C, D and E, left-justified with no spaces. The final input set is followed by a line containing a 0, indicating end of input.

Output

Output for each input set should be one line of the form:

ranking is the median ranking with value value.

Of course ranking should be replaced by the correct ranking and value with the correct value. If there is more than one median ranking, you should output the one which comes first alphabetically.

Example

Input:

4
ABDCE
BACDE
ABCED
ACBDE
0

Output:

ABCDE is the median ranking with value 4.

Added by:Adrian Kuegel
Date:2005-07-09
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM East Central North America Regional Programming Contest 2004









SPOJ Problem Set (classical)

400. To and Fro

Problem code: TOANDFRO

Mo and Larry have devised a way of encrypting messages. They first decide secretly on the number of columns and write the message (letters only) down the columns, padding with extra random letters so as to make a rectangular array of letters. For example, if the message is “There’s no place like home on a snowy night” and there are five columns, Mo would write down

t o i o y
h p k n n
e l e a i
r a h s g
e c o n h
s e m o t
n l e w x

Note that Mo includes only letters and writes them all in lower case. In this example, Mo used the character ‘x’ to pad the message out to make a rectangle, although he could have used any letter. Mo then sends the message to Larry by writing the letters in each row, alternating left-to-right and right-to-left. So, the above would be encrypted as

toioynnkpheleaigshareconhtomesnlewx

Your job is to recover for Larry the original message (along with any extra padding letters) from the encrypted one.

Input

There will be multiple input sets. Input for each set will consist of two lines. The first line will contain an integer in the range 2...20 indicating the number of columns used. The next line is a string of up to 200 lower case letters. The last input set is followed by a line containing a single 0, indicating end of input.

Output

Each input set should generate one line of output, giving the original plaintext message, with no spaces.

Example

Input:

5
toioynnkpheleaigshareconhtomesnlewx
3
ttyohhieneesiaabss
0

Output:

theresnoplacelikehomeonasnowynightx
thisistheeasyoneab

Added by:Adrian Kuegel
Date:2005-07-09
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource: ACM East Central North America Regional Programming Contest 2004









SPOJ Problem Set (classical)

401. Translations

Problem code: TRANSL


Bob Roberts is in charge of performing translations of documents between various languages. To aid him in this endeavor his bosses have provided him with translation files. These files come in twos — one containing sample phrases in one of the languages and the other containing their translations into the other language. However, some over-zealous underling, attempting to curry favor with the higher-ups with his initiative, decided to alphabetically sort the contents of all of the files, losing the connections between the phrases and their translations. Fortunately, the lists are comprehensive enough that the original translations can be reconstructed from these sorted lists. Bob has found this is most usually the case when the phrases all consist of two words. For example, given the following two lists:

Language 1 Phrases Language 2 Phrases
arlo zym bus seat
flub pleve bus stop
pleve dourm hot seat
pleve zym school bus

Bob is able to determine that arlo means hot, zym means seat, ub means school, pleve means bus, and dourm means stop. After doing several of these reconstructions by hand, Bob has decided to automate the process. And if Bob can do it, then so can you.

Input

Input will consist of multiple input sets. Each input set starts with a positive integer n, n ≤ 250, indicating the number of two-word phrases in each language. This is followed by 2n lines, each containing one two-word phrase: the first n lines are an alphabetical list of phrases in the first language, and the remaining n lines are an alphabetical list of their translations into the second language. Only upper and lower case alphabetic characters are used in the words. No input set will involve more than 25 distinct words. No word appears as the first word in more than 10 phrases for any given language; likewise, no word appears as the last word in more than 10 phrases. A line containing a single 0 follows the last problem instance, indicating end of input.

Output

For each input set, output lines of the form

word1/word2

where word1 is a word in the first language and word2 is the translation of word1 into the second language, and a slash separates the two. The output lines should be sorted according to the first language words, and every first language word should occur exactly once. There should be no white space in the output, apart from a single blank line separating the outputs from different input sets. Imitate the format of the sample output, below. There is guaranteed to be a unique correct translation corresponding to each input instance.

Example

Input:

4
arlo zym
flub pleve
pleve dourm
pleve zym
bus seat
bus stop
hot seat
school bus
2
iv otas
otas re
ec t
eg ec
0

Output:

arlo/hot
dourm/stop
flub/school
pleve/bus
zym/seat

iv/eg
otas/ec
re/t

Added by:Adrian Kuegel
Date:2005-07-09
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource: ACM East Central North America Regional Programming Contest 2004









SPOJ Problem Set (classical)

402. Hike on a Graph

Problem code: HIKE

"Hike on a Graph" is a game that is played on a board on which an undirected graph is drawn. The graph is complete and has all loops, i.e. for any two locations there is exactly one arrow between them. The arrows are coloured. There are three players, and each of them has a piece. At the beginning of the game, the three pieces are in fixed locations on the graph. In turn, the players may do a move. A move consists of moving one's own piece along an arrow to a new location on the board. The following constraint is imposed on this: the piece may only be moved along arrows of the same colour as the arrow between the two opponents' pieces.

In the sixties ("make love not war") a one-person variant of the game emerged. In this variant one person moves all the three pieces, not necessarily one after the other, but of course only one at a time. Goal of this game is to get all pieces onto the same location, using as few moves as possible. Find out the smallest number of moves that is necessary to get all three pieces onto the same location, for a given board layout and starting positions.

Input

The input file contains several test cases. Each test case starts with the number n. Input is terminated by n=0. Otherwise, 1<=n<=50. Then follow three integers p1, p2, p3 with 1<=pi<=n denoting the starting locations of the game pieces. The colours of the arrows are given next as a n×n matrix m of whitespace-separated lower-case letters. The element mij denotes the colour of the arrow between the locations i and j. Since the graph is undirected, you can assume the matrix to be symmetrical.

Output

For each test case output on a single line the minimum number of moves required to get all three pieces onto the same location, or the word "impossible" if that is not possible for the given board and starting locations.

Example

Input:

3 1 2 3
r b r
b b b
r b r
2 1 2 2
y g
g y
0

Output:

2
impossible

Added by:Adrian Kuegel
Date:2005-07-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:University of Ulm Local Contest 2000









SPOJ Problem Set (classical)

403. Sort fractions

Problem code: FRACTION

You are given a positive integer N. Let us consider set A of fractions x/y where 0 <= x/y <= 1, y <= N and the maximum common divisor of x and y is 1.

For example N = 5. Set A in increasing order consists of elements 0/1; 1/5; 1/4; 1/3; 2/5; 1/2; 3/5; 2/3; 3/4; 4/5; 1/1.

Your task is to find the i-th smallest fraction in set A.

Input

The first line of input contains the number of testcases t (t <= 15). The first line of each testcase contains numbers N and M (N <= 5000, M <= 10000). The next M lines contain one question each.

Output

For each testcase, you should output M lines which are the answers to the M questions.

Example

Input:
1
5 4
1
3
5
8

Output:
0/1
1/4
2/5
2/3

Added by:Lê Ðôn Khuê
Date:2005-07-12
Time limit:2s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Mr Nguyen Duc Thinh









SPOJ Problem Set ()

404. Scanner

Problem code: SCANNER

A body scanner works by scanning a succession of horizontal slices through the body; the slices are imaged one at a time. The image slices can be reassembled to form a three dimensional model of the object. Write a program to construct a two dimensional image slice using data captured during the scan.

epsfbox{p229.eps}

The scanner consists of four arrays of sensors arranged around a 10×15 matrix. Array 1 consists of 10 sensors pointing to the right, array 2 has 24 sensors pointing diagonally to the top right, array 3 has 15 sensors pointing to the top and array 4 has 24 sensors pointing to the top left. Each sensor records the thickness of that portion of the object directly in front of that sensor.

Readings from the arrays of sensors are recorded in counterclockwise order. Within an array of sensors, data are also recorded counterclockwise. A complete scan consists of 73 readings.

Input

The input file begins with a line with an integer indicating the number of image slices to follow. For each image slice, there are separate lines with 10, 24, 15, and 24 integers representing sensor data from sensor arrays 1 through 4 respectively. The order of the readings is indicated in the diagram. You can assume that there exist at least one image for the given sensor data.

Output

For each slice, your program should print 10 lines of 15 cells. To indicate that the cell represents a part of the object, print a hash character (#) for the cell; to indicate that the cell is not a part of the object, print a period (.). Between successive output image slices, print a blank line.

It is possible for the result of a scan to be ambiguous, in that case you can print any solution.

Example

Input:

1
10 10 6 4 6 8 13 15 11 6
0 1 2 2 2 2 4 5 5 6 7 6 5 6 6 5 5 6 6 3 2 2 1 0
2 4 5 5 7 6 7 10 10 10 7 3 3 5 5
0 0 1 3 4 4 4 4 3 4 5 7 8 8 9 9 6 4 4 2 0 0 0 0

Output:

.##########....
.##########....
....######.....
......####.....
.......####..##
.......########
#####..########
###############
..#########..##
....######.....

Added by:Adrian Kuegel
Date:2005-07-26
Time limit:42s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM ICPC World Finals 1993









SPOJ Problem Set ()

405. Tin Cutter

Problem code: TCUTTER

In a Tin Cutting factory there is a machine for cutting parts from tin plates. It has an extraordinarily sharp knife able to make horizontal or vertical segment cuts in the tin plates. Each cutting process consists of a sequence of such cuts. Each segment cut is given by its endpoints that are always located inside the tin plate. During the cutting process some parts of tin plate can fall out and so some holes in the plate can emerge.

Factory management needs to predict the number of holes in the plate at the end of the given sequence of cuts. Write a program that answers this question. Single segment cuts are not considered to be holes.

Here there are examples of some situations that can arise after cutting:

two holes two holes one hole one hole

Input

The input file consists of blocks of lines. Each block except the last describes one cutting process. In the first line of the block there is a number tex2html_wrap_inline33 indicating the number of segment cuts in the cutting process. These cuts are defined by the following N lines. The line defining one segment cut has the form tex2html_wrap_inline37 where tex2html_wrap_inline39 and tex2html_wrap_inline41 are the co-ordinates of the end points of the segment cut. They are separated by one space. The co-ordinates are integers and always define horizontal or vertical segment (i.e. segment parallel with x or y axis).

The last block consists of just one line containing 0.

Output

The output file contains the lines corresponding to the blocks in the input file. Each such line contains the number of holes that remain in the tin plate after the execution of the corresponding cuts.

There is no line in the output file corresponding to the last "null" block of the input file.

Example

Input:

4
0 1 1 1
1 1 1 0
1 0 0 0
0 0 0 1
2
0 1 2 1
1 2 1 0
0

Output:

1
0

Added by:Adrian Kuegel
Date:2005-07-26
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Central European Regional Contest 1996









SPOJ Problem Set ()

406. Logic

Problem code: LOGIC

Consider a 10x10 grid. Cells in this grid can contain one of five logic operations (AND, OR, NOT, Input, Output). These can be joined together to form a logic circuit. Given a description of a circuit and a set of boolean values, build the logic circuit and execute the input stream against it.

Input

The first line of the input contains a single integer n, which specifies the number of circuits to be processed. There will then be n groups of circuit descriptions and test values.

A circuit is made up of a number of operations. Each line describing an operation begins with three characters: the co-ordinates for a cell, 0-9 on the X-axis then 0-9 on the Y-axis, followed by a single character to represent the operation of that cell (`&' for AND, `|' for OR, `!' for NOT, `i' for Input and `o' for Output). Optionally following each triple is a set of co-ordinate pairs which represent the x and y co-ordinates of cells that take the output of this cells operation as an input for theirs. This (possibly empty) output list is terminated by `..'. The list of operations is terminated by a line containing the word `end'.

Next, for each circuit, comes the set of test values. The first line contains an integer t which gives the number of test cases your program must run. Next, there are t lines, each line containing a sequence of `0' and `1' characters symbolising the input values for one test case. The number of inputs will always correspond to the number of inputs defined by the circuit description. The input values are to be applied to the inputs in the order in which the input operations were defined in the circuit description.

The next circuit description, if any, will then follow.

Output

For each circuit, your program should output one line for each test case given in the input. The line should contain one `0' or `1' character for each output defined by the circuit description in the order in which the outputs were defined.

Your program should output a blank line after each set of test cases.

Example

Input:

1
00i 11 13 ..
02i 11 13 ..
11& 21 ..
21o ..
13| 23 ..
23o ..
end
4
00
01
10
11

Output:

00
01
01
11

Notes:

Hint: Sample input specifies a circuit consiting of an `AND' and an `OR' operation in parallel both fed from the same two inputs:

               +---------\
3              |          |OR #----------OUT(2)
               |     +---/
               |     |
2     IN(2)----+     |
               |     |
               +---------\
1                    |    |AND#----------OUT(1)
                     +---/
                     |
0      IN(1)---------+

         0                 1              2

In grid terms this is two inputs at 0,0 and 1,0. The first input feeds the AND operation at 1,1 and the OR operation at 1,3. The second input operation feeds the second input for the same AND and OR operations. The AND operation then feeds an output operation at 2,1. The OR operation also feeds an output operation, this one at 2,3.


Added by:Adrian Kuegel
Date:2005-07-26
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Northwestern European Regional Contest 1993









SPOJ Problem Set ()

407. Random Number

Problem code: RNUMBER

A Black Box algorithm supposes that natural number sequence $u(1), u(2), dots, u(N)$ is sorted in non-descending order, $N le M$ and for each p ( $1 le p le N$) an inequality $p le u(p) le M$ is valid.


Making tests for this algorithm we have met with the following problem. For setting a random sequence ${u(i)}$ a usual random data generator did not fit. As the sequence itself had been imposed certain restrictions, the method of choosing the next random element (in the interval defined by restrictions) did not give the random sequence as a whole.


We have come to a conclusion that the problem can be solved in the following way. If we arrange all possible sequences in certain order (for example, in lexicographical order) and assign each sequence its number, after choice of the random number it is possible to take the correspondent sequence for the random one. At the first glance it seems enough to make up a program generating all these sequences in such order. Alas! Even having not great values of M and N it would have taken any powerful modern computer centuries to enumerate all such sequences. It turned out it was possible to avoid generating all sequences if we managed to create required sequence according to its number immediately. But even this statement does not cover all. As the amount of sequences is quite large, the number can be a long one, composed of hundreds decimal digits, though our random data generator could give only normal numbers. We decided to produce a long random number from a real random number distributed in [0,1]. Namely, present the number in binary notation: $0.b(1)b(2)dots$, where all b(i) = 0 or 1. Let us set a regulation to associate such real number to an integer from [A,B] segment:

Formula


begin{displaymath}G(A,B,0.b_1b_2dots b_p) = left{ begin{array}{ll}
A, & m...
...p, & mbox{if $b_1=1$} end{array} right.
end{array} right.
end{displaymath}

Here we suppose, that $A le B$, $p ge 0$, and ``div 2" is an integer division by 2.


Let M, N ( $1 le N le M le 200$) and a binary real number $0.b(1)b(2)dots b(p)$ ( $1 le p le 400$) be given. Write a program to find out the corresponding $u(1), u(2), dots, u(N)$ sequence, i.e. to find a sequence with $G(1, T, 0.b(1)b(2)dots b(p))$ number in lexicographical order of all possible ${u(i)}$ for the given M and N (T is the quantity of such sequences). Numeration begins with 1. Keep in mind that in lexicographical order ${l(i)}$ proceeds ${h(i)}$ if after omitting equal beginnings, the first number of ${l(i)}$ tail is smaller than the first number or ${h(i)}$ tail. Following example illustrates the list of all possible sequences for M = 4 and N = 3 in lexicographical order.

A note (it does not concern the solution of this task):

The choice of random binary vector $0.b(1)b(2)dots b(p)$ does not give an absolute uniform random data generator if we use the Formula. However, taking into account the fact that [A,B] interval is big we shall obtain a distribution applicable in most cases.

Example

1, 2, 3
1, 2, 4
1, 3, 3
1, 3, 4
1, 4, 4
2, 2, 3
2, 2, 4
2, 3, 3
2, 3, 4
2, 4, 4
3, 3, 3
3, 3, 4
3, 4, 4
4, 4, 4

(here T=14)

Input

The first line of the input is an integer K ≤ 10, followed by K datasets.

The first line of each dataset contains M and N. The second line contains binary real number $0.b(1)b(2)dots b(p)$ (without leading, trailing and other spaces).

Output

For each dataset, write into the output data file the corresponding sequence $u(1), u(2), dots, u(N)$. The sequence numbers should be separated with spaces and end-of-line characters. There should be up to 20 numbers in each line. If neccesary, the numbers will have leading blanks to occupy 3 characters.

Example

Input:

1
4 3
0.01101101011110010001101010001011010

Output:

  2   2   4

Added by:Adrian Kuegel
Date:2005-07-26
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Northeastern European Regional Contest 1996









SPOJ Problem Set (classical)

408. Jill Rides Again

Problem code: JRIDE

Jill likes to ride her bicycle, but since the pretty city of Greenhills where she lives has grown, Jill often uses the excellent public bus system for part of her journey. She has a folding bicycle which she carries with her when she uses the bus for the first part of her trip. When the bus reaches some pleasant part of the city, Jill gets off and rides her bicycle. She follows the bus route until she reaches her destination or she comes to a part of the city she does not like. In the latter event she will board the bus to finish her trip.


Through years of experience, Jill has rated each road on an integer scale of niceness. Positive niceness values indicate roads Jill likes; negative values are used for roads she does not like. There are not zero values. Jill plans where to leave the bus and start bicycling, as well as where to stop bicycling and re-join the bus, so that the sum of niceness values of the roads she bicycles on is maximized. This means that she will sometimes cycle along a road she does not like, provided that it joins up two other parts of her journey involving roads she likes enough to compensate. It may be that no part of the route is suitable for cycling so that Jill takes the bus for its entire route. Conversely, it may be that the whole route is so nice Jill will not use the bus at all.


Since there are many different bus routes, each with several stops at which Jill could leave or enter the bus, she feels that a computer program could help her identify the best part to cycle for each bus route.

Input

The input file contains information on several bus routes. The first line of the file is a single integer b representing the number of route descriptions in the file. The identifier for each route (r) is the sequence number within the data file, 1 ≤ r ≤ b. Each route description begins with the number of stops on the route: an integer s, 2 ≤ s ≤ 100000 on a line by itself. The number of stops is followed by s - 1 lines, each line i (1 ≤ i < s) is an integer ni with absolute value ≤ 1000 representing Jill's assessment of the niceness of the road between the two stops i and i+1.

Output

For each route in the input file, your program should identify the beginning bus stop i and the ending bus stop j that identify the segment of the route which yields the maximal sum of niceness, m= ni+ni+1+...+nj-1. If more than one segment is maximally nice, choose the one with the longest cycle ride (largest j-i). To break ties in longest maximal segments, choose the segment that begins with the earliest stop (lowest i). For each route r in the input file, print a line in the form:


The nicest part of route r is between stops i and j


However, if the maximal sum is not positive, your program should print:


Route r has no nice parts

Example

Input:

3
3
-1
6
10
4
-5
4
-3
4
4
-4
4
-5
4
-2
-3
-4

Output:

The nicest part of route 1 is between stops 2 and 3
The nicest part of route 2 is between stops 3 and 9
Route 3 has no nice parts

Added by:Adrian Kuegel
Date:2005-07-27
Time limit:4s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM ICPC World Finals 1997









SPOJ Problem Set ()

409. DEL Command

Problem code: DELCOMM

It is required to find out whether it is possible to delete given files from MS-DOS directory executing the DEL command of MS-DOS operation system only once. There are no nested subdirectories.

A note

DEL command has the following format: DEL wildcard


The actual wildcard as well as a full file name can be made up either of a name containing 1 up to 8 characters or of a name and extension, containing up to 3 characters. The point character '.' separates the extension from the file name. The extension can be empty and this is equivalent to a name without any extension (in this case a wildcard ends with a point). In a wildcard the characters '?' and '*' can be used. A question mark substitutes exactly one character of the full file name excluding a point, an asterisk any sequence of characters (containing no points) even empty one. An asterisk can appear only at the last position of the name and the extension.


MS-DOS system can permit maybe other wildcards but they can not be used in this task. File names and extensions consist only of Latin capitals and digits.

Input

The first line of the input is an integer M, then a blank line followed by M datasets. There is a blank line between datasets.

Input data for each dataset contains a list of full file names without empty lines and spaces. Each name is written in a separate line of input data file and preceded with a control sign: '-' for delete or '+' for keep. Full file names are not repeated. The list comprises at least one file, and at least one file is marked to be deleted. There are no more than 1000 files.

Output

For each dataset, write to the first line of output the required DEL command (only one proposal) or IMPOSSIBLE if there is no solution. A space should separate "DEL" from wildcard. Print a blank line between datasets.

Example

Input:

1

-BP.EXE
-BPC.EXE
+TURBO.EXE

Output:

DEL ?P*.*

Added by:Adrian Kuegel
Date:2005-07-27
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Northeastern European Regional Contest 1996









SPOJ Problem Set (classical)

410. Variable Radix Huffman Encoding

Problem code: VHUFFM

Huffman encoding is a method of developing an optimal encoding of the symbols in a source alphabet using symbols from a target alphabet when the frequencies of each of the symbols in the source alphabet are known. Optimal means the average length of an encoded message will be minimized. In this problem you are to determine an encoding of the first N uppercase letters (the source alphabet, tex2html_wrap_inline87 through tex2html_wrap_inline89 , with frequencies tex2html_wrap_inline91 through tex2html_wrap_inline93 ) into the first R decimal digits (the target alphabet, tex2html_wrap_inline97 through tex2html_wrap_inline99 ).

Consider determining the encoding when R=2. Encoding proceeds in several passes. In each pass the two source symbols with the lowest frequencies, say tex2html_wrap_inline87 and tex2html_wrap_inline105 , are grouped to form a new ``combination letter" whose frequency is the sum of tex2html_wrap_inline91 and tex2html_wrap_inline109 . If there is a tie for the lowest or second lowest frequency, the letter occurring earlier in the alphabet is selected. After some number of passes only two letters remain to be combined. The letters combined in each pass are assigned one of the symbols from the target alphabet.

The letter with the lower frequency is assigned the code 0, and the other letter is assigned the code 1. (If each letter in a combined group has the same frequency, then 0 is assigned to the one earliest in the alphabet. For the purpose of comparisons, the value of a ``combination letter" is the value of the earliest letter in the combination.) The final code sequence for a source symbol is formed by concatenating the target alphabet symbols assigned as each combination letter using the source symbol is formed.

The target symbols are concatenated in the reverse order that they are assigned so that the first symbol in the final code sequence is the last target symbol assigned to a combination letter.

The two illustrations below demonstrate the process for R=2.

tabular23

When R is larger than 2, R symbols are grouped in each pass. Since each pass effectively replaces R letters or combination letters by 1 combination letter, and the last pass must combine R letters or combination letters, the source alphabet must contain k*(R-1)+R letters, for some integer k.

Since N may not be this large, an appropriate number of fictitious letters with zero frequencies must be included. These fictitious letters are not to be included in the output. In making comparisons, the fictitious letters are later than any of the letters in the alphabet.

Now the basic process of determining the Huffman encoding is the same as for the R=2 case. In each pass, the R letters with the lowest frequencies are grouped, forming a new combination letter with a frequency equal to the sum of the letters included in the group. The letters that were grouped are assigned the target alphabet symbols 0 through R-1. 0 is assigned to the letter in the combination with the lowest frequency, 1 to the next lowest frequency, and so forth. If several of the letters in the group have the same frequency, the one earliest in the alphabet is assigned the smaller target symbol, and so forth.

The illustration below demonstrates the process for R=3.

tabular63

Input

The input will contain one or more data sets, one per line. Each data set consists of an integer value for R (between 2 and 10), an integer value for N (between 2 and 26), and the integer frequencies tex2html_wrap_inline91 through tex2html_wrap_inline93 , each of which is between 1 and 999.

The end of data for the entire input is the number 0 for R; it is not considered to be a separate data set.

Output

For each data set, display its number (numbering is sequential starting with 1) and the average target symbol length (rounded to two decimal places) on one line. Then display the N letters of the source alphabet and the corresponding Huffman codes, one letter and code per line.
Print a blank line after each test case.
The examples below illustrate the required output format.

Example

Input:

2 5 5 10 20 25 40
2 5 4 2 2 1 1
3 7 20 5 8 5 12 6 9
4 6 10 23 18 25 9 12
0

Output:

Set 1; average length 2.10
    A: 1100
    B: 1101
    C: 111
    D: 10
    E: 0

Set 2; average length 2.20
    A: 11
    B: 00
    C: 01
    D: 100
    E: 101

Set 3; average length 1.69
    A: 1
    B: 00
    C: 20
    D: 01
    E: 22
    F: 02
    G: 21

Set 4; average length 1.32
    A: 32
    B: 1
    C: 0
    D: 2
    E: 31
    F: 33

Added by:Adrian Kuegel
Date:2005-07-27
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM ICPC World Finals 1995









SPOJ Problem Set (classical)

411. Number of quite different words

Problem code: NUMQDW

Let's consider the alphabet consisting of the first c roman uppercase letters, i.e. {A, B, C, D, E, F} if c is 6.
We will call two words quite different, if there is no common subsequence of length more than one between those two words. For example ABC and CBA are quite different, but ABBA and CADDCAD aren't, because AA is a subsequence of both words.
Given a word w you are to find the number of words of length n that are quite different from w.

Input

The first line will contain the number of test cases (at most 20). Then there will be pairs of lines, the first one containing the numbers n (n will fit into a 32-bit signed integer and will be non-negative) and c (1 <= c <= 6), the second one the word w. w will only consist of the first c letters of the roman alphabet and will have at most 10000 characters.

Output

Print one line for each test case, consisting only of the number of words that are quite different from w. As this number can be quite large, you just have to output its remainder when dividing by 4242.

Example

Input:
3
3 3
ABC
4 4
CADDCAD
100 3
A

Output:
10
13
2223


Added by:Robin Nittka
Date:2005-08-04
Time limit:20s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:self-invented









SPOJ Problem Set (classical)

412. K-path cover

Problem code: COVER


Problem

K-path cover of a directed graph is a set of exactly k of its edges chosen in such way that every two of them have different start vertices and every two of them have different end vertices. Assuming that for each vertex we know its cost we can define cost of the edge as a sum of costs of its start and end. We can also define cost of a k-path cover as a sum of costs of its edges. Your task is to find cheapest k-path cover for given directed graph with known costs of the vertices.


A graph and its cheapest 4-path cover.

Input

First line of input contains number of test cases c (1<=c<=20). Each test case begins with k, number of vertices n and number of edges m (1<=k<=100, 1<=n<=10000, 0<=m<=1000000). Next n lines contain costs of the vertices, each of them is an integer from [-100000,100000]. Then m lines describing edges follow, each of them containing exactly two numbers representing its start and end vertices. Vertices are numbered from 1 to n.

Output

For each test case output cost of the cheapest k-path cover. When given graph has no k-path cover output NONE.

Example

Input:
1
4 6 9
5
4
6
10
2
3
1 2
1 4
2 4
3 2
4 3
5 4
6 3
5 6
6 5

Output:
33

Added by:Pawel Gawrychowski
Date:2005-08-08
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ONTAK 05









SPOJ Problem Set (classical)

413. Word Puzzles

Problem code: WPUZZLES

Word puzzles are usually simple and very entertaining for all ages. They are so entertaining that Pizza-Hut company started using table covers with word puzzles printed on them, possibly with the intent to minimise their client's perception of any possible delay in bringing them their order.

Even though word puzzles may be entertaining to solve by hand, they may become boring when they get very large. Computers do not yet get bored in solving tasks, therefore we thought you could devise a program to speedup (hopefully!) solution finding in such puzzles.

The following figure illustrates the PizzaHut puzzle. The names of the pizzas to be found in the puzzle are: MARGARITA, ALEMA, BARBECUE, TROPICAL, SUPREMA, LOUISIANA, CHEESEHAM, EUROPA, HAVAIANA, CAMPONESA.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 Q W S P I L A A T I R A G R A M Y K E I
1 A G T R C L Q A X L P O I J L F V B U Q
2 T Q T K A Z X V M R W A L E M A P K C W
3 L I E A C N K A Z X K P O T P I Z C E O
4 F G K L S T C B T R O P I C A L B L B C
5 J E W H J E E W S M L P O E K O R O R A
6 L U P Q W R N J O A A G J K M U S J A E
7 K R Q E I O L O A O Q P R T V I L C B Z
8 Q O P U C A J S P P O U T M T S L P S F
9 L P O U Y T R F G M M L K I U I S X S W
10 W A H C P O I Y T G A K L M N A H B V A
11 E I A K H P L B G S M C L O G N G J M L
12 L D T I K E N V C S W Q A Z U A O E A L
13 H O P L P G E J K M N U T I I O R M N C
14 L O I U F T G S Q A C A X M O P B E I O
15 Q O A S D H O P E P N B U Y U Y O B X B
16 I O N I A E L O J H S W A S M O U T R K
17 H P O I Y T J P L N A Q W D R I B I T G
18 L P O I N U Y M R T E M P T M L M N B O
19 P A F C O P L H A V A I A N A L B P F S

Problem

Your task is to produce a program that given the word puzzle and words to be found in the puzzle, determines, for each word, the position of the first letter and its orientation in the puzzle.

You can assume that the left upper corner of the puzzle is the origin, (0,0). Furthemore, the orientation of the word is marked clockwise starting with letter A for north (note: there are 8 possible directions in total).

Input

The first line of the input contains a number T ≤ 10 which indicates the number of test cases to follow. Each test case starts with a line consisting of three positive numbers: The number of lines of the word puzzle, 0 < L ≤ 1000, the number of columns, 0 < C ≤ 1000, and the number of words to be found, 0 < W ≤ 1000. The following L input lines, each consisting of C uppercase letters, contain the word puzzle. Then at last the W words are input one per line. You can assume that each word can be found exactly once in the word puzzle.

Output

For each test case your program should output W lines: For each word (using the same order as the words were input) print a triplet defining the coordinates, line and column, where the first letter of the word appears, followed by a letter indicating the orientation of the word according to the rules defined above. Each value in the triplet must be separated by one space only.
Print one blank line between test cases.

Example

Input:

1
20 20 10
QWSPILAATIRAGRAMYKEI
AGTRCLQAXLPOIJLFVBUQ
TQTKAZXVMRWALEMAPKCW
LIEACNKAZXKPOTPIZCEO
FGKLSTCBTROPICALBLBC
JEWHJEEWSMLPOEKORORA
LUPQWRNJOAAGJKMUSJAE
KRQEIOLOAOQPRTVILCBZ
QOPUCAJSPPOUTMTSLPSF
LPOUYTRFGMMLKIUISXSW
WAHCPOIYTGAKLMNAHBVA
EIAKHPLBGSMCLOGNGJML
LDTIKENVCSWQAZUAOEAL
HOPLPGEJKMNUTIIORMNC
LOIUFTGSQACAXMOPBEIO
QOASDHOPEPNBUYUYOBXB
IONIAELOJHSWASMOUTRK
HPOIYTJPLNAQWDRIBITG
LPOINUYMRTEMPTMLMNBO
PAFCOPLHAVAIANALBPFS
MARGARITA
ALEMA
BARBECUE
TROPICAL
SUPREMA
LOUISIANA
CHEESEHAM
EUROPA
HAVAIANA
CAMPONESA

Output:

0 15 G
2 11 C
7 18 A
4 8 C
16 13 B
4 15 E
10 3 D
5 1 E
19 7 C
11 11 H

Added by:Adrian Kuegel
Date:2005-08-10
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:ACM Southwestern European Regional Contest 2002









SPOJ Problem Set (classical)

414. Equatorial Bonfire

Problem code: BONFIRE

Some great ideas are never implemented. This was the case with the equatorial bonfire planned for the millenial celebration. Maybe the plan will be rediscovered for the next turn of millenia. Before it is completely forgotten we will tell you about it: The idea was to put tarred logs and gun powder contiguously along the equator and then ignite bonfires at various points of this gun powder belt at various times. The fire would spread in both directions along the equator and in the end, the whole equator would burn.

One concern of the architects of this celebration was what would be the last place to catch fire and when would it happen?

Input

The input file consists of at most 10 blocks, each specifying a separate proposal for the equatorial bonfire. The first line of each block specifies the speed of fire's advance in the degrees of longitude per hour. The next line contains the number of bonfires N ≤ 5000 along the equator. Each of the next N lines contains two numbers specifying the time and the location of a bonfire.

The time is given in hours from 12:00am GMT (all times are positive), the location is given in the degrees of longitude (greater than -180 and less than or equal to 180). All numbers except N are given with precision of at most 2 decimal places. Every block is followed by an empty line. The last block is followed by an empty line and then a line containing -1.

Output

For every block in the input file, output a single line containing the time and coordinate of the last place to catch fire. The time and the coordinate should be in the same units and from the same range as input, but with precision of 3 decimal places. If there are multiple solutions, output the one which is the closest if you travel from the zero meridian east (i.e. in the positive direction).

Example

Input:

2
2
1 90
1 -90

10.0
3
1 40
2 45
6 -80

-1

Output:

46.000 0.000
15.500 -175.000

Note that in the second case, the fire at 45 degrees actually starts 1.5 hours after 12:00am. This of course does does not prevent anybody from igniting it again 2 hours after 12:00am.


Added by:Adrian Kuegel
Date:2005-08-11
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:IPSC 2002









SPOJ Problem Set (easy)

416. Divisibility by 15

Problem code: DIV15

There is a string containing only decimal digit characters. The length of the string is between 1 and 1000. Using characters of the string, you have to construct the maximum number which divides by fifteen without remainder. Each character of the string may not be used more than once.

Input

First line of input contains an integer t (1t90), equal to the number of testcases. Then descriptions of t testcases follow.

Each testcase is described in a single line representing the source string.

Output

For each testcase output one line with the decimal representation of the maximum number. Leading zeroes should be omitted. If no number can be constructed, output a single word “impossible”.

Example

Input:
1
02041

Output:
4200

Added by:Ivan Metelsky
Date:2005-08-25
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6 PYTH 3.2.3 n
Resource:NEERC Western Subregion QF 2004









SPOJ Problem Set (classical)

417. The lazy programmer

Problem code: LAZYPROG


A new web-design studio, called SMART (Simply Masters of ART), employs two people. The first one is a web-designer and an executive director at the same time. The second one is a programmer. The director is so a nimble guy that the studio has already got N contracts for web site development. Each contract has a deadline di.

It is known that the programmer is lazy. Usually he does not work as fast as he could. Therefore, under normal conditions the programmer needs bi of time to perform the contract number i. Fortunately, the guy is very greedy for money. If the director pays him xi dollars extra, he needs only (bi - ai*xi) of time to do his job. But this extra payment does not influence other contracts. This means that each contract should be paid separately to be done faster. The programmer is so greedy that he can do his job almost instantly if the extra payment is (bi/ai) dollars for the contract number i.

The director has a difficult problem to solve. He needs to organize programmer’s job and, may be, assign extra payments for some of the contracts so that all contracts are performed in time. Obviously he wishes to minimize the sum of extra payments. Help the director!

Input

First line of the input contains an integer t (1t45), equal to the number of testcases. Then descriptions of t testcases follow.

First line of description contains the number of contracts N (1N100000, integer). Each of the next N lines describes one contract and contains integer numbers ai, bi, di (1ai, bi10000; 1di1000000000) separated by spaces.

At least 90% of testcases will have 1N10000.

Output

For each testcase in the input your program should output one line with a single real number S. Here S is the minimum sum of money which the director needs to pay extra so that the programmer could perform all contracts in time. The number must have two digits after the decimal point.

Example

Input:
1
2
20 50 100
10 100 50

Output:
5.00

Added by:Ivan Metelsky
Date:2005-08-25
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:NEERC Western Subregion QF 2004









SPOJ Problem Set (classical)

418. Necklace

Problem code: NECKLACE


There are N points marked on a surface, pair (xi, yi) is coordinates of a point number i. Let's call a necklace a set of N figures which fulfills the following rules.

Write a program which takes points and constructs a necklace.

Input

First line of input contains an integer t (1t45), equals to the number of testcases. Then descriptions of t testcases follow.

The first line of the description contains one integer number N (2N100). Each of the next N lines contains two real numbers xi, yi (-1000xi, yi1000), separated by one space. It is guaranteed that at least one necklace exists for each testcase.

Output

For each testcase your program should output exactly N lines. A line #i should contain real number ri (0ri < 10000). To avoid potential accuracy problems, a checking program uses the following rules.

Example

Input:
1
4
0 0
10 0
10 10
0 10

Output:
7
7
7
7


Added by:Ivan Metelsky
Date:2005-08-25
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:NEERC Western Subregion QF 2004









SPOJ Problem Set ()

419. Transposing is Fun

Problem code: TRANSP


Problem

Suppose you are given a 2ax2b array. It is stored sequentially in memory in the usual way, first values in the first row, then values in the second one and so on. You would like to transpose it, but you don't have any additional memory. The only operation that you can perform is swapping contents of two memory cells. What is the minimal number of such operations required for transpostion?

Input

The first line of input contains the number of test cases c (1<=c<=100). Each test case consists of two integers a,b (0<=a+b<=500000).

Output

For each test case output the minimal number of swaps required to transpose an 2ax2b array. As it can be quite large, you have to output its remainder when divided by 1000003 (yes, it's a prime number :).

Example

Input:
3
1 1
2 2
5 7

Output:
1
6
3744


Added by:Pawel Gawrychowski
Date:2005-09-03
Time limit:30s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









SPOJ Problem Set (classical)

421. Another Road Problem

Problem code: AROAD


Problem

Let's say you are given a set of cities (numbered from 1 to n) and possible bidirectional roads between them. You would like to build cheapest road network that will make getting from the capital (which has number 1) to every other city possible, where the cost of the network is just sum of its roads' costs. Seems easy? Well, it certainly would be too easy and boring, so this time you should satisfy one additional constraint: you must consider only networks in which there are at most d roads outgoing from the capital.

Input

First line of input contains number of test cases c (1<=c<=40). Each test case begins with number of cities n, number of possible roads m and maximum degree d (1<=n<=1000, 0<=m<=100000, 0<=d<=100). Then m lines describing roads follow, each of them containing road endpoints x,y and its cost c (1<=x,y<=n, 0<=c<=10000).

Output

For each test case output the cost of building cheapest road network or NONE if it is impossible.

Example

Input:
4
4 5 0
1 2 1
1 3 1
1 4 2
2 3 2
3 4 1000

4 5 1
1 2 1
1 3 1
1 4 2
2 3 2
3 4 1000

4 5 2
1 2 1
1 3 1
1 4 2
2 3 2
3 4 1000

4 5 3
1 2 1
1 3 1
1 4 2
2 3 2
3 4 1000

Output:
NONE
1003
5
4


Added by:Pawel Gawrychowski
Date:2005-10-07
Time limit:6s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

422. Transposing is Even More Fun

Problem code: TRANSP2

Problem

Suppose you are given a 2ax2b array. It is stored sequentially in memory in the usual way, first values in the first row, then values in the second one and so on. You would like to transpose it, but you don't have any additional memory. The only operation that you can perform is swapping contents of two memory cells. What is minimal number of such operations required for transpostion?

Input

First line of input contains number of test cases c (1<=c<=400000). Each test case consists of two integers a,b (0<=a+b<=1000000).

Output

For each test case output minimal number of swaps required to transpose an 2ax2b array. As it can be quite large, you have to output its remainder when divided by 1000003 (yes, it's a prime number :).

Example

Input:
3
1 1
2 2
5 7

Output:
1
6
3744


Added by:Pawel Gawrychowski
Date:2005-10-08
Time limit:8s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set ()

423. Assignments

Problem code: ASSIGN

Problem

Your task will be to calculate number of different assignments of n different topics to n students such that everybody gets exactly one topic he likes.

Input

First line of input contains number of test cases c (1<=c<=80). Each test case begins with number of students n (1<=n<=20). Each of the next n lines contains n integers describing preferences of one student. 1 at the ith position means that this student likes ith topic, 0 means that he definitely doesn't want to take it.

Output

For each test case output number of different assignments (it will fit in a signed 64-bit integer).

Example

Input:
3
3
1 1 1
1 1 1
1 1 1
11
1 0 0 1 0 0 0 0 0 1 1 
1 1 1 1 1 0 1 0 1 0 0 
1 0 0 1 0 0 1 1 0 1 0 
1 0 1 1 1 0 1 1 0 1 1 
0 1 1 1 0 1 0 0 1 1 1 
1 1 1 0 0 1 0 0 0 0 0 
0 0 0 0 1 0 1 0 0 0 1 
1 0 1 1 0 0 0 0 0 0 1 
0 0 1 0 1 1 0 0 0 1 1 
1 1 1 0 0 0 1 0 1 0 1 
1 0 0 0 1 1 1 1 0 0 0 
11
0 1 1 1 0 1 0 0 0 1 0 
0 0 1 1 1 1 1 1 1 1 1 
1 1 0 1 0 0 0 0 0 1 0 
0 1 0 1 0 1 0 1 0 1 1 
1 0 0 1 0 0 0 0 1 0 1 
0 0 1 0 1 1 0 0 0 0 1 
1 0 1 0 1 1 1 0 1 1 0 
1 0 1 1 0 1 1 0 0 1 0 
0 0 1 1 0 1 1 1 1 1 1 
0 1 0 0 0 0 0 0 0 1 1 
0 1 1 0 0 0 0 0 1 0 1 

Output:
6
7588
7426


Added by:Pawel Gawrychowski
Date:2005-10-08
Time limit:20s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

428. Particular Palindromes

Problem code: PARTPALI

A palindromic decimal integer reads the same forward and backward. For example, the following numbers are palindromic.

6, 55, 282, 5005, 78187, 904409, 3160613, 11111111

Palindromic integers are plentiful. In fact, any integer not divisible by 10 has an infinite number of multiples that are palindromic. (The standard representation of a nonzero multiple of 10 cannot be palindromic since its reversal would have a leading 0.)

Write a program to determine, for a given positive integer, how many of its positive multiples are palindromes of a given length.

Input

The first line of the input will specify an integer n indicating the number of problem instances to follow, one to a line. Each of the ensuing n lines will specify a pair of positive integers m,s separated by a single space, with 1 < m < 1000, s < 20. (For m,s in this range, there are fewer than 2^32 palindromes among the s-digit multiples of m.) Each line will terminate with an end-of-line.

Output

The output should indicate for each m,s, exactly how many s-digit positive palindromes are divisible by m, with one problem instance per line.

Example

Input:
5	
3 1	
25 3	
12 4	
30 3
81 6


Output:
3
2
7
0
0

Explanation: There are three positive 1-digit multiples of 3, namely, 3, 6, and 9; all 1-digit numbers are trivially palindromes. Among the 3-digit palindromes, 525 and 575 are multiples of 25. The 4-digit multiples of 12 that are palindromes are 2112, 2772, 4224, 4884, 6336, 6996, 8448. There are no positive palindromic numbers ending in 0 (since we do not allow leading 0's). No 6-digit palindromes are divisible by 81.


Added by:Sebastian Kanthak
Date:2005-10-26
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM Pacific Northwest Regional Contest 2003









SPOJ Problem Set ()

449. Simple Numbers with Fractions Conversion

Problem code: TCNUMFL

Every integer number n is represented in positional number system of base r by a sequence of digits 0 <= di < r, decimal point ',' and fractional part, so the value is equal to:

n = d0 + r * d1 + r2 * d2 + r3 * d3 + ... + r-1 * d-1 + r-2 * d-2 + r-3 * d-3 + ...

Your task is to convert a given number in r-base represantation into s-base representation with l digits after decimal point (no rounding - use floor), for example: decimal 231,5 into binary 11100111,1 with one digit after decimal point. Assume that r <= 36 and the digits are 0,1,2,3,4,5,6,7,8,9, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z.

Input

N [the number of series <= 1000]
n r s l [n < 361000 + 1, r,s <= 36, l <= 1000 ]

Output

n [s-base representation of number n]

Text grouped in [ ] does not appear in the input and output file.

Example

Input:
10
500,1 6 31 3
3866,DJ 22 27 1
EH75,L3 24 4 3
A73C,10B 13 27 2
6C6J,E483 22 6 2
JA,L 30 5 4
6,5A 20 31 2
1,C5 14 7 1
HD,6K 26 9 2
1001,011 2 10 3

Output:
5P,555
1M8H,H
301223231,320
14MB,25
1255211,35
4310,3222
6,8G
1,6
555,23
9,375

Added by:Piotr Piotrowski
Date:2004-11-08
Time limit:13s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: JAR









SPOJ Problem Set (classical)

484. Fossil in the Ice

Problem code: TFOSS


A small group of archaeologists is working in the Antarctic. Their sensors have detected a number of caves in which there are interesting fossils. However, a thick layer of ice blocks the entrance to each cave. The archaeologists possess the equipment needed to burn a tunnel in the layer of ice, but the fuel is extremely expensive. In order to determine the size of each fossil the group has launched a number of probes through small bore-holes. Each probe which hit the fossil emits a signal consisting of its x and y coordinates. Your task is to determine the smallest possible size of the tunnel, which is equal to the maximal distance between any two probes (so that the fossil won’t be damaged during extraction). The drilling equipment needs to be provided with the squared value of this distance.

Given the list of coordinates of the points containing probes, find the square of the maximal distance between any two probes.

Input

t [the number of tests <= 20] [empty line] n [the number of active probes <= 100000] x1 y1 [coordinates of the first probe] ... xn xn [integer coordinates from -50000000 to 50000000] [empty line] [input for the next test cases...]

Text grouped in [ ] does not appear in the input file.

Output

o1 [the square of the maximal distance in the first set]
[output for the next test cases...]

Example

Input:
5

1
2 -3

4
0 0
-2 2
2 2
1 0

6
-4 2
2 2
5 0
0 5
6 1
-1 -1

10
0 0
5 1
9 2
12 3
14 4
15 5
16 7
17 10
18 14
19 19

10
2 -3
-1 2
0 5
-5 -1
-4 2
4 0
1 3
4 3
-3 -4
0 -2

Output:
0
16
101
722
98

Added by:Lukasz Wrona
Date:2004-12-29
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

515. Collatz

Problem code: CLTZ

Let N be a positive integer, Consider the following recurrence: f(1) = N and f(K) = (0.5 + 2.5 * (f(K-1) mod 2)) * f(K-1) + (f(K-1) mod 2) if K>1. For a given N you have to compute the smallest L for which f(L)=1 (such an L always exists for N's in the input).

Input

Each line contains a positive integer N in decimal notation. You can be sure that N and all intermediate results are not bigger than 10^1888. Input terminated by EOF.

Output

For each number N in the input print one line with the value of L in decimal notation.

Example

Input:
1
2
321
1111111111111
111111111111111111111111111111111111111111111111111111111111
Output:
1
2
25
261
1296

Added by:Noszály Csaba
Date:2005-04-25
Time limit:8s
Source limit:18000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Folklore









SPOJ Problem Set (classical)

518. Zig-Zag Permutation

Problem code: ZZPERM


In the following we will deal with nonempty words consists only of lower case letters 'a','b',..., 'j' and we will use the natural 'a' < 'b' < ... < 'j' ordering. Your task is to write a program that generates almost all zig-zag words (zig-zag permutations) from a given collection of letters. We say that a word W=W(1)W(2)...W(n) is zig-zag iff n = 1 or W(i) > W(i+1) and W(j) < W(j+1) for all odd 0 < i < n and for all even 0 < j < n or W(i) > W(i+1) and W(j) < W(j+1) for all even 0 < i < n and for all odd 0 < j < n. For example: "aabcc" is not zig-zag, "acacb" is zig-zag, "cac" is zig-zag, "abababc" is not zig-zag. If you imagine all possible zig-zag permutations of a word in increasing lexicographic order, you can assign a serial number (rank) to each one. For example: the word "aabcc" generates the sequence: 1 <-> "acacb", 2 <-> "acbca", 3 <-> "bacac", 4 <-> "bcaca", 5 <-> "cabac", 6 <-> "cacab".

Input

The input file consists several test cases. Each case contains a word (W) not longer than 64 letters and one positive number (D). The letters of each word are in increasing order. Input terminated by EOF.

Output

For each case in the input file, the output file must contain all of the zig-zag permutations of W whose zig-zag serial is divisible by D, in increasing lexicographic order - one word per line. In the next line you have to print the total number of zig-zag permutations of W. There is no case that produces more than 365 lines of output. Print an empty line after each case.

Example

Input:
j 1
abc 2
aaabc 1
aaabb 2
aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbcccdd 123456


Output:
j
1

bac
cab
4

abaca
acaba
2

1

babacbcabacabadabababababababababadab
213216


Added by:Noszály Csaba
Date:2005-05-05
Time limit:8s
Source limit:12345B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Folklore









SPOJ Problem Set (classical)

526. Divisors

Problem code: DIV

Let N be a positive integer. In theory it is easy to decide if d(N) (the number of positive divisors of N including 1 and N) is prime or not. Your task is just a little bit harder: compute all N in [1,10^6] for which d(N)=p*q where p and q distinct primes.

Input

There is no input for this problem.

Output

To make the problem less io related write out only every 9-th of them, one per line.

Output:
50
99
162
...
999524
999728
999927

Added by:Noszály Csaba
Date:2005-05-16
Time limit:4s
Source limit:3333B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Folklore.









SPOJ Problem Set (classical)

530. Divisors 2

Problem code: DIV2

Let N be a positive integer and d(N) be the number of positive divisors of N including 1 and N. Your task is to compute all N in [1,10^6] for which d(N)>3 and if M divides N then d(M) divides d(N) too.

Input

None.

Output

To make the problem less output related write out only every 108-th of them, one per line.

Example

Output:
267
511
753
...
999579
999781
999977

Added by:Noszály Csaba
Date:2005-05-24
Time limit:9s
Source limit:3333B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Folklore









SPOJ Problem Set ()

598. Increasing Subsequences

Problem code: INCR

A sequence p(1), p(2), ..., p(N) consisting of numbers 1, 2, ..., N is called a permutation if all elements in the sequence are different.

It is said that a permutation p contains increasing subsequence of k elements when there are numbers 1 ≤ i1 < i2 < ... < ik ≤ N such that p(i1) < p(i2) < ... < p(ik).

When a permutation p contains an increasing subsequence consisting of B elements and does not contain an increasing subsequence consisting of B+1 elements then the number B is called the degree of increase of this permutation.

You need to write a program which being given a number N calculates the number of permutations whose degree of increase is B. Since the number of such permutations might be quite big, it is necessary to calculate its remainder of integer division by 1 000 000 000.

Input

First line of input contains integer T (1 ≤ T ≤ 60) - the number of testcases. Then descriptions of T testcases follow.

The description of the testcase consists of one line. The line contains two integer numbers N and B (1 ≤ N ≤ 40, 1 ≤ B ≤ 5) separated by one or more spaces.

Output

For each testcase in the input your program should output one line. This line should contain one integer number which is the remainder of integer division by 1 000 000 000 of the number of permutations whose degree of increase is B.

Example

Input:
1
3 2

Output:
4

Added by:Ivan Metelsky
Date:2005-11-07
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:NEERC Western Subregion QF 2005









SPOJ Problem Set (classical)

660. Dungeon of Death

Problem code: QUEST4

To reach the treasure, Jones has to pass through the "Room of Death". The floor of this room is a square with side 120 units. It is laid with square tiles of dimensions {1 X 1} arranged into a grid. But, at some places in the grid tiles are missing. As soon as the door to this room is opened poisonous gas starts coming out of these missing grid locations. The only escape from this gas is to completely cover these locations with planks lying outside the room. Each plank has dimensions {120 X 1} and can only be placed parallel to either sides of the floor. Now Jones wants to minimize the damage to his health so that he has enough of it left for the treasure. He figures out that in order to achieve this he has to use the minimum number of planks possible. He also realises that even if the planks overlap, poisonous gas from the missing tiles can still be successfully blocked. Please help Jones in this task.

Dungeon of Death: Tiles Uncovered
Dungeon of Death: Tiles Covered

Input

Output

The output should consist of t lines, one for each room. The kth line in the output should be an integer mk, the minimum number of planks needed for the kth room.

Example

Input:
2
3
1 0
2 0
3 0
4
1 1
2 2
3 3
4 4

Output:
1
4


Added by:Kashyap KBR
Date:2005-12-08
Time limit:8s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (classical)

661. Nail Them

Problem code: QUEST5

To get to the treasure, Jones must complete one more task. He comes across a table, where there are a number of wooden planks lying along the length of the table. He notices that the width of the table is exactly equal to the width of every plank on it. The planks are so heavy that they cannot be manually moved in any way. Some of these wooden planks are overlapping. Jones has a hammer and the Gods grant him infinite nails. The planks have to be joined to the table with nails such that every plank is connected to the table through at least one nail. The nails are of sufficient length, and have to be hammered vertically into the table. One or more planks can be joined to the table through a single nail provided they have a common overlap. Find out the minimum number of nails he needs to nail all planks to the table.

Planks

Input

Output

The output must contain t lines , the kth line corresponding to the kth table. The output on the kth line must be an integer ik, the minimum number of nails required.

Example

Input:
2
3
1 5
3 5
2 4
2
1 4
4 5

Output:
1
1


Added by:Kashyap KBR
Date:2005-12-08
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6









SPOJ Problem Set (main)

665. String it out

Problem code: SUBS

Let A and B be two strings made up of alphabets such that A = A[1-n], B = B[1-m]. We say B is a subsequence of A if there exists a sequence of indices i1 < i2 <..m of A such that A[ik] = B[k].

Given B[1-m], a string of characters from some alphabets, B^i is defined as string with the characters of B each repeating i times. For example, (abbacc)^3 = aaabbbbbbaaacccccc. Also, B^0 is the empty string.

Given strings X, Y made up of characters from 'a' - 'z' find the maximum value of M such that X^M is a subsequence of Y.

Input

Output

The output must contain t lines, each line corresponding to a test case. The value on the kth line should be the value of M for the kth pair of X and Y.

Example

Input:
3
abc
aabbcc
abc
bbccc
abcdef
abc

Output:
2
0
0


Added by:Kashyap KBR
Date:2005-12-12
Time limit:8s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK NODEJS PERL 6 PYTH 3.2.3 n SED









SPOJ Problem Set (classical)

666. Con-Junctions

Problem code: VOCV

The city of Y-O is a network of two-way streets and junctions with the following properties:

  1. There is no more than one street between each pair of junctions.
  2. Every junction is connected to every other junction either directly via a street or through other junctions by a unique path.
  3. When a light is placed at a junction, all the streets meeting at this junction are also lit.

A valid lighting is a set of junctions such that if lights were placed at these, all the streets would be lit. An optimal lighting is a valid lighting such that it contains the least number of junctions.

The task is divided into two subtasks:

  1. Find the number of lights in an optimal lighting.
  2. Find the total number of such optimal lightings in the city.

Input

Output

The output must consist of t lines, the kth line corresponding to the kth network; (1 <= k <= t). The kth line must contain two integers separated by a single space. The first integer on the kth line must be the number of junctions in an optimal lighting of network k. The second integer must be N%10007, which is the remainder left by the number of optimal lightings when divided by 10007.

Example

Input:
2
4
1 2
2 3
3 4
3
1 2
1 3

Output:
2 3
1 1


Added by:Kashyap KBR
Date:2005-12-12
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: JAR NEM NICE NODEJS PERL 6 SCM qobi ST









SPOJ Problem Set (classical)

676. Sorting is not easy

Problem code: LSORT

An N-element permutation is an N-element sequence of distinct numbers from the set {1, 2, ...,n}. For example the sequence 2,1,4,5,3 is a 5-element permutation. P is an N-element permutation. Your task is to sort P in ascending order. But because it is very simple, I have a new rule for you. You have two sequences P and Q. P is an N-element permutation and Q is initially empty and formed by sorting P (i.e. finally Q = 1, 2, 3,... , N). You have to implement N steps to sort P. In the i-th step, P has N-i+1 remaining elements, Q has i-1 elements and you have to choose some x-th element (from the N-i+1 available elements) of P and put it to the left or to the right of Q. The cost of this step is equal to x * i. The total cost is the sum of costs of individual steps. After N steps, Q must be an ascending sequence. Your task is to minimize the total cost.

Input

The first line of the input file is T (T ≤ 10), the number of test cases. Then descriptions of T test cases follow. The description of each test case consists of two lines. The first line contains a single integer N (1 ≤ N ≤ 1000). The second line contains N distinct integers from the set {1, 2, .., N}, the N-element permutation P.

Output

For each test case your program should write one line, containing a single integer - the minimum total cost of sorting.

Example

N = 4
P = {4,1,3,2}
Step 1, Choose 3-rd, P={4,1,2}, Q={3} , Cost=3
Step 2, Choose 1-st, P={1,2}, Q={3,4} , Cost=2
Step 3, Choose 2-nd, P={1}, Q={2,3,4} , Cost=6
Step 4, Choose 1-st, P={}, Q={1,2,3,4}, Cost=4
The total cost is 15.
Another way to sort:
Step 1, Choose 4-th, P={4,1,3}, Q={2} , Cost=4
Step 2, Choose 2-nd, P={4,3}, Q={1,2} , Cost=4
Step 3, Choose 2-nd, P={4}, Q={1,2,3} , Cost=6
Step 4, Choose 1-st, P={}, Q={1,2,3,4}, Cost=4
The total cost is 18.

Input:
1
4
4 1 3 2

Output: 15

Added by:Nguyen Minh Hieu
Date:2005-12-20
Time limit:2s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:Romanian National Contest









SPOJ Problem Set (classical)

677. A place for the brewery

Problem code: BROW

The dwellers of the island Abstinence are very fond of alkoholfree beer. Hitherto alkohol-free beer was imported from Poland, but this year one of the cities on Abstinence is going to build a brewery. All the cities of this island lie on the coast and are connected by a highway running around the island along its shore. The investor building the brewery collected information about the demand for beer, i.e. how many tanks of beer are needed daily in each city. He has also a table of distances between cities. The cost of transporting one tank is 1 thaler per mile. A daily cost of transport is the amount of money, which has to be spent on transporting a necessary number of tanks of beer from the brewery to each city. The daily cost depends on the location of the brewery. The investor wants to find a location that minimizes the daily cost.

Task

Write a program which

Input

There are multiple test cases. Their number is given in the first line of input. In the first line of each test case there is one integer n - the number of cities, 5 <= n <= 10 000. (We assume that cities are numbered along the highway, so that the neighbouring cities have subsequent numbers. Cities 1 and n are neighbours too.) In each of the following n lines there are two non-negative numbers separated by a single space. Numbers zi di written in the line (i+1) are respectively the demand for beer in the city i and the distance (in miles) from city i to the next city on the highway. The entire length of the highway is not greater than 1 000 000 miles. The demand for beer in each city is not greater than 1 000 tanks.

Output

For each test case your program should write only one line - exactly one integer equal to the minimal daily cost of transport.

Example

Input:
1
6
1 2
2 3
1 2
5 2
1 10
2 3

Output:
41

Added by:Pawe³ Dobrzycki
Date:2005-12-21
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:VII Polish Olympiad in Informatics, Ist Stage









SPOJ Problem Set (classical)

681. Building the Tower

Problem code: HANOI07


There are N cubes in a toy box which has 1-unit height, the width is double the height. The teacher organizes a tower-building game. The tower is built by the cubes. The height of the tower is H (h levels). The bottom of the tower contains M cubes; and for all above level, each must contains a number of cubes which is exactly 1 less than or greater than the number of cubes of the level right below it. Your task is to determine how many different towers can be there. Two towers are considered different if there is at least one number i (1< i <=H) so that the i'th level of one tower contains a different number of cubes to the i'th level of the other tower.

Input

The first line of input file is the integer number t ( 0 < t < 1002 ) , the number of test cases . Each test case in one line , the line contains three positive number N, H and M (N <= 32767, H<=60, M<=10).

Output

With each test case , write in one line , the total of different towers that can be founded.

Example

Input:
2
7 3 2
22 5 4
Output:
2
10
(* In the first test case , all the towers are : 2-1-2 , 2-3-2 . *)

Added by:Nguyen Minh Hieu
Date:2005-12-30
Time limit:7s
Source limit:7777B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:ACM









SPOJ Problem Set (classical)

682. Pairs of Integers

Problem code: PAIRINT

You are to find all pairs of integers such that their sum is equal to the given integer number N and the second number results from the first one by striking out one of its digits. The first integer always has at least two digits and starts with a non-zero digit. The second integer always has one digit less than the first integer and may start with a zero digit.

Input

The first line of the input file is the integer number t ( 1 ≤ t ≤ 20 ), the number of test cases. Then t lines follow, each test case in one line; the line consists of a single integer N (10 ≤ N ≤ 10^9).

Output

For each test case:

On the first line write the total number of different pairs of integers that satisfy the problem statement. On the following lines write all those pairs. Write one pair on a line in ascending order of the first integer in the pair. Each pair must be written in the following format

X + Y = N

Here X, Y, and N, must be replaced with the corresponding integer numbers. There should be exactly one space on both sides of '+' and '=' characters.

Example

Input:
2
302
11

Output:
5
251 + 51 = 302
275 + 27 = 302
276 + 26 = 302
281 + 21 = 302
301 + 01 = 302
1
10 + 1 = 11

Added by:Nguyen Minh Hieu
Date:2006-01-01
Time limit:1s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:2001-2002 ACM Northeastern European Regional Programming Contest









SPOJ Problem Set (acm)

684. Another Assignment Problem

Problem code: ASSIGN4

Assume that you are a manager and there are m types of worker (numbered from 1 to m) and n types of task (numbered from 1 to n). There are a(i) workers of type #i and b(j) postitions for task #j. C(i, j) is the cost of hiring a worker of type #i to do the task of type #j. Your job is to minimize the cost of hiring workers to fill all the positions given that the total number of workers is equal to the total number of positions.

Input

The first line of input contains the number of test cases nTest (1<= nTest <= 10). Each test case contains:

Notes:

1 <= m, n <= 200;

1 <= a(i), b(i) <= 30000;

1 <= C(i, j) <= 10000.

Sum of a(i) equals to sum of b(j).

Output

For each test case write the minimum cost in a separate line (it will fit in a signed 32-bit integer).

Example

Input:
2
3 4
3 6 7
2 5 1 8
1 2 3 4
8 7 6 5
9 12 10 11
4 4
1 3 5 7
2 4 2 8
1 4 7 3
4 7 5 3
5 7 8 3
5 3 6 8

Output:
110
54

Added by:Nguyen Dinh Tu
Date:2006-01-02
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Tran Quang Khai









SPOJ Problem Set (classical)

685. Partition the sequence

Problem code: SEQPAR

Given an integer sequence containing n elements (numbered from 1 to n), your task is to find the minimum value M so that we can find k + 1 integers 0 = p(0) < p(1) < p(2) < ... < p(k-1) < p(k) = n, such that for any i from 0 to k - 1, the sum of elements from postition p(i)+1 to postition p(i+1) is not greater than M.

Input

The first line of input contains the number of test cases nTest (1 <= nTest <= 10).

Each test case contains:

The first line contains n, k. (1 <= k <= n <= 15000)

Each of the next n lines contains an integer of the sequence with value range from -30000 to 30000.

Output

For each test case write the minimum number M in a separate line.

Example

Input:
1
9 4
1
1
1
3
2
2
1
3
1

Output:
5

Added by:Nguyen Dinh Tu
Date:2006-01-02
Time limit:44s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Viet Nam Olympiad in Informatic 2005, Day I









SPOJ Problem Set ()

687. Repeats

Problem code: REPEATS

A string s is called an (k,l)-repeat if s is obtained by concatenating k>=1 times some seed string t with length l>=1. For example, the string

s = abaabaabaaba

is a (4,3)-repeat with t = aba as its seed string. That is, the seed string t is 3 characters long, and the whole string s is obtained by repeating t 4 times.

Write a program for the following task: Your program is given a long string u consisting of characters ‘a’ and/or ‘b’ as input. Your program must find some (k,l)-repeat that occurs as substring within u with k as large as possible. For example, the input string

u = babbabaabaabaabab

contains the underlined (4,3)-repeat s starting at position 5. Since u contains no other contiguous substring with more than 4 repeats, your program must output the maximum k.

Input

In the first line of the input contains H- the number of test cases (H <= 20). H test cases follow. First line of each test cases is n - length of the input string (n <= 50000), The next n lines contain the input string, one character (either ‘a’ or ‘b’) per line, in order.

Output

For each test cases, you should write exactly one interger k in a line - the repeat count that is maximized.

Example

Input:
1
17
b
a
b
b
a
b
a
a
b
a
a
b
a
a
b
a
b

Output:
4
since a (4, 3)-repeat is found starting at the 5th character of the input string.
Added by:Hoang Hong Quan
Date:2006-01-05
Time limit:18s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:BOI 2004









SPOJ Problem Set (classical)

688. Toy Cars

Problem code: SAM

Jasio is a little boy - he is only three years old and enjoys playing with toy cars very much. Jasio has n different cars. They are kept on a shelf so high, that Jasio cannot reach it by himself. As there is little space in his room, at no moment may there be more than k toy cars on the floor. Jasio plays with one of the cars on the floor. Jasio's mother remains in the room with her son all the time. When Jasio wants to play with another car that is on the floor, he reaches it by himself. But when the toy is on the shelf, his mummy has to hand it to him. When she gives Jasio one car, she can at the same time pick any car from the floor and put it back on the shelf (so that there remains sufficient space on the floor). The mother knows her child very well and therefore can predict perfectly which cars Jasio will want to play with. Having this knowledge, she wants to minimize the number of times she has to hand Jasio a toy from the shelf. Keeping that in mind, she has to put the toys off on the shelf extremely thoughtfully.

Task

Write a programme that:

1.reads from the standard input the sequence of toy cars in order in which Jasio will want to play with them,

2.calculates the minimal number of times the mother has to pick cars from the shelf,

3.writes the result to the standard output.

Input

In the first line of the standard input is H- the number of test case (H <= 16). For each test case follow contains some lines, start with three integers: n, k, p (1 <= k <= n <= 100000, 1 <= p <= 500000), separated by single spaces. These denote respectively: the total number of cars, the number of cars that can remain on the floor at once and the length of the sequence of cars which Jasio will want to play with. Each of the following p lines contains one integer. These integers are the numbers of cars Jasio will want to play with (the cars are numbered from 1 to n ).

Output

For each test case, you should write only one integer - the minimal number of times his mother has to pick a car from the shelf.

Example

Input:

For the following input data:

3 2 7 1 2 3 1 3 1 2 Output:

the correct answer is:

4


Added by:Hoang Hong Quan
Date:2006-01-08
Time limit:8s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:12th Polish Olympiad in Informatics, stage 1









SPOJ Problem Set (classical)

693. Lethal Warfare

Problem code: LWAR

A major cosmic battle was getting over. The InterGalactic SuperPower had been under attack, but it had defended itself quite well. It was about to launch its final retaliatory assault. But the number of enemy ships was quite large and they could scatter very easily. Their only hope, or so their Space Warfare expert said, was to bomb the enemies (who happened to be lined up in a long line!) using the strategy described below.

Because the number of ships will be a power of 2, to bomb all the ships (numbered 0 to 2N -1), the strategy to be used, which we will call BombStrat, goes like this:
1. Bomb it’s first half, [0 to 2N-1 -1], in the left to right direction.
2. Of the remaining half, bomb its latter half part in reverse direction, i.e., bomb ships 2N-1, 2N-2,...., 2N-1+2N-2 in that order.
3. Then use BombStrat on the remaining ships: [2N-1 to 2N-1 + 2N-2 -1 ]

For example, when N=3, i.e., with ships numbered from 0 to 23 -1, this is what happens:
Step 1: Ships 0,1,2,3 get bombed in that order.
Step 2: Ships 7, 6 go down next.
Step 3: Now, the remaining ships [4, 5] are destroyed using the same strategy.

So the bombing is done in the order 0 -> 1 -> 2 -> 3 -> 7 -> 6 -> 4 -> 5. To make the job easier for the InterGalactic SuperPower’s ships’ pilots, they want to find which ship should be bombed when. This is your task. Given N, and the description of a ship, return the 0-based serial number of the bomb will blast it.

Input

T – the number of test cases, T<=50.
For each test case:

One line containing a binary number, describing the number of the place. The length of this string will equal N (it will be padded with leading zeroes if necessary). N<=30000.

Output

For each test case, output the index of a bomb, represented in the same format, as binary digits, whose length is exactly N.

Example

Sample Input:
3
111
100
1100

Sample Output:
100
110
1011


Added by:Prasanna
Date:2006-01-13
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ByteCode '06









SPOJ Problem Set (classical)

694. Distinct Substrings

Problem code: DISUBSTR

Given a string, we need to find the total number of its distinct substrings.

Input

T- number of test cases. T<=20;
Each test case consists of one string, whose length is <= 1000

Output

For each test case output one number saying the number of distinct substrings.

Example

Sample Input:
2
CCCCC
ABABA

Sample Output:
5
9

Explanation for the testcase with string ABABA:
len=1 : A,B
len=2 : AB,BA
len=3 : ABA,BAB
len=4 : ABAB,BABA
len=5 : ABABA
Thus, total number of distinct substrings is 9.


Added by:Prasanna
Date:2006-01-13
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ByteCode '06









SPOJ Problem Set (classical)

695. Unite Fast

Problem code: UFAST


The Agents need to unite. They are on a road and each of them possess a special device which can both send and receive signals, in both directions upto a maximal distance of D units. Apart from this small limitation, the devices work very efficiently so that the time taken for interdevice communication is practically zero. Now that the agents are at different points on the road, for them to be able to communicate with each other at will, every agent should be connected to every other agent through one or more intermediate devices. For example: agent A may communicate to agent C via agent B’s device, when A and C are not close enough. This happens when dist(A,C)>D, but dist(A,B)<=D and dist(B,C)<=D.

Getting the line ready, is the process of agents moving from their current positions in order to get the network fully connected. That is, from every agent to every other agent, there is a communication path.

The agent’s final positions (in two cases that are going to follow) are decided by a programmer, who watches the scene from above and instructs each agent of the time to move and the final position to move to. Each agent moves a unit distance in unit time.

We need to find the minimal time taken for the programmer to “get the line ready” if he moves the agents:
1. Independently: In other words, every agent moves to their final position without waiting for any other agent; all agents are told of their final positions at time zero.
2. Sequentially: In this the agents form a definite sequence of movement. No two agents are moving at the same time.

Input

T – number of test cases. For each test case :
N D – where N is the number of agents, D is the maximal communication distance
The i-th line, of the N-lines that follow gives the position of the i-th agent on the road currently.

Output

For each test case, output two integers;
1st – minimal time taken to unite if they move independently
2nd - minimal time taken to unite if they move sequentially

Constraints:
T<=20
1<=N,D<=100 ;
Each agent's initial position is between 0 and 1000.

Example

Sample Input:
2
4 3
10 20 30 35
5 3
1 2 3 4 30

Sample Output:
8 23
12 23


Added by:Prasanna
Date:2006-01-13
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ByteCode '06









SPOJ Problem Set (classical)

696. Liar Liar

Problem code: LIAR


Professor Millman hates us, and worse, characterizes us as liars. We don’t care if he means it or not, but we (more professional that him!) planned to give the lower and upper bound on the number of liars in the class (so that you know what happens the next time he scolds us! ).

To start with we took a survey of all students in the class. Each student gave a reply about every student saying whether that student is a liar or not. These answers are in the form of a Matrix A, where A[i][j] represents the reply given by the i-th student about the j-th student. If that character is ‘L’ – it means he/she is a liar; if it’s ‘T’ – then it means that, that student is a truth speaker.

We take the following as our definition of the terms Truth-Speaker, and Liar:
Truth-Speaker (‘T’): All his/her replies are true.
Liar (‘L’) : (S)he has made at least one false reply.

Input

T – the number of test cases; For each test case :
N – total number of students in the class
Matrix A of NxN characters, without space separation;

Output

For i-th test case output one line of the form “Class Room#i contains atleast A and atmost B liars”, where A and B are the lower and the upper bounds on the number of liars respectively. If there is a paradoxical class room, instead of the above line, print “Class Room#i is paradoxical”.

Constraints:
T<=50; Our class rooms contain atmost 70 students.

Example

Sample Input:
4
2
LL
TT
3
TTT
TTT
TTT
4
TLLL
LTLL
LLTL
LLLT
5
TLTLT
TTTTT
LLTLL
LLLLL
TLTLT

Sample Output:
Class Room#1 is paradoxical
Class Room#2 contains atleast 0 and atmost 3 liars
Class Room#3 contains atleast 3 and atmost 4 liars
Class Room#4 contains atleast 4 and atmost 4 liars

Here a paradox occurs if a person can't be classified as a liar or a truth-speaker.


Added by:Prasanna
Date:2006-01-13
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ByteCode '06









SPOJ Problem Set (classical)

697. Matrix Words

Problem code: MWORDS


Given an NxN matrix of characters. We start at position (1,1) and want to reach (N,N) in exactly 2N-1 moves. Each move consists of movement in one of the four standard directions. As we move, we collect the characters found in our positions forming a string. We now constrain our attention to all paths that do not cross the diagonal of the matrix. However the parts of the path can be on the diagonal line. These paths can be classified into two partitions; the paths that lie above and paths that lie below the diagonal. Each path is represented by a string of characters formed by the ordered concatenation of characters found on the way. If we consider the set of all valid paths, (both upper and lower) get their corresponding strings, sort them all in alphabetical order, we obtain the (ordered) master set. Note that the master set might contain duplicates, and all strings in the master set consist of exactly 2N-1 characters. Let M be the total number of strings in the master set, given an integer I, we need to find the string with index = I (modulo M) within the master set.
If Master Set = { “A”,”B”,”B”,”C” } (although this set can never be a master set!)
I=0 produces “A”, while I=2 and I=5, produces “B”.

Constraints:
N<=30.
I<=1018. ‘I’ will fit into a 64-bit integer.

Input

T-number of test cases
N I
Next is the NxN matrix of characters, N characters per line.
All characters are between ‘A’-‘Z’ (only uppercase).

Output

For each test case output the corresponding string sought for in the master set.

Example

Sample Input:
2
3 18
DAA
BDA
BBD
3 18
DAA
ADA
AAD

Sample Output:
DBBBD
DADAD

Explanation:
Test case I: Master Set = { “DAAAD”, “DADAD”,”DBBBD”,”DBDBD”}
Test case II: Master Set = { “DAAAD”,”DAAAD”,”DADAD”,”DADAD”}


Added by:Prasanna
Date:2006-01-13
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ByteCode '06









SPOJ Problem Set (classical)

698. Plane Hopping

Problem code: PLHOP


This man has grown so rich that, when he travels between any two locations he always takes atleast K flights. In a region of N cities, we need to find the minimal cost required for the man to travel between every pair of cities. There are provisions (especially for this type of rich men,) to fly from i-th city to the i-th city itself!

Input

T – The number of test cases.
In each test case :
K N
NxN matrix representing the costs of the tickets. The i-th line, j-th column’s entry represents the cost of a ticket from city i to city j. The numbers are of course space separated.

Constraints :
T<=20
N<=50
K<=109
The cost of each ticket <= 100
Each element of the output matrix will fit into a 64-bit integer.

Output

For the i-th test case , 1st line is of the form “Region #i:”.
In the following N lines, output an NxN matrix where the j-th element of the i-th line represents the minimal cost to travel from city i to city j with taking atleast K flights. The numbers on a line must be separated by atleast one space. Output a blank line after each testcase (including the last one).

Example

Sample Input:
2
3 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
10999 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Sample Output:
Region #1:
3 4 5 6
7 8 9 10
11 12 13 14
15 16 17 18

Region #2:
10999 11000 11001 11002
11003 11004 11005 11006
11007 11008 11009 11010
11011 11012 11013 11014


Added by:Prasanna
Date:2006-01-13
Time limit:2.5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ByteCode '06









SPOJ Problem Set (classical)

699. Huge Knap Sack

Problem code: HKNAP

Our King has won the brutal battle and this whole land is now ours. The special thing about this land is that it has many beautiful golden statues. Our King wants to take back as much gold as possible to his palace. We have found that there are N types of statues and -- almost unbelievably -- that there is an unlimited number of each type of statue. Each statue of type i has a weight of W[i] units and occupies V[i] units of volume. Our King wants to maximize the amount of gold he carries back to his palace. We may use S sacks for this purpose, each of volume Y. All sacks are filled up independently by golden statues. However, there is a provision to stitch two sacks together, at the cost of C units of gold. Stitching three sacks costs 2*C because it requires two stitchings, and so on. Your task is to find how much gold our King can possibly gain, i.e. the total weight of the statues brought back, minus the stitching charges.

Input

T – The number of test cases.
For each test case :
N S Y C // 1st line
Next N lines two numbers W[i] and V[i] each.

Output

One integer, the maximum gain in gold for our King.
This gain is the total amount of gold transported minus stitching charges.

Constraints :
1<= S <= 1000
1<= Y <= 1000 000 000
1<= N <= 1000
1<= W[i] <= 100; (for all i)
1<= V[i] <= 18;
The Output will fit into a 64-Bit integer.
1<=T<=20
All W[i] & V[i] are guaranteed to be either prime or equal to 1.

Example

Sample Input:
2
2 5 3 1
1 2
5 7
2 5 3 1
1 2
7 5

Sample Output:
6
17


Added by:Prasanna
Date:2006-01-13
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ByteCode '06









SPOJ Problem Set (classical)

700. Branch Prediction

Problem code: BPRED


As most of you might already know, the Intel-class hi-tech processors of today do a series of parallel tasks to help speedup instruction execution. The most complicated of those tasks is branch prediction. Since the instruction chunks on a modern processor are broken down into independent chunks and executed for a speed up, there is always a requirement to predict what branch an execution path will take (before the actual operands required for the condition to be evaluated to select the branch, are available). This complex task, is not addressed to fullest level today, but heuristics (as always) have helped.

The task we are going to consider now is much more simple compared to the actual branch prediction task. For our modelling, let us suppose that every instruction has the following syntax:

All labels are strings of alphabets only. Labels are case-sensitive.

Moreover the probability that a certain branch will be taken is P (it is equal for all branches). If a branch is taken, the point of execution (control) goes to the branched-label. Otherwise the next statement in that order is executed. Control starts at the "start" (lowercase) label and control ends at the "end" (lowercase) label. The branch-label of start and end are themselves, and when start is executed, the control goes to the next instruction, and when end is executed, processing ends, with 100% probability. The last statement in the program is always an “end”.

It is required to find the expected number of times a statement executes.

Input

T – the number of test cases;
For each test case:
1st line contains one integer N (the number of lines to follow), one real P and one label L.
Each of the N lines that follow consist of instructions (two labels).

Output

For each test case, output one line containing:
"Expected number of times label L is executed is R",
where L - is the label given in the input
R - is the number of times the label is expected to be executed. It must be printed with exactly five decimal places.

Constraints:
T<=20
3<=N<=120.
P lies between 0.01 and 0.99, i.e. no jump is 100% sure.
Also you can assume no label occurs on the jump side, without being defined throughout the program.
Each label is less than 10 characters in length.
Also each line has a distinct label associated with it.

Example

Sample Input:
3
5 .5 B
C start
start start
B C
D C
end end
5 .99 C
start start
A B
B A
C end
end end
3 .5 label
start start
label label
end end

Sample Output:
Expected number of times label B is executed is 4.00000
Expected number of times label C is executed is 1.00000
Expected number of times label label is executed is 2.00000


Added by:Prasanna
Date:2006-01-13
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource: ByteCode '06









SPOJ Problem Set ()

702. Barn Expansion

Problem code: EXPAND

Farmer John has N (1 <= N <= 25,000) rectangular barns on his farm, all with sides parallel to the X and Y axes and integer corner coordinates in the range 0..1,000,000. These barns do not overlap although they may share corners and/or sides with other barns. Since he has extra cows to milk this year, FJ would like to expand some of his barns. A barn has room to expand if it does not share a corner or a wall with any other barn. That is, FJ can expand a barn if all four of its walls can be pushed outward by at least some amount without bumping into another barn. If two barns meet at a corner, neither barn can expand. Please determine how many barns have room to expand.

Input

t – the number of test cases, then t test cases follow.

Each test case takes the following form:

The first line contains the number of rectangular barns - n.

Each of the next n lines contains:

Four space-separated integers A, B, C, and D, describing one barn. The lower-left corner of the barn is at (A,B) and the upper right corner is at (C,D).

Output

For each test case write a single integer that is the number of barns that can be expanded in a separate line

Example

Input:
1
5
0 2 2 7
3 5 5 8
4 2 6 4
6 1 8 6
0 0 8 1

Output:
2
Input/Output details:

There are 5 barns. The first barn has its lower-left corner at (0,2) and its upper-right corner at (2,7), and so on.

Only two barns can be expanded --- the first two listed in the input. All other barns are each in contact with at least one other barn.


Added by:Nguyen Dinh Tu
Date:2006-01-17
Time limit:4s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:USACO December 2005 Gold Division









SPOJ Problem Set ()

703. Mobile Service

Problem code: SERVICE


A company provides service for its partners that are located in different towns. The company has three mobile service staff employees. If a request occurs at some location, an employee of the service staff must move from his current location to the location of the request (if no employee is there) in order to satisfy the request. Only one employee can move at any moment. They can move only on request and are not allowed to be at the same location. Moving an employee from location p to location q incurs a given cost C(p,q). The cost function is not necessarily symmetric, but the cost of not moving is 0, i.e. C(p,p)=0. The company must satisfy the received requests in a strict first-come, first-serve basis. The goal is to minimize the total cost of serving a given sequence of requests.

Task

You are to write a program that decides which employee of the service staff is to move for each request such that the total cost of serving the given sequence of requests is as small as possible.

Input

The first line of input contains the number of test cases - nTest. Each test case contains:

The first line of each test cases contains two integers, L and N. L (3 <= L <= 200) is the number of locations and N (1 <= N <= 1000) is the number of requests. Locations are identified by the integers from 1 to L. Each of the next L lines contains L non-negative integers. The jth number in the line i+1 is the cost C(i,j), and it is less than 2000.

The last of each test cases contains N integers, the list of the requests. A request is identified by the identifier of the location where the request occurs. Initially, the three service staff employees are located at location 1, 2 and 3, respectively.

Output

For each test case write the minimal total cost in a separate line.

Example

Input:
1
5 9
0 1 1 1 1
1 0 2 3 2
1 1 0 4 1
2 1 5 0 1
4 2 3 4 0
4 2 4 1 5 4 3 2 1
Output:
5

Added by:Nguyen Dinh Tu
Date:2006-01-17
Time limit:10s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:CEOI 2005, Day 1









SPOJ Problem Set (classical)

704. Remove The String

Problem code: PSTRING

Given two strings X and Y, your task is find the minimum number of characters to be removed from X in order to obtain a string X' that does not contain Y as a substring.

Input

Input contains some test cases. Each test cases contains two lines, First is X and second is Y. Length of X <= 10000, Length of Y <= 1000.

Output

For each test cases, You should output exactly one integer is the minimum number of characters to be remove

Example

Input:
ababaa
aba

Output:
1


Added by:Hoang Hong Quan
Date:2006-01-17
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:A contest of Romanian









SPOJ Problem Set (classical)

705. New Distinct Substrings

Problem code: SUBST1

Given a string, we need to find the total number of its distinct substrings.

Input

T- number of test cases. T<=20; Each test case consists of one string, whose length is <= 50000

Output

For each test case output one number saying the number of distinct substrings.

Example

Input:
2
CCCCC
ABABA

Output:
5
9

Added by:Hoang Hong Quan
Date:2006-01-18
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Base on a problem in ByteCode06









SPOJ Problem Set (classical)

707. Triple-Free Sets

Problem code: TFSETS


A set S of positive integers is called strongly triple-free if, for any integer x, the sets {x, 2x} and {x, 3x} are not subsets of S. Let's define F(n) as a number of strongly triple-free subsets of {1, 2, ..., n}, where n is a natural number.

You need to write a program which being given a number n calculates the number F(n) modulo 1 000 000 001.

Input

The first line of input contains integer T (1 ≤ T ≤ 500) - the number of testcases. Then descriptions of T testcases follow.

The description of the testcase consists of one line. The line contains an integer number n (1 ≤ n ≤ 100 000).

Output

For each testcase in the input your program should output one line. This line should contain one integer number which is the number F(n) modulo 1 000 000 001.

Example

Input:
5
3
1
10
20
39

Output:
5
2
198
43776
971827200

Added by:Ivan Metelsky
Date:2006-01-19
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Based on a problem from www.test-the-best.by









SPOJ Problem Set (classical)

709. The day of the competitors

Problem code: NICEDAY

The International Olympiad in Informatics is coming and the leaders of the Vietnamese Team have to choose the best contestants all over the country. Fortunately, the leaders could choose the members of the team among N very good contestants, numbered from 1 to N (3 ≤ N ≤ 100000). In order to select the best contestants the leaders organized three competitions. Each of the N contestants took part in all three competitions and there were no two contestants with equal results on any of the competitions. We say that contestant А is better than another contestant В when А is ranked before В in all of the competitions. A contestant A is said to be excellent if no other contestant is better than A. The leaders of the Vietnamese Team would like to know the number of excellent contestants.

Input

First line of the input contains an integer t (1 ≤ t ≤ 10 ), equal to the number of testcases. Then descriptions of t testcases follow. First line of description contains the number of competitors N . Each of the next N lines describes one competitor and contains integer numbers ai, bi, ci (1 ≤ ai, bi , ci ≤ N ) separated by spaces, the order of i-th competitor's ranking in the first competition , the second competition and the third competition.

Output

For each test case in the input your program should output the number of excellent contestants in one line.

Note : Because the input is too large so we have 4 input files and the total time limit is 4s ( not 1s ).

Example

Input:
1
3
1 2 3
2 3 1
3 1 2

Output:
3

Added by:Nguyen Minh Hieu
Date:2006-01-20
Time limit:1s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Base on a problem from BOI









SPOJ Problem Set (classical)

726. Promotion

Problem code: PRO

A large Bytelandian supermarket chain has asked you to write a program for the simulating costs of a promotion being prepared.

The promotion has to follow the following rules:

The turnover of the supermarket is very big, thus an assumption can be made, that at the end of every day, before taking out receipts amounting to the largest and the smallest sum, there are at least 2 receipts in the ballot box.

Your task is to compute (on the basis of information about prices on receipts thrown into the ballot box on each day of promotion) what the total cost of prizes during the whole promotion will be.

Write a program, which: reads from the standard input a list of prices on receipts thrown into the ballot box on each day of the promotion, computes the total cost of prizes paid in consecutive days of promotion, then writes the result to the standard output.

Input

The first line of the input contains one positive integer n (1 <= n <= 5000), which is the duration of promotion in days. Each of the next n lines consists of a sequence of non-negative integers separated by single spaces. Numbers in the (i+1)-th line of the file represent prices on receipts thrown into the ballot box on the i-th day of promotion. The first integer in the line is k, 0 <= k <= 10^5, the number of receipts on the day, and the next k numbers are positive integers standing for the sums on receipts; none of these numbers is larger than 10^6.

The total number of bills thrown into the ballot box during the whole promotion does not exceed 10^6.

Output

The output should contain exactly one integer, equal to the total cost of prizes paid during the whole promotion.

Example

Input:
5
3 1 2 3
2 1 1
4 10 5 5 1
0
1 2

Output:
19

Added by:Duc
Date:2006-01-24
Time limit:1s-4s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:VII Polish Olympiad In Informatics 2000, stage III









SPOJ Problem Set ()

729. Move your armies

Problem code: MAXIMUS

Commodus has discovered with your help that the traitor is Maximus. Commodus has gathered N prestigious armies A1 A2 ... AN and asked you to lead them to kill Maximus. A brave warrior like you must now act intelligently to lead the armies to victory.

There are three countries which are considered here, for simplicity lets name them C0, C1 and C2. You have moved the armies to C0 and you know that Maximus is in C2. You are wise enough to know that without all your N armies you stand no chance against great Maximus. The problem is that your armies are too egoistic in nature ( after all they were organized by Commodus ). Only the biggest army can leave any country Cy (Army Ax can leave Cy, if there is no army Ai in Cy with i > x.). Also, the army Ax will go into Cy only if it is the biggest army to get there, i. e. there is no army Ai in Cy with i > x.

There is another confusion here, all the armies Am have been trained by a different commander and they march differently. Each army Am where m is either 1 or prime can only move from Ci to C(i+1)%3, while your armies Am where m > 1 is composite will march only from Ci to C(i+2)%3.

Commodus is impatient and he is asking you to find the number of moves you need to reach Maximus. You are planning to reach there with the shortest possible number of moves; tell your answer to Commodus.

Example for N = 2:
The required number of steps would be 7
initially
C0 - A1, A2
C1 -
C2 -

after step 1
C0 - A1
C1 - A2
C2 -

after step 2
C0 - A1
C1 -
C2 - A2

after step 3
C0 -
C1 - A1
C2 - A2

after step 4
C0 - A2
C1 - A1
C2 -

after step 5
C0 - A2
C1 -
C2 - A1

after step 6
C0 -
C1 - A2
C2 - A1

after step 7
C0 -
C1 -
C2 - A1, A2

Input

The input will consist of at most 100 test cases. Each test case consists of a number N (the number of armies, 1 ≤ N ≤ 5000). The last test case is followed by a line containing 0.

Output

For each number N, you have to output the number of moves needed to move the armies to C2 with the minimum number of steps.

Example

Input:
1
2
3
4
100
0

Output:
2
7
21
49
1299510268586153115889930564780511199231

Added by:Adrian Kuegel
Date:2006-01-29
Time limit:10s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:Codearena 2006









SPOJ Problem Set (easy)

734. Ivan and his interesting game

Problem code: IVAN

Little Ivan likes to play games in his spare time. Unfortunately, he cannot always enjoy the company of his friends and sometimes he is a little bored when he is alone. Therefore, he makes up games, where he is the only player. He is especially proud of his last game and likes to tell you about it.
You are given two finite sequences of positive integers. The game consists of making consecutive moves. You are allowed to make the following move. You remove the last K1 numbers (K1≥1) from the first sequence (possibly the whole sequence) and find their sum S1 and the last K2 numbers (K2≥1) from the second sequence (again you can remove the whole sequence) and find their sum S2. Then you calculate the cost of the move to be (S1 – K1)*(S2 – K2). You continue to make moves until you remove all the numbers in both sequences. The total cost of the game is the sum of the costs of all moves. Your goal is to minimize this total cost. You are not allowed to leave one of the sequences empty, while the other is not.
As Ivan has told you the rules of the game, you realize that it is easily solvable with the help of a computer, so you decide to write a program GAME, that computes the minimum total cost of the game.

Input

Input data is read from the standard input and consists of three lines. The first line contains two space-separated integers, L1 and L2 (1 ≤ L1, L2 ≤ 2000), which denote the lengths of the two sequences. The second line contains L1 space-separated integers, which are the elements of the first sequence. The third line contains L2 space-separated integers, which are the elements of the second sequence. The elements of the sequences do not exceed 1000.

Output

Your program has to output one line on the standard output that contains only one number – the minimum total cost of the game as described above.

Example

Input:
3 2
1 2 3
1 2
Output:
2

Added by:VOJ problem setters
Date:2006-02-08
Time limit:1s-2s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:unknown









SPOJ Problem Set (classical)

735. Minimum Diameter Spanning Tree

Problem code: MDST


Solve the minimum diameter spanning tree problem for the simple graphs.

For a given list of adjacent vertices of a graph G find the minimum diameter spanning tree T and write down the diameter of this tree diam(T).

Each graph has only one connected component, so there is at least one spanning tree, which connects all the vertices.

Input

t [the number of test graphs]
Graph:
n [1 <= n <= 1000 the number of graph vertices]
i m v1 v2 ... vm [the list of m adjacent vertices to vertex i]

Output

For each test case output:
d [diameter of the minimum diameter spanning tree]

Example

Input:
6

10
1 3 2 3 4
2 3 1 5 7
3 3 1 5 6
4 3 1 6 8
5 3 2 3 9
6 3 3 4 10
7 1 2
8 1 4
9 1 5
10 1 6

10
1 4 4 5 7 9
2 1 8
3 4 4 7 8 10
4 3 1 3 9
5 2 1 9
6 2 8 9
7 4 1 3 8 9
8 5 2 3 6 7 9
9 7 1 4 5 6 7 8 10
10 2 3 9

1
1 0

2
1 1 2
2 1 1

3
1 1 2
2 2 1 3
3 1 2

5
1 2 2 4
2 3 1 3 4
3 1 2
4 3 2 5 1
5 1 4

Output:
5
3
0
1
2
3


Added by:Bart³omiej Kowalski
Date:2006-02-09
Time limit:1s-25s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:









SPOJ Problem Set (classical)

738. Another Counting Problem

Problem code: TREE

Tree is an important data structure in Computer Science. Of all trees we work with, Binary Tree is probably the most popular one. A Binary Tree is called a Strictly Binary Tree if every nonleaf node in a binary tree has nonempty left and right subtrees. Let us define a Strictly Binary Tree of depth d, as a Strictly Binary Tree that has at least one root to leaf path of length d, and no root to leaf path in that tree is longer than d. So let us use a similar reasoning to define a generalized structure.

An n-ary Tree is called a Strictly n-ary Tree if every nonleaf node in an n-ary tree has n children each. A Strictly n-ary Tree of depth d can now be defined as a Strictly n-ary Tree that has at least one root to leaf path of length d, and no root to leaf path in that tree is longer than d.

Given the value of n and depth d, your task is to find the number of different strictly n-ary trees of depth d.

The figure below shows the 3 different strictly binary trees of depth 2.

Input

Input consists of several test cases. Each test case consists of two integers n (0 < n <= 32), d (0 <= d <= 16). Input is terminated a test case where n=0 and d=0, you must not process this test case.

Output

For each test case, print three integers, n, d and the number of different strictly n-ary trees of level d, in a single line. There will be a single space in between two integers of a line. You can assume that you would not be asked about cases where you had to consider trees that may have more than 210 nodes in a level of the tree. You may also find it useful to know that the answer for each test case will always fit in a 200 digit integer.

Example

Input:
2 0
2 1
2 2
2 3
3 5
0 0

Output:
2 0 1
2 1 1
2 2 3
2 3 21
3 5 58871587162270592645034001

Added by:Nguyen Van Quang Huy
Date:2006-02-14
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS
Resource:acm.uva.es









SPOJ Problem Set (classical)

739. The Moronic Cowmpouter

Problem code: NEG2

Inexperienced in the digital arts, the cows tried to build a calculating engine (yes, it's a cowmpouter) using binary numbers (base 2) but instead built one based on base negative 2! They were quite pleased since numbers expressed in base -2 do not have a sign bit.

You know number bases have place values that start at 1 (base to the 0 power) and proceed right-to-left to base^1, base^2, and so on. In base -2, the place values are 1, -2, 4, -8, 16, -32, ... (reading from right to left). Thus, counting from 1 goes like this: 1, 110, 111, 100, 101, 11010, 11011, 11000, 11001, and so on.

Eerily, negative numbers are also represented with 1's and 0's but no sign. Consider counting from -1 downward: 11, 10, 1101, 1100, 1111, and so on.

Please help the cows convert ordinary decimal integers (range -2,000,000,000 .. 2,000,000,000) to their counterpart representation in base -2.

Input

A single integer to be converted to base -2

Output

A single integer with no leading zeroes that is the input integer converted to base -2. The value 0 is expressed as 0, with exactly one 0.

Example

Input:
-13

Output:
110111

Added by:Nguyen Van Quang Huy
Date:2006-02-15
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:USACO FEB06 Bronze Division









SPOJ Problem Set (classical)

740. Treats for the Cows

Problem code: TRT

FJ has purchased N (1 <= N <= 2000) yummy treats for the cows who get money for giving vast amounts of milk. FJ sells one treat per day and wants to maximize the money he receives over a given period time. The treats are interesting for many reasons:

Given the values v(i) of each of the treats lined up in order of the index i in their box, what is the greatest value FJ can receive for them if he orders their sale optimally?

The first treat is sold on day 1 and has age a=1. Each subsequent day increases the age by 1.

Input

Line 1: A single integer, N

Lines 2..N+1: Line i+1 contains the value of treat v(i)

Output

The maximum revenue FJ can achieve by selling the treats

Example

Input:
5
1
3
1
5
2

Output:
43

Added by:Nguyen Van Quang Huy
Date:2006-02-15
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:USACO FEB06 Gold Division









SPOJ Problem Set (classical)

741. Steady Cow Assignment

Problem code: STEAD

Farmer John's N (1 <= N <= 1000) cows each reside in one of B (1 <= B <= 20) barns which, of course, have limited capacity. Some cows really like their current barn, and some are not so happy.

FJ would like to rearrange the cows such that the cows are as equally happy as possible, even if that means all the cows hate their assigned barn.

Each cow gives FJ the order in which she prefers the barns. A cow's happiness with a particular assignment is her ranking of her barn. Your job is to find an assignment of cows to barns such that no barn's capacity is exceeded and the size of the range (i.e., one more than the positive difference between the the highest-ranked barn chosen and that lowest-ranked barn chosen) of barn rankings the cows give their assigned barns is as small as possible.

Input

Line 1: Two space-separated integers, N and B

Lines 2..N+1: Each line contains B space-separated integers which are exactly 1..B sorted into some order. The first integer on line i+1 is the number of the cow i's top-choice barn, the second integer on that line is the number of the i'th cow's second-choice barn, and so on.

Line N+2: B space-separated integers, respectively the capacity of the first barn, then the capacity of the second, and so on. The sum of these numbers is guaranteed to be at least N.

Output

One integer, the size of the minimum range of barn rankings the cows give their assigned barns, including the endpoints

Example

Input:
6 4
1 2 3 4
2 3 1 4
4 2 3 1
3 1 2 4
1 3 4 2
1 4 2 3
2 1 3 2

Output:
2

Added by:Nguyen Van Quang Huy
Date:2006-02-16
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:USACO FEB06 Gold Division









SPOJ Problem Set (classical)

744. Longest Permutation

Problem code: LPERMUT


You are given a sequence A of n integer numbers (1<=Ai<=n). A subsequence of A has the form Au, Au+1 ... , Av (1<=u<=v<=n). We are interested in subsequences that are permutations of 1, 2, .., k (k is the length of the subsequence).

Your task is to find the longest subsequence of this type.

Input

Output

A single integer that is the length of the longest permutation

Example

Input:
5
4 1 3 1 2

Output:
3

Added by:Duc
Date:2006-02-20
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:A problem put forward by Mr Mircea Pasoi









SPOJ Problem Set (classical)

757. Thermal Luminescence

Problem code: TEM

After many years of hard work a group of scientists developed a shiny new state-of-the-art processor with a 3D configuration. Due to the high clock frequency at which this processor works, the silicon cube uses up too much energy. Even with its powerful cooling system, the processor is unable to cope with the heat discharge in some of its cubical blocks. With the help of special analysis methods, scientists have developed the overheat rate for each of the cubical blocks of the system. As it conveniently happens, this overheat rate is an integer value, either positive or negative depending on many factors (such as the proximity of ventilators, refrigerators, etc.).

Science can do no more, so now the developers of the processor need your support. For a given three-dimensional matrix representing the overheat rate of elements of the processor, you have to find a submatrix for which the sum of overheat rates coming from all its elements is maximal.

Input

t – number of test cases [t <= 99], then t tests follow.
Each test begins with 3 integers: x, y, z – the width, length and height of matrix [5 <= x, y, z <= 50]. Then there follows the description of x rectangular 2D matrixes of height y and width z. In total there are x*y*z integers, which absolute value does not exceed 10000.

Output

For each test case you should output 6 integers: x1, y1, z1, x2, y2, z2, where each triple (xi, yi, zi) defines one of the two opposite corners of submatrix, resulting in the maximum overheat. [1 <= x1 <= x2 <= x] [1 <= y1 <= y2 <= y] [1 <= z1 <= z2 <= z]

Example

Input:
1
5 5 5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
-1 -1 -10 -1 -1
-1 -1 -10 -1 -1
-1 -1 -10 -1 -1
-1 -1 -10 -1 -1
-1 -1 -10 -1 -1
20 2 2 2 20
20 2 2 2 20
20 2 2 2 20
20 2 2 2 20
20 2 2 2 20
5 5 5 5 5
5 5 5 5 5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
-10 10 -10 10 -10
-10 10 -10 10 -10
-10 10 -10 10 -10
-10 10 -10 10 -10
-10 10 -10 10 -10


Output:
3 1 1 4 5 5 

Note:
The maximum overheat for the example is equal to 295.

Added by:Roman Sol
Date:2005-04-11
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ZCon 2006









SPOJ Problem Set (classical)

760. Convex Hull 3D

Problem code: CH3D


Bytelandian scientists have developed a brand new method for determining the volume of a person's lungs. The idea is simple: the patient is asked to inhale a sufficiently large number of nanobots, which then transmit their exact 3D-coordinates to an external sensor. Early clinical tests proved rather fun (especially for the scientists who were watching the process of nanobot inhalation), but gave rise to several problems of an algorithmic nature. In other words, nobody had any idea of how the volume of the lungs should be determined afterwards. A lung consists of a large number of disjoint alveoli (which can for our purposes be regarded as little hollows), and inhaled nanobots tend to float around aimlessly within the alveolus they happened to fall into. Whereas it is relatively simple to distinguish between different alveoli, establishing the volume of a single alveolus is a tough task.

One way to estimate the shape and volume of an alveolus is to smear all nanobots with a little liquid glue and see what they end up stuck to. Another (arguably more humane) method is to calculate the convex hull of the set of points representing nanobot coordinates, its volume and surface area. A convex hull of given set of points in 3D is the convex set of minimum volume which contains all these points.

Lung 1
arrow
Lung 2
arrow
Lung 3

Input

t – number of test cases [t <= 100], then t tests follow.
Each test starts with integer N - the number of given points [10 <= N <= 1000]. Then exactly N lines follow with 3 real numbers Xi, Yi, Zi in each of them, where [-10.0 <= Xi, Yi, Zi <= 10.0].

Output

For each test case you should output 2 real numbers: the surface area and volume of the hull with precision 0.01.

Example

Input:
1
10
0.00000 0.00000 0.00000
1.00000 0.00000 0.00000
0.00000 1.00000 0.00000
0.00000 0.00000 1.00000
1.00000 1.00000 0.00000
1.00000 0.00000 1.00000
0.00000 1.00000 1.00000
1.00000 1.00000 1.00000
0.50000 0.50000 0.50000
0.66666 0.77777 0.88888

Output:
6.0000 1.0000


Added by:Roman Sol
Date:2005-11-28
Time limit:8s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ZCon 2006









SPOJ Problem Set (classical)

780. The Archipelago

Problem code: ARCHPLG


Byteland is a country located in the Archipelago of Rectangular Islands. The archipelago consists of 1<=n<=1000 islands. A fact that each island has a rectangular shape is very nice for Bytelandian cartographers.

Bytelandian islands are rather small and none are very fertile, so each of (rectangular of course) pieces of cultivated land is under special control, simply speaking: ‘never enter there to save your life’. Other areas are guaranteed to be free accessible for the people.

The communication between islands is possible by ferries. On each island there is 0<=b<=10 terminals, from where crossings to another terminals on other islands are possible. It is known that total number of crossing connections is 0<=m<=100000. Other infrastructure is practically unknown. Specifically the only possible way of traveling through the island is to do it on foot.

Well, now we are close to a task you are requested to solve. John – one of the Bytelandian citizens is working as a sales manager. Simply speaking he is often requested to travel from one place to another, what he rather dislike and preferably (like other Bytelandian people use to do) he would like to spent more time in one of the beach clubs playing Puto (a kind of strategic game, very popular in Byteland). Please help him to find a way to spare his time.

Task

Find one of the fastest ways for John using ferries and foot paths on islands. Assume that while walking John is always moving one BM (Bytelandian unit of length) per BH (Bytelandian unit of time). You can also assume that the ferry departures nearly immediately after John arrives the terminal, it will be enough to round up the walking time to the nearest integer.

Input

In the first line t - the number of tests, then for each test: in next line n - the number of islands. Description of each island is as follows:

name
w h [island dimensions]
b - [number of terminals]
[description of each terminal in a form:]
name x y [name of a terminal and its coordinates]
F [number of restricted areas F<20]
xl, yd, xr, yu [coordinates of each restricted area,
0 <=xl < xr<=250 0<=yd < yu<=250.]

All coordinates are nonnegative integers measured in BM according to upper left corner of an island.

You can assume that any two restricted areas are disjoint. After the description of all islands all ferry connections are given (each connection is bi-directional).

m  [number of connections]
[description of each connection]
NB1 NW1 NB2 NW2 time [name of a first terminal, its island, the second respectively
and communiaction time]
...
[description follows]
...
NBS NWS NBC NWC [start and goal terminal for John]

Output

For each test describe the shortest route for John from terminal NBS on NWS island to terminal NBC on NWC island in the following format:

case nr Y [nr - test number]
T [travel time in BH]
NBS  NWS
...
[consecutive terminals]
...
NBC NWC
[empty line]
[consecutive tests]

If two consecutive terminals are located on the same island and John must take some walk you must give all middle point like in an example.

Example

Input:
1
3
W1
8 7
2
Lindos 4 0
Kamejros 4 7
3
2 1 6 2
2 3 6 4 
2 5 6 6 
W2
14 12
2
Malia 14 1
Knossos 1 12
5
2 6 10 10
11 1 12 6
8 1 10 5
11 7 12 9
3 2 5 4
W3 
1 1
1
Korkyra 0 0
0
2
Kamejros W1 Knossos W2 100
Malia W2 Korkyra W3 100
Korkyra W3 Lindos W1

An example of a correct answer:

Output:
case 1 Y
230
Korkyra W3
Malia W2
12 6
11 7
10 10
Knossos W2
Kamejros W1
2 6
2 1
Lindos W1

Added by:£ukasz Kuszner
Date:2006-03-15
Time limit:40s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: NODEJS PERL 6
Resource:GUT Algorithm Analysis 2005









SPOJ Problem Set (classical)

827. Trigonometric optimization

Problem code: TRIOPT


Many problems arising in practical applications may be stated as optimization problems. Usually it is necessary to maximize or minimize so called criterion function taking into account some constraints.

Let’s consider a trigonometric optimization problem. It is necessary to maximize or to minimize criterion function F1(x) + F2(y) + F3(z) with constraint x + y + z = S, where x, y, z – variables, S – parameter, x, y, z, S - natural numbers. Each of the functions F1, F2 and F3 is a trigonometric function sin or cos.

You need to write a program which solves the trigonometric optimization problem.

Input

The first line of the input data contains integer T (1 ≤ T ≤ 65) - the number of testcases. Then the descriptions of T testcases follow.

The description of each testcase consists of 5 lines. The first line describes function F1 and contains either sin or cos. The second and the third lines describe functions F2 and F3 respectively and have the same format as the first line. Next, the fourth line contains either min or max. If the line contains min than it is necessary to minimize criterion function, otherwise it is necessary to maximize criterion function. Finally, the fifth line contains parameter S value (3 ≤ S ≤ 1 000 000).

Output

For each testcase you should output one line into the output data. This line should contain one real number – the found value of the criterion function. Absolute error of your answer must not exceed 10-10.

Example

Input:
1
sin
cos
sin
max
10

Output:
2.7787651403

Added by:Ivan Metelsky
Date:2006-04-27
Time limit:90s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:NEERC Western Subregion QF 2005









SPOJ Problem Set (classical)

839. Optimal Marks

Problem code: OPTM


You are given an undirected graph G(V, E). Each vertex has a mark which is an integer from the range [0..231 – 1]. Different vertexes may have the same mark.

For an edge (u, v), we define Cost(u, v) = mark[u] xor mark[v].

Now we know the marks of some certain nodes. You have to determine the marks of other nodes so that the total cost of edges is as small as possible.

Input

The first line of the input data contains integer T (1 ≤ T ≤ 10) - the number of testcases. Then the descriptions of T testcases follow.

First line of each testcase contains 2 integers N and M (0 < N <= 500, 0 <= M <= 3000). N is the number of vertexes and M is the number of edges. Then M lines describing edges follow, each of them contains two integers u, v representing an edge connecting u and v.

Then an integer K, representing the number of nodes whose mark is known. The next K lines contain 2 integers u and p each, meaning that node u has a mark p. It’s guaranteed that nodes won’t duplicate in this part.

Output

For each testcase you should print N lines integer the output. The Kth line contains an integer number representing the mark of node K. If there are several solutions, you have to output the one which minimize the sum of marks. If there are several solutions, just output any of them.

Example

Input:
1
3 2
1 2
2 3
2
1 5
3 100

Output:
5
4
100 

Added by:Thanh-Vy Hua
Date:2006-05-05
Time limit:6s
Source limit:10000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Guo HuaYang









SPOJ Problem Set (classical)

850. Soccer Choreography

Problem code: WM06

Mr. Bitmann, the coach of the national soccer team of Bitland, is a perfectionist. He taught his players optimal tactics and improved their endurance and shape. So they qualified for the soccer woldcup this year. Due to his perfectionism the coach attaches importance not only to the performance in the game but also before the game. So he told the team captain in what formation the team should assemble before the national anthem is played. Since each of the 11 team members has a unique number between 1 and 11 on his shirt, he can represent the formation as a permutation of numbers.

Before the first game the coach told the captain that the team should line up in increasing order (picture (d)). But some players forgot the ordering and the orientation of the formation like in picture (a). Only player 1 has the right orientation. The coach went nearly mad when he saw this desaster! How could he solve the problem?

scenario example

"Hmmm... I'll let my players dance!". A great idea! He took his notebook and started to create a choreography which leads to his expected formation. Due to the fact that no one of the players took dancing lessons he restricts his dance to one basic move: One player or more players who stand side by side can turn 180 degrees around the center of the move. Picture (b) contains an example: The players

-11 -10 -9 -2

(we mark players which stand in the wrong direction with a minus) can do one move to

2 9 10 11

As perfect as he is he calculated a dance with a minimum number of moves. It works perfectly and now he's planning to do dancing performances with teams with more than 11 members. So he needs your help to find optimal dancing moves...

Input

Each testcase starts with the number of team members n (0<=n< 2200). The next lines represent the formation at the beginning and the expected formation at the end of the choreography.

Output

For each testcase output m, the minimal number of moves which are necessary to reach the expected formation. The next m+1 lines should represent one possible scenario of moves.

Example

Input:
11
-5 -4 -3 -8 -7 -6 1 -11 -10 -9 -2
1 2 3 4 5 6 7 8 9 10 11
11
1 2 3 -4 -5 -6 -7 -8 -9 10 11
11 9 8 7 6 5 4 3 2 10 1
0

Output:
3 Steps
-5 -4 -3 -8 -7 -6 +1 -11 -10 -9 -2
-5 -4 -3 -8 -7 -6 +1 +2 +9 +10 +11
-5 -4 -3 -2 -1 +6 +7 +8 +9 +10 +11
+1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11
5 Steps
+1 +2 +3 -4 -5 -6 -7 -8 -9 +10 +11
+1 +2 -3 -4 -5 -6 -7 -8 -9 +10 +11
+1 -2 -3 -4 -5 -6 -7 -8 -9 +10 +11
+1 -2 -3 -4 -5 -6 -7 -8 -9 -11 -10
+11 +9 +8 +7 +6 +5 +4 +3 +2 -1 -10
+11 +9 +8 +7 +6 +5 +4 +3 +2 +10 +1

Added by:Simon Gog
Date:2006-05-11
Time limit:20s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









SPOJ Problem Set (classical)

861. Counting inversions

Problem code: SWAPS

You are given a sequence A of N (N≤250000) integers between 1 and 50000. On this sequence you have to apply M (M≤10000) operations of the form: modify the i-th element in the sequence and then say how many inversions are there in the sequence. The number of inversions in a sequence is given by the number of pairs (i,j) with i < j and Ai > Aj.

Input

The first line of input contains the number N and the next line contains the numbers that form the sequence. After that follows the number M and then M lines, each containig 2 integers X and Y, meaning that new value of the X-th element of the sequence is Y and that you should count the number of inversions in the modified sequence.

Output

Output must contain M lines, the i-th line of output containg the number of inversions in the sequence after the first i operations.

Example

Input:
10
2 6 6 4 7 6 3 5 9 1 
7
8 8
5 1
5 6
10 5
7 1
10 10
4 6

Output:
17
18
16
13
14
8
6


Added by:Gogu Marian
Date:2006-05-31
Time limit:1s-5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:









SPOJ Problem Set (classical)

866. DNA Translation

Problem code: DNA


Deoxyribonucleic acid (DNA) is composed of a sequence of nucleotide bases paired together to form a double-stranded helix structure. Through a series of complex biochemical processes the nucleotide sequences in an organism's DNA are translated into the proteins it requires for life. The object of this problem is to write a computer program which accepts a DNA strand and reports the protein generated, if any, from the DNA strand.

The nucleotide bases from which DNA is built are adenine, cytosine, guanine, and thymine (hereafter referred to as A, C, G, and T, respectively). These bases bond together in a chain to form half of a DNA strand. The other half of the DNA strand is a similar chain, but each nucleotide is replaced by its complementary base. The bases A and T are complementary, as are the bases C and G. These two "half-strands" of DNA are then bonded by the pairing of the complementary bases to form a strand of DNA.

Typically a DNA strand is listed by simply writing down the bases which form the primary strand (the complementary strand can always be created by writing the complements of the bases in the primary strand). For example, the sequence TACTCGTAATTCACT represents a DNA strand whose complement would be ATGAGCATTAAGTGA. Note that A is always paired with T, and C is always paired with G.

From a primary strand of DNA, a strand of ribonucleic acid (RNA) known as messenger RNA (mRNA for short) is produced in a process known as transcription. The transcribed mRNA is identical to the complementary DNA strand with the exception that thymine is replaced by a nucleotide known as uracil (hereafter referred to as U). For example, the mRNA strand for the DNA in the previous paragraph would be AUGAGCAUUAAGUGA.

It is the sequence of bases in the mRNA which determines the protein that will be synthesized. The bases in the mRNA can be viewed as a collection of codons, each codon having exactly three bases. The codon AUG marks the start of a protein sequence, and any of the codons UAA, UAG, or UGA marks the end of the sequence. The one or more codons between the start and termination codons represent the sequence of amino acids to be synthesized to form a protein. For example, the mRNA codon AGC corresponds to the amino acid serine (Ser), AUU corresponds to isoleucine (Ile), and AAG corresponds to lysine (Lys). So, the protein formed from the example mRNA in the previous paragraph is, in its abbreviated form, Ser-Ile-Lys.

The complete genetic code from which codons are translated into amino acids is shown in the table below (note that only the amino acid abbreviations are shown). It should also be noted that the sequence AUG, which has already been identified as the start sequence, can also correspond to the amino acid methionine (Met). So, the first AUG in a mRNA strand is the start sequence, but subsequent AUG codons are translated normally into the Met amino acid.

First base in codon Second base in codon Third base in codon
UCAG
U PheSerTyrCysU
PheSerTyrCysC
LeuSer------A
LeuSer---TrpG
C LeuProHisArgU
LeuProHisArgC
LeuProGlnArgA
LeuProGlnArgG
A IleThrAsnSerU
IleThrAsnSerC
IleThrLysArgA
MetThrLysArgG
G ValAlaAspGlyU
ValAlaAspGlyC
ValAlaGluGlyA
ValAlaGluGlyG

The input for this program consists of strands of DNA sequences, one strand per line, from which the protein it generates, if any, should be determined and output. The given DNA strand may be either the primary or the complementary DNA strand, and it may appear in either forward or reverse order, and the start and termination sequences do not necessarily appear at the ends of the strand. For example, a given input DNA strand to form the protein Ser-Ile-Lys could be any of ATACTCGTAATTCACTCC, CCTCACTTAATGCTCATA, TATGAGCATTAAGTGAGG, or GGAGTGAATTACGAGTAT. The input file will be terminated by a line containing a single asterisk character.

You may assume the input to contain only valid, upper-case, DNA nucleotide base letters (A, C, G, and T). No input line will exceed 255 characters in length. There will be no blank lines or spaces in the input. Some sequences, though valid DNA strands, do not produce valid protein sequences; the string "*** No translatable DNA found ***" should be output when an input DNA strand does not translate into a valid protein.

Input:

ATACTCGTAATTCACTCC
CACCTGTACACAGAGGTAACTTAG
TTAATACGACATAATTAT
GCCTTGATATGGAGAACTCATTAGATA
AAGTGTATGTTGAATTATATAAAACGGGCATGA
ATGATGATGGCTTGA
*
Output:

Ser-Ile-Lys
Cys-Leu-His
Ser-Tyr
*** No translatable DNA found ***
Leu-Asn-Tyr-Ile-Lys-Arg-Ala
Met-Met-Ala

Added by:Wanderley Guimarães
Date:2006-06-01
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS
Resource:ACM Mid Central Regionals 1995









SPOJ Problem Set (classical)

867. Perfect Cubes

Problem code: CUBES


For hundreds of years Fermat's Last Theorem, which stated simply that for n > 2 there exist no integers a, b, c > 1 such that a^n = b^n + c^n, has remained elusively unproven. (A recent proof is believed to be correct, though it is still undergoing scrutiny.) It is possible, however, to find integers greater than 1 that satisfy the "perfect cube" equation a^3 = b^3 + c^3 + d^3 (e.g. a quick calculation will show that the equation 12^3 = 6^3 + 8^3 + 10^3 is indeed true). This problem requires that you write a program to find all sets of numbers {a,b,c,d} which satisfy this equation for a <= 100.

The output should be listed as shown below, one perfect cube per line, in non-decreasing order of a (i.e. the lines should be sorted by their a values). The values of b, c, and d should also be listed in non-decreasing order on the line itself. There do exist several values of a which can be produced from multiple distinct sets of b, c, and d triples. In these cases, the triples with the smaller b values should be listed first.

Note that the programmer will need to be concerned with an efficient implementation. The official time limit for this problem is 2 minutes, and it is indeed possible to write a solution to this problem which executes in under 2 minutes on a 33 MHz 80386 machine. Due to the distributed nature of the contest in this region, judges have been instructed to make the official time limit at their site the greater of 2 minutes or twice the time taken by the judge's solution on the machine being used to judge this problem.

The first part of the output is shown here:

Cube = 6, Triple = (3,4,5)
Cube = 12, Triple = (6,8,10)
Cube = 18, Triple = (2,12,16)
Cube = 18, Triple = (9,12,15)
Cube = 19, Triple = (3,10,18)
Cube = 20, Triple = (7,14,17)
Cube = 24, Triple = (12,16,20)

Added by:Wanderley Guimarães
Date:2006-06-01
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 1995









SPOJ Problem Set (classical)

869. Galactic Import

Problem code: IMPORT


With the introduction of the new ThrustoZoom gigadimensional drive, it has become possible for HyperCommodities, the import/export conglomerate from New Jersey, to begin trading with even the most remote galaxies in the universe. HyperCommodities wants to import goods from some of the galaxies in the Plural Z sector. Planets within these galaxies export valuable products and raw materials like vacuuseal, transparent aluminum, digraphite, and quantum steel. Preliminary reports have revealed the following facts:

HyperCommodities has assigned a relative value (a positive real number less than 10) to each planet's chief export. The higher the number, the more valuable the product. More valuable products can be resold with a higher profit margin in domestic markets. The problem is to determine which planet has the most valuable export when shipping fees are taken into account.

The input consists of one or more galaxy descriptions. Each galaxy description begins with a line containing an integer N which specifies the number of planets in the galaxy. The next N lines contain descriptions of each planet, which consist of:

  1. The letter used to represent the planet.

  2. A space.

  3. The relative value of the planet's export, in the form d.dd.

  4. A space.

  5. A string containing letters and/or the character `*'; a letter indicates a shipping line to that planet, and a `*' indicates a willingness to open a ThrustoZoom shipping line to Earth.

For each galaxy description, output a single line which reads "Import from P" where P is the letter of the planet with the most valuable export, once shipping fees have been taken into account. (If more than one planet have the same most valuable export value then output the plant which is alphabetically first).

A sample input file is shown here:

1
F 0.81 *
5
E 0.01 *A
D 0.01 A*
C 0.01 *A
A 1.00 EDCB
B 0.01 A*
10
S 2.23 Q*
A 9.76 C
K 5.88 MI
E 7.54 GC
M 5.01 OK
G 7.43 IE
I 6.09 KG
C 8.42 EA
O 4.55 QM
Q 3.21 SO

The following output file should be produced from the above sample input:

Import from F
Import from A
Import from A

Added by:Wanderley Guimarães
Date:2006-06-01
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 1995









SPOJ Problem Set (classical)

870. Basically Speaking

Problem code: BASE

The Really Neato Calculator Company, Inc. has recently hired your team to help design their Super Neato Model I calculator. As a computer scientist you suggested to the company that it would be neato if this new calculator could convert among number bases. The company thought this was a stupendous idea and has asked your team to come up with the prototype program for doing base conversion. The project manager of the Super Neato Model I calculator has informed you that the calculator will have the following neato features:

The input for your prototype program will consist of one base conversion per line. There will be three numbers per line. The first number will be the number in the base you are converting from. The second number is the base you are converting from. The third number is the base you are converting to. There will be one or more blanks surrounding (on either side of) the numbers. There are several lines of input and your program should continue to read until the end of file is reached.

The output will only be the converted number as it would appear on the display of the calculator. The number should be right justified in the 7-digit display. If the number is to large to appear on the display, then print ``ERROR'' (without the quotes) right justified in the display.

A sample input file is shown here:

1111000  2 10
1111000  2 16
2102101  3 10
2102101  3 15
  12312  4  2
     1A 15  2
1234567 10 16
   ABCD 16 15

The following output file should be produced from the above sample input:

    120
     78
   1765
    7CA
  ERROR
  11001
 12D687
   D071

Added by:Wanderley Guimarães
Date:2006-06-01
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 1995









SPOJ Problem Set (classical)

871. Letter Sequence Analysis

Problem code: SEQUENCE

Cryptographic analysis makes extensive use of the frequency with which letters and letter sequences occur in a language. If an encrypted text is known to be in english, for example, a great deal can be learned from the fact that the letters E, L, N, R, S, and T are the most common ones used in written english. Even more can be learned if common letter pairs, triplets, etc. are known.

For this problem you are to write a program which accepts as input a text file of unspecified length and performs letter sequence analysis on the text. The program will report the five most frequent letter sequences for each set of sequences from one to five letters. That is it will report the individual characters which occur with the five highest frequencies, the pairs of characters which occur with the five highest frequencies, and so on up to the letter sequences of five characters which occur with the five highest frequencies.

The program should consider contiguous sequences of alphabetic characters only, and case should be ignored (e.g. an `a' is the same as an `A'). A report should be produced using the format shown in the example at the end of this problem description. For each sequence length from one to five, the report should list the sequences in descending order of frequency. If there are several sequences with the same frequency then all sequences should be listed in alphabetical order as shown (list all sequences in upper case). Finally, if there are less than five distinct frequencies for a particular sequence length, simply report as many distinct frequency lists as possible.

When a text file containing simply the line ``Peter Piper Picks Pickles!'' is used as input, the output should appear as shown here:

Analysis for Letter Sequences of Length 1
-----------------------------------------
Frequency = 5, Sequence(s) = (P)
Frequency = 4, Sequence(s) = (E)
Frequency = 3, Sequence(s) = (I)
Frequency = 2, Sequence(s) = (C,K,R,S)
Frequency = 1, Sequence(s) = (L,T)

Analysis for Letter Sequences of Length 2
-----------------------------------------
Frequency = 3, Sequence(s) = (PI)
Frequency = 2, Sequence(s) = (CK,ER,IC,PE)
Frequency = 1, Sequence(s) = (ES,ET,IP,KL,KS,LE,TE)

Analysis for Letter Sequences of Length 3
-----------------------------------------
Frequency = 2, Sequence(s) = (ICK,PIC)
Frequency = 1, Sequence(s) = (CKL,CKS,ETE,IPE,KLE,LES,PER,PET,PIP,TER)

Analysis for Letter Sequences of Length 4
-----------------------------------------
Frequency = 2, Sequence(s) = (PICK)
Frequency = 1, Sequence(s) = (CKLE,ETER,ICKL,ICKS,IPER,KLES,PETE,PIPE)

Analysis for Letter Sequences of Length 5
-----------------------------------------
Frequency = 1, Sequence(s) = (CKLES,ICKLE,PETER,PICKL,PICKS,PIPER)
When the first three paragraphs of this problem description are used as input, the output should appear as shown here:

Analysis for Letter Sequences of Length 1
-----------------------------------------
Frequency = 201, Sequence(s) = (E)
Frequency = 112, Sequence(s) = (T)
Frequency = 96, Sequence(s) = (S)
Frequency = 90, Sequence(s) = (R)
Frequency = 84, Sequence(s) = (N)

Analysis for Letter Sequences of Length 2
-----------------------------------------
Frequency = 37, Sequence(s) = (TH)
Frequency = 33, Sequence(s) = (EN)
Frequency = 27, Sequence(s) = (HE)
Frequency = 24, Sequence(s) = (RE)
Frequency = 23, Sequence(s) = (NC)

Analysis for Letter Sequences of Length 3
-----------------------------------------
Frequency = 24, Sequence(s) = (THE)
Frequency = 21, Sequence(s) = (ENC,EQU,QUE,UEN)
Frequency = 12, Sequence(s) = (NCE,SEQ,TER)
Frequency = 9, Sequence(s) = (CES,FRE,IVE,LET,REQ,TTE)
Frequency = 8, Sequence(s) = (ETT,FIV)

Analysis for Letter Sequences of Length 4
-----------------------------------------
Frequency = 21, Sequence(s) = (EQUE,QUEN)
Frequency = 20, Sequence(s) = (UENC)
Frequency = 12, Sequence(s) = (ENCE,SEQU)
Frequency = 9, Sequence(s) = (FREQ,NCES,REQU)
Frequency = 8, Sequence(s) = (ETTE,FIVE,LETT,TTER)

Analysis for Letter Sequences of Length 5
-----------------------------------------
Frequency = 21, Sequence(s) = (EQUEN)
Frequency = 20, Sequence(s) = (QUENC)
Frequency = 12, Sequence(s) = (SEQUE,UENCE)
Frequency = 9, Sequence(s) = (ENCES,FREQU,REQUE)
Frequency = 8, Sequence(s) = (ETTER,LETTE)

Added by:Wanderley Guimarães
Date:2006-06-01
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 1995









SPOJ Problem Set (classical)

872. Mark-up

Problem code: MARKUP

Mark-up languages are computer languages that assist in the formatting of text files. Special keywords are used to mark the text to allow control of fonts, page styles, paragraph styles, etc. TeX, troff, and HTML are examples of mark-up languages.

Spell checking can be difficult to adapt to these special texts. In general, special processors or spell checkers must be created in order to accommodate mark-up languages. A special processor would recognize the mark-up language and strip it from the text so that the ``plain'' text could then be processed by a spell checker. For this problem, you are to write such a processor for a small mark-up language so that the output of your program will be the plain text without the mark-ups.

The mark-up language to consider is one which allows the modification of fonts within the text. Each markup command will be preceded by a \ character. If the letter following the \ character is not a recognized command from the table below then the character following the \ is printed as part of the plain text. For instance, the mark-up \\ can be used to print a single \.

\b
toggle bold font on/off (default state is off)
\i
toggle italics font on/off (default state is off)
\s
set font size; the s is immediately followed by an optional number; if the number is missing then the command will restore the previous size
\*
toggle processing of mark-ups on/off; if processing is toggle off then mark-ups are considered to be literal text (default state is on)
The number following the \s command can have a decimal point so 12, 9.5, 11., and .5 should all be recognized as valid numbers.

The input file will be plain text containing mark-ups from the language above. At the start, processing of mark-ups should be on. The file should be processed until the end-of-file is encountered.

A sample input file is shown here:

\s18.\bMARKUP sample\b\s

\*For bold statements use the \b command.\*

If you wish to \iemphasize\i something use the \\i command.

For titles use \s14BIG\s font sizes, 14 points usually works well.

Remember that all of the commands toggle except for the \\s command.

The following output file should be produced from the above sample input:

MARKUP sample

For bold statements use the \b command.

If you wish to emphasize something use the \i command.

For titles use BIG font sizes, 14 points usually works well.

Remember that all of the commands toggle except for the \s command.

Added by:Wanderley Guimarães
Date:2006-06-01
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:1995 ACM Mid-Central Programming Contest









SPOJ Problem Set ()

898. Transmitters

Problem code: TRANSMIT

In a wireless network with multiple transmitters sending on the same frequencies, it is often a requirement that signals don't overlap, or at least that they don't conflict. One way of accomplishing this is to restrict a transmitter's coverage area. This problem uses a shielded transmitter that only broadcasts in a semicircle.

A transmitter T is located somewhere on a 1,000 square meter grid. It broadcasts in a semicircular area of radius r. The transmitter may be rotated any amount, but not moved. Given N points anywhere on the grid, compute the maximum number of points that can be simultaneously reached by the transmitter's signal. Figure 1 shows the same data points with two different transmitter rotations.

All input coordinates are integers (0-1000). The radius is a positive real number greater than 0. Points on the boundary of a semicircle are considered within that semicircle. There are 1-150 unique points to examine per transmitter. No points are at the same location as the transmitter.

Input consists of information for one or more independent transmitter problems. Each problem begins with one line containing the (x,y) coordinates of the transmitter followed by the broadcast radius, r. The next line contains the number of points N on the grid, followed by N sets of (x,y) coordinates, one set per line. The end of the input is signalled by a line with a negative radius; the (x,y) values will be present but indeterminate. Figures 1 and 2 represent the data in the first two example data sets below, though they are on different scales. Figures 1a and 2 show transmitter rotations that result in maximal coverage.

For each transmitter, the output contains a single line with the maximum number of points that can be contained in some semicircle.

Input:
25 25 3.5
7
25 28
23 27
27 27
24 23
26 23
24 29
26 29
350 200 2.0
5
350 202
350 199
350 198
348 200
352 200
995 995 10.0
4
1000 1000
999 998
990 992
1000 999
100 100 -2.5
Output:
3
4
4

Added by:Wanderley Guimarães
Date:2006-06-09
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:ACM Mid Central Regionals 2001









SPOJ Problem Set (classical)

899. Ws Cipher

Problem code: WSCIPHER

Weird Wally's Wireless Widgets, Inc. manufactures an eclectic assortment of small, wireless, network capable devices, ranging from dog collars, to pencils, to fishing bobbers. All these devices have very small memories. Encryption algorithms like Rijndael, the candidate for the Advanced Encryption Standard (AES) are demonstrably secure but they don't fit in such a tiny memory. In order to provide some security for transmissions to and from the devices, WWWW uses the following algorithm, which you are to implement.

Encrypting a message requires three integer keys, k1, k2, and k3. The letters [a-i] form one group, [j-r] a second group, and everything else ([s-z] and underscore) the third group. Within each group the letters are rotated left by ki positions in the message. Each group is rotated independently of the other two. Decrypting the message means doing a right rotation by ki positions within each group.

Consider the message the_quick_brown_fox encrypted with ki values of 2, 3 and 1. The encrypted string is _icuo_bfnwhoq_kxert. The figure below shows the decrypting right rotations for one character in each of the three character groups.

Looking at all the letters in the group [a-i] we see {i,c,b,f,h,e} appear at positions {2,3,7,8,11,17} within the encrypted message. After a right rotation of k1=2, these positions contain the letters {h,e,i,c,b,f}. The table below shows the intermediate strings that come from doing all the rotations in the first group, then all rotations in the second group, then all the rotations in the third group. Rotating letters in one group will not change any letters in any of the other groups.

[a-i], k1= 2 [j-r], k2= 3 [s-z] and _, k3= 1
Encrypted: _icuo_bfnwhoq_kxert _heuo_icnwboq_kxfrt _heuq_ickwbro_nxfot
Decrypted: _heuo_icnwboq_kxfrt _heuq_ickwbro_nxfot the_quick_brown_fox
Changes:
 ^^   ^^  ^     ^  
    ^   ^  ^^ ^  ^  
^  ^ ^   ^   ^ ^  ^  

All input strings contain only lowercase letters and underscores(_). Each string will be at most 80 characters long. The ki are all positive integers in the range 1-100.

Input consists of information for one or more encrypted messages. Each problem begins with one line containing k1, k2, and k3 followed by a line containing the encrypted message. The end of the input is signalled by a line with all key values of 0.

For each encrypted message, the output is a single line containing the decrypted string.

Input:
2 3 1
_icuo_bfnwhoq_kxert
1 1 1
bcalmkyzx
3 7 4
wcb_mxfep_dorul_eov_qtkrhe_ozany_dgtoh_u_eji
2 4 3
cjvdksaltbmu
0 0 0
Output:
the_quick_brown_fox
abcklmxyz
the_quick_brown_fox_jumped_over_the_lazy_dog
ajsbktcludmv

Added by:Wanderley Guimarães
Date:2006-06-09
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 2001









SPOJ Problem Set (classical)

900. Split Windows

Problem code: SPLIT

The Dotty Software Company makes software that is displayed on inexpensive text based terminals. One application for this system has a main window that can be subdivided into further subwindows. Your task is to take a description of the screen layout after a sequence of window splits and draw the minimum sized window grid that is consistent with the description.

In this problem we will concentrate on the boundaries of windows, so all the characters inside of windows will be left blank. Each window that is not further subdivided has a label. Each label is a distinct uppercase letter. For a text terminal the boundaries of windows must be drawn with characters, chosen as follows: A capital letter label is placed in the upper left-hand corner of each undivided window. Asterisks,'*', appear in corners of windows where there is not a label. Dashes, '-', appear on upper and lower boundaries where there are not corners. Vertical bars, '|', appear on side boundaries where there are not corners.

For example, the sequence of splits below would generate Window 1: Initially there could be an application window labeled M, that is split next into left and right subwindows, adding label R, and the left subwindow is split into top and bottom subwindows, adding the label C.

For each pattern of splits there is a binary tree of characters that can describe it. The window splitting and tree structures are described together, building up from the simplest cases.

  1. A window may be an undivided rectangle. Such a window has a capital letter as label. The tree for the window contains just the label.
  2. A window may either be split into left and right subwindows or into top and bottom subwindows, and the corresponding trees have as root the boundary character for the split: a vertical line '|' or a horizontal dash '-' respectively. The root has left and right subtrees corresponding to the top and bottom or left and right subwindows respectively.
Tree 1, above, and Trees 2-4, below, would be consistent with Windows 1-4. Note that Tree 4 contains Trees 2 and 3.

The trees may be more succinctly expressed via a preorder traversal:

  1. The preorder traversal of a tree with just one node (containing a letter) is that letter.
  2. The preorder traversal of a tree with a left and a right subtree is the character from the root of the tree ('-' or '|') followed by the preorder traversal of the left subtree, and then the preorder traversal of the right subtree.
The preorder traversals for Trees 1 through 4 are
   |-MCR    -|-ABC-D|E-FG   -P-|Q|RST    |-|-ABC-D|E-FG-P-|Q|RST

Each undivided window must have space for at least one character inside. Hence each tree of splits will be associated with a minimum window size. Windows 1-4 are minimum sized windows for Trees 1-4. Each window illustrates the fact that even in a minimum sized window, not all undivided windows contain only one character.

Consider Tree 4 and Window 4. The main window is split into a left window with Tree 2 and right window with Tree 3. The left window is like Window 2, but the right window is not just like Window 3. The heights of left and right subwindows must match, so the right window must be stretched.

The stretching rule depends on a definition of the size of windows. For dimension calculations it is easiest to imagine that a window contains its interior and a half character wide boundary on all sides, so the total dimensions of a window are one more than the dimensions of the interior. Hence the minimum dimensions of a window are 2 by 2, since a window must contain one character inside, and we add one for the boundary. This definition also means that the sum of the widths of left and right subwindows is the width of their enclosing window. The sum of the heights of top and bottom subwindows is the height of their enclosing window.

The right window in Window 4 must be stretched to match the height 10 of the left window. The right window is split into a top with tree P having minimum height 2 and a bottom with tree -|Q|RST having minimum height 4. The rule for the dimensions in the stretched window is that the heights of the subwindows expand in proportion to their minimum heights, if possible. Some symbols may help here: Let D = 10 be the height of the combined stretched window. We want to determine D1 and D2, the stretched heights of the top and bottom subwindow. Call the corresponding minimum dimensions d = 6, d1 = 2, and d2 = 4. If the window were expanded from a total height d to D in proportion, we would have D1 = d1*(D/d) = 2*(10/6) = 3.333...and D2 = d2*(D/d) = 6.666.... Since the results are not integers we increase D1 to 4 and decrease D2 to 6.

There is a similar calculation for the bottom window with tree -|Q|RST. It is further subdivided into a top with tree |Q|RS and a bottom with tree T, each having minimum height 2 = d1 = d2. The heights need to add up to D = 6, so they are increased proportionally to D1 = D2 = 2*(6/4) = 3 (exact integers).

The final dimensions of an enclosing window are always determined before the final dimensions of its subwindows. In this example only heights needed to be apportioned. If all horizontal and vertical splits were interchanged in this example, producing a tree -|-|ABC|D-E|FG|P|-Q-RST, then widths would be apportioned correspondingly, as shown in the third part of the sample output below. If the proportion calculations do not work out to integers, it is always the top or left subwindow whose dimension is increased to the next integer.

The first line of input contains one integer, which is the total number of preorder traversals describing window structures. This line is followed by one line for each preorder traversal. Each preorder traversal will contain appropriate dividers '|' and '-' and from 1 to 26 uppercase letters.

For each preorder traversal, print the number of the preorder traversal on one line followed by the minimum sized window grid that the traversal could represent. Contrary to the general contest output conventions, there may be more than one consecutive blank in this output, but the other general rules for contest output are followed. The total number of rows or columns in output grids will be no more than 53.

Input:
3
|-MCR
|-|-ABC-D|E-FG-P-|Q|RST
-|-|ABC|D-E|FG|P|-Q-RST
Output:
1
M-R-*
| | |
C-* |
| | |
*-*-*
2
A-C-P-----*
| | |     |
B-* |     |
| | |     |
D-*-Q-R-S-*
|   | | | |
E-F-* | | |
| | T-*-*-*
| G-*     |
| | |     |
*-*-*-----*
3
A-B-D-E---*
| | | |   |
C-*-* F-G-*
|   | | | |
P---Q-*T*-*
|   |  |  |
|   R--*  |
|   |  |  |
|   S--*  |
|   |  |  |
*---*--*--*

Added by:Wanderley Guimarães
Date:2006-06-09
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 2001









SPOJ Problem Set (classical)

901. Index Generation

Problem code: INDEXGEN


Most nonfiction and reference books have an index to help readers find references to specific terms or concepts in the text. Here is a sample index.

larch, 4, 237, 238, 414
+ Monty Python and, 64, 65, 66
+ planting of, 17
Lenny Kravitz, 50
+ going his way, 53
lumbago, 107
mango
+ Chris Kattan, 380
+ storage of, 87, 90
+ use in Nethack, 500, 501
+ Vitamin C content, 192

Each index entry contains a primary entry followed by zero or more secondary entries, which begin with a '+'. Entries will normally be followed by a list of page references, but a primary entry might not be if at least one secondary entry is present (as is the case with mango, above). Primary entries are sorted, and secondary entries following a primary entry are also sorted. Sorting is case-insensitive. Page references for an entry are in ascending order and do not include duplicates. (A duplicate could occur if there are two or more identical entries on the same page.)

Your task is to read a document that has index information embedded within it and produce the index. Documents consist of one or more lines of ASCII text. The page number starts at 1, and the character '&' indicates the start of a new page (which adds 1 to the current page number). Index entries are indicated by a marker, which in its most elaborate form has the following syntax:

{text%primary$secondary}

Here text is the text to be indexed, primary is an alternative primary entry, and secondary is a secondary entry. Both '%primary' and '$secondary' are optional, but if both are present they must appear in the order given. If primary is present then it is used as the primary entry, and if not then text is used as the primary entry. If secondary is present then the marker adds a page reference for that secondary entry; otherwise it adds a page reference for the primary entry. A single marker cannot add a page reference for both a primary and secondary entry. Here are examples of each of the four possible types of marker, which correspond to four of the entries in the sample index above.

... his {lumbago} was acting up, so ...
... {Lenny%Lenny Kravitz} lit up the crowd with his version of ...
... Monty Python often used the {larch$Monty Python and} in ...
... when storing {mangos%mango$storage of}, be sure to ...

The input consists of one or more documents, followed by a line containing only '**' that signals the end of the input. Documents are implictly numbered starting with 1. Each document consists of one or more lines of text followed by a line containing only '*'. Each line of text will be at most 79 characters long, not counting end-of-line characters. For document i, output the line 'DOCUMENT i' followed by the sorted index using the exact output format shown in the examples.

Be sure to read Notes to Teams, which has general formatting guidelines that pertain to all problem input files, including this one. Also note:

Input:
Call me Ishmael.
*
One {fish $unary}, two {fish$ binary},&red {fish $ scarlet}, blue {fish$
azure}. & By { Dr. Seuss }.
*
This is a {simple } & & { document} that &{
simply %simple
$adverb
} & {illustrates %vision} &&&&& one {simple-minded% simple} {Judge}'s {vision} 
for what a {document } might { look % vision} like.
*
**

Output:
DOCUMENT 1
DOCUMENT 2
Dr. Seuss, 3
fish
+ azure, 2
+ binary, 1
+ scarlet, 2
+ unary, 1
DOCUMENT 3
document, 3, 10
Judge, 10
simple, 1, 10
+ adverb, 4
vision, 5, 10

Added by:Wanderley Guimarães
Date:2006-06-09
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 2001









SPOJ Problem Set (classical)

902. Hangover

Problem code: HANGOVER

How far can you make a stack of cards overhang a table? If you have one card, you can create a maximum overhang of half a card length. (We're assuming that the cards must be perpendicular to the table.) With two cards you can make the top card overhang the bottom one by half a card length, and the bottom one overhang the table by a third of a card length, for a total maximum overhang of 1/2 + 1/3 = 5/6 card lengths. In general you can make n cards overhang by 1/2 + 1/3 + 1/4 + ... + 1/(n + 1) card lengths, where the top card overhangs the second by 1/2, the second overhangs tha third by 1/3, the third overhangs the fourth by 1/4, etc., and the bottom card overhangs the table by 1/(n + 1). This is illustrated in the figure below.

Input

The input consists of one or more test cases, followed by a line containing the number 0.00 that signals the end of the input. Each test case is a single line containing a positive floating-point number c whose value is at least 0.01 and at most 5.20; c will contain exactly three digits.

Output

For each test case, output the minimum number of cards necessary to achieve an overhang of at least c card lengths. Use the exact output format shown in the examples.

Input:
1.00
3.71
0.04
5.19
0.00
Output:
3 card(s)
61 card(s)
1 card(s)
273 card(s)

Added by:Wanderley Guimarães
Date:2006-06-09
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 2001









SPOJ Problem Set (classical)

903. Double Vision

Problem code: DOUBLEVI


The DoubleVision company designs inks and fonts that can be easily read by both humans and machines. They design their fonts on a rectangular grid. Shown below is a very simple 5x3 design for the first five digits.

.o. .o. oo. oo. o.o
o.o .o. ..o ..o o.o
o.o .o. .o. oo. ooo
o.o .o. o.. ..o ..o
.o. .o. ooo oo. ..o

The ink appears to be normal black ink, but just underneath the surface DoubleVision adds a special polymer that can be detected by an infrared scanner. A human sees the black ink but not the polymer, and a machine sees the polymer but not the black ink. The only problem is that the polymer is much more expensive than the ink, so DoubleVision wants to use as little of it as possible. They have discovered that with many fonts, each symbol can be uniquely identified by at most two pixels. By only adding the polymer to one or two pixels per symbol, they drastically lower costs while still ensuring 100% accuracy in their scanners. The font shown above has this property; pixels that uniquely identify each letter are highlighted with '#'. (There are other choices that would work as well.)

.#. .o. #o. oo. o.#
#.o .#. ..o ..o o.o
o.o .o. .o. #o. ooo
o.o .o. #.. ..o ..o
.o. .o. ooo #o. ..o

Your job is to write a program to determine if a given font has this property, and if so highlight the pixels.

The input consists of one or more test cases, followed by a line containing '0 0 0' (three zeros) that signals the end of the input. Each test case begins with a line containing three positive integers n, r, and c, separated by a space: n is the number of symbols in the font, r is the number of rows in each grid, and c is the number of columns in each grid. The next r lines contain the image of each symbol, using the exact format shown in the examples: a dot '.' represents an empty part of the grid, a lowercase 'o' represents a pixel, and adjacent grids are separated by a space. The total width of each line will be at most 79 characters (not counting end-of-line characters), and r will be at most 10. The test cases are implicitly numbered starting with 1.

For test case i, first output a line that says 'Test i'. Then determine if each symbol can be uniquely identified with one or two pixels. If not, output a line with the word 'impossible'. Otherwise, output the font in the same format except that the identifying pixels for each symbol are replaced with '#'.

In general there may be several different pixels or pixel pairs that uniquely identify a symbol. To ensure that the output is unique, we add the following definition and rules. When comparing two pixels, the topmost-leftmost pixel is the one closest to the top of the grid. If both pixels are on the same row, then the topmost-leftmost is the one closest to the left of the grid.

If one pixel will work, highlight the topmost-leftmost pixel that works. Never highlight a two-pixel solution if a one-pixel solution is possible. If two pixels are needed, highlight the pair with the topmost-leftmost pixel. If two or more pairs have the same topmost-leftmost pixel, highlight the one with the topmost-leftmost other pixel.

Input:
3 2 2
oo oo .o
o. .o o.
3 2 2
oo oo .o
o. .o oo
5 5 3
.o. .o. oo. oo. o.o
o.o .o. ..o ..o o.o
o.o .o. .o. oo. ooo
o.o .o. o.. ..o ..o
.o. .o. ooo oo. ..o
1 2 4
.o..
...o
0 0 0
Output:
Test 1
impossible
Test 2
#o #o .o
#. .# ##
Test 3
.#. .o. #o. oo. o.#
#.o .#. ..o ..o o.o
o.o .o. .o. #o. ooo
o.o .o. #.. ..o ..o
.o. .o. ooo #o. ..o
Test 4
.#..
...o

Added by:Wanderley Guimarães
Date:2006-06-09
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 2001









SPOJ Problem Set (classical)

904. Image Perimeters

Problem code: IMAGE

Technicians in a pathology lab analyze digitized images of slides. Objects on a slide are selected for analysis by a mouse click on the object. The perimeter of the boundary of an object is one useful measure. Your task is to determine this perimeter for selected objects.

The digitized slides will be represented by a rectangular grid of periods, '.', indicating empty space, and the capital letter 'X', indicating part of an object. Simple examples are

XX Grid 1 .XXX Grid 2
XX .XXX
.XXX
...X
..X.
X...

An X in a grid square indicates that the entire grid square, including its boundaries, lies in some object. The X in the center of the grid below is adjacent to the X in any of the 8 positions around it. The grid squares for any two adjacent X's overlap on an edge or corner, so they are connected.

XXX
XXX Central X and adjacent X's
XXX

An object consists of the grid squares of all X's that can be linked to one another through a sequence of adjacent X's. In Grid 1, the whole grid is filled by one object. In Grid 2 there are two objects. One object contains only the lower left grid square. The remaining X's belong to the other object.

The technician will always click on an X, selecting the object containing that X. The coordinates of the click are recorded. Rows and columns are numbered starting from 1 in the upper left hand corner. The technician could select the object in Grid 1 by clicking on row 2 and column 2. The larger object in Grid 2 could be selected by clicking on row 2, column 3. The click could not be on row 4, column 3.

One useful statistic is the perimeter of the object. Assume each X corresponds to a square one unit on each side. Hence the object in Grid 1 has perimeter 8 (2 on each of four sides). The perimeter for the larger object in Grid 2 is illustrated in the figure at the left. The length is 18.

Objects will not contain any totally enclosed holes, so the leftmost grid patterns shown below could NOT appear. The variations on the right could appear:

Impossible Possible

XXXX XXXX XXXX XXXX
X..X XXXX X... X...
XX.X XXXX XX.X XX.X
XXXX XXXX XXXX XX.X

..... ..... ..... .....
..X.. ..X.. ..X.. ..X..
.X.X. .XXX. .X... .....
..X.. ..X.. ..X.. ..X..
..... ..... ..... .....

The input will contain one or more grids. Each grid is preceded by a line containing the number of rows and columns in the grid and the row and column of the mouse click. All numbers are in the range 1-20. The rows of the grid follow, starting on the next line, consisting of '.' and 'X' characters.

The end of the input is indicated by a line containing four zeros. The numbers on any one line are separated by blanks. The grid rows contain no blanks.

For each grid in the input, the output contains a single line with the perimeter of the specified object.

Input:
2 2 2 2
XX
XX
6 4 2 3
.XXX
.XXX
.XXX
...X
..X.
X...
5 6 1 3
.XXXX.
X....X
..XX.X
.X...X
..XXX.
7 7 2 6
XXXXXXX
XX...XX
X..X..X
X..X...
X..X..X
X.....X
XXXXXXX
7 7 4 4
XXXXXXX
XX...XX
X..X..X
X..X...
X..X..X
X.....X
XXXXXXX
0 0 0 0
Output:
8
18
40
48
8

Added by:Wanderley Guimarães
Date:2006-06-09
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Mid Central Regionals 2001









SPOJ Problem Set (classical)

912. Submatrix of submatrix

Problem code: MATRIX2

You are given a matrix P of N rows and M columns. It consists of integer numbers in the range [1..100]. We define the sum of a matrix is the sum of its elements. Your task is to find a submatrix Q (of A rows and B columns) of P and a submatrix K (of C rows and D columns) of Q so that the difference between the sum of Q and the sum of K is maximal, and submatrix K is absolutely inside matrix Q (i.e no element on matrix Q's sides is also in matrix K).

Because the tests are large, we suggest a method to define matrix P:
P[i][j] = ( P[i][j-1] * 71 + 17 ) mod 100 + 1 . ( 1 ≤ i ≤ N , 1 ≤ j ≤ M )
With this method we only care about P[i][1].

Constraints
1 ≤ N , M ≤ 1000
1 ≤ A ≤ N
1 ≤ B ≤ M
0 ≤ C ≤ A - 2
0 ≤ D ≤ B - 2

Input

The first line of the input contains an integer t (1 ≤ t ≤ 10 ), equal to the number of testcases. Then descriptions of t testcases follow. The first line of the description contains 6 integer numbers N, M, A, B, C, D. Then N lines follow, line i contains one integer number P[i][1].

Output

For each test case, your program should output the maximal difference between two matrices (in a separate line).

Example

Input:
1
3 3 3 3 1 1
1
2
3
Output:
260

Added by:Nguyen Dinh Tu
Date:2006-08-18
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Base on a problem in IOI 2006 .









SPOJ Problem Set (classical)

913. Query on a tree II

Problem code: QTREE2

You are given a tree (an undirected acyclic connected graph) with N nodes, and edges numbered 1, 2, 3...N-1. Each edge has an integer value assigned to it, representing its length.

We will ask you to perfrom some instructions of the following form:

Example:
N = 6
1 2 1 // edge connects node 1 and node 2 has cost 1
2 4 1
2 5 2
1 3 1
3 6 2

Path from node 4 to node 6 is 4 -> 2 -> 1 -> 3 -> 6
DIST 4 6 : answer is 5 (1 + 1 + 1 + 2 = 5)
KTH 4 6 4 : answer is 3 (the 4-th node on the path from node 4 to node 6 is 3)

Input

The first line of input contains an integer t, the number of test cases (t <= 25). t test cases follow.

For each test case:

There is one blank line between successive tests.

Output

For each "DIST" or "KTH" operation, write one integer representing its result.

Print one blank line after each test.

Example

Input:
1

6
1 2 1
2 4 1
2 5 2
1 3 1
3 6 2
DIST 4 6
KTH 4 6 4
DONE

Output:
5
3

Added by:Thanh-Vy Hua
Date:2006-08-27
Time limit:2s
Source limit:15000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Special thanks to Ivan Krasilnikov for his alternative solution









SPOJ Problem Set (classical)

944. Free Tour

Problem code: FTOUR

In order to celebrate the 2nd anniversary of Travel Agent SPOJ (Safe – Professional – hOspitable – Joyful), the management intend to hold free tours around cities for clients to make them more satisfied with SPOJ.

A tour is a simple cycle, starting at any city (called a source-city) visits some other cities (each city must be visited at most once) and then returns to the source-city. The number of roads in the tour should be an even number because we are celebrating a 2nd anniversary, and 2 is even! Since many tours in different areas of the country are planned, the cost of organising them could turn out quite high. Hence, the management of SPOJ hope to find at least one 'reasonable' tour, which should have as small a number of roads as possible.

You're given maps of the areas where SPOJ wants to hold free tours. For each map, help them figure out a reasonable tour.

Input

The first line of input contains an integer t, the number of maps (t <= 5). t maps follow.

For each map:

There is one blank line between successive tests.

Output

For each map, if there is no tour satisfying the conditions, write "-1" (without quotes). Otherwise, write one integer representing the number of roads in a reasonable tour, and in the next line show out the tour with form "source-city a b c .. source-city", that means the tour is source-city -> city a -> city b -> … -> source-city. If there are many tours satisfy in each map, any of them will be accepted.

Example

Input:
2

3 3
1 2 
2 3
3 1

4 4
1 2
2 3
3 4
4 1


Output:
-1
4
1 2 3 4 1

Added by:Thanh-Vy Hua
Date:2006-09-16
Time limit:1s-4s
Source limit:15000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6









SPOJ Problem Set (classical)

962. Intergalactic Map

Problem code: IM

Map Jedi knights, Qui-Gon Jinn and his young apprentice Obi-Wan Kenobi, are entrusted by Queen Padmé Amidala to save Naboo from an invasion by the Trade Federation. They must leave Naboo immediately and go to Tatooine to pick up the proof of the Federation’s evil design. They then must proceed on to the Republic’s capital planet Coruscant to produce it in front of the Republic’s Senate. To help them in this endeavor, the queen’s captain provides them with an intergalactic map. This map shows connections between planets not yet blockaded by the Trade Federation. Any pair of planets has at most one connection between them, and all the connections are two-way. To avoid detection by enemy spies, the knights must embark on this adventure without visiting any planet more than once. Can you help them by determining if such a path exists?

Note - In the attached map, the desired path is shown in bold.

Input Description

The first line of the input is a positive integer t ≤ 20, which is the number of test cases. The descriptions of the test cases follow one after the other. The first line of each test case is a pair of positive integers n, m (separated by a single space). 2 ≤ n ≤ 30011 is the number of planets and m ≤ 50011 is the number of connections between planets. The planets are indexed with integers from 1 to n. The indices of Naboo, Tatooine and Coruscant are 1, 2, 3 respectively. The next m lines contain two integers each, giving pairs of planets that have a connection between them.

Output Description

The output should contain t lines. The ith line corresponds to the ith test case. The output for each test case should be YES if the required path exists and NO otherwise.

Example


Input
2
3 3
1 2
2 3
1 3
3 1
1 3

Output
YES
NO


Added by:Kashyap KBR
Date:2006-10-10
Time limit:6s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:Fair Isaac Programming Challenge - prelims 2006









SPOJ Problem Set (classical)

964. Entrapment

Problem code: EN


Example The separatist leader General Grievous, the second in command of Count Dooku, comes to know that Chancellor Palpatine’s convoy, escorted by Obi-wan and Anakin, is scheduled to depart from Kashyyyk in the Middle Rim of the Universe to Alderaan. General Grievous is aware that there are multiple paths going via different sets of planets from Kashyyyk to Alderaan. To make his abduction attempt successful, he decides to send his robots to the planet closest to Kashyyyk, other than itself, which lies on all the possible paths from Kashyyyk to Alderaan. Since you have pledged your allegiance to Count Dooku, you need to help him identify this planet. The planetary map which is given to you for this purpose consists of a set of one-way connections between planets. You also know that a pair of planets can have at most one connection between them in each direction and there is always a path from Kashyyyk to Alderaan.

Note: In the given example, the planet with index 5 is the required planet.

Input Description

The first line of the input is a positive integer t ≤ 20, which is the number of test cases. The descriptions of the test cases follow one after the other. The first line of each test case is a pair of positive integers n, m (separated by a single space). 2 ≤ n ≤ 30011 is the number of planets and m ≤ 100011 is the number of connections between planets. The planets are indexed with integers from 1 to n and the indices of Kashyyyk and Alderaan are 1, n respectively. Each of the next m lines contains two integers p,q, meaning that there is a one-way connection from planet p to planet q.

Output Description

The output should contain t lines. The ith line corresponds to the ith test case. The output for the ith test case should be the index of the planet with the required property.

Example

Input
2
3 2
1 3
3 2
4 4
1 3
3 4
1 2
2 4

Output
3
4


Added by:Kashyap KBR
Date:2006-10-10
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:Fair Isaac Programming Challenge - prelims 2006









SPOJ Problem Set (classical)

967. Parking Bay

Problem code: PB

Illustration Luke Skywalker successfully leads the rebel starship fleet to break the Emperor's siege of the planet Endor. The rebels, jubilant in their victory, return to their base on the moon of Endor to pay their homage to Princess Leia. They fly towards the parking bay where there are n parking slots in a row. One by one n starships numbered S1 to Sn enter the parking bay. Each rebel Ri heads to his favorite parking slot Pi, and if it is free, he docks his starship there. Otherwise, he continues further to the next free slot and occupies it. But if all succeeding slots are occupied, he leaves for good. How many sequences Pi are such that every rebel can dock his starship?

Input Description

The first line of the input is a positive integer t ≤ 20, which is the number of test cases. The descriptions of the test cases follow one after the other. The description of each test case contains exactly one line (a positive integer), containing the value of n ≤ 1000000.

Output Description

The output consists of exactly t lines. The ith line should be Ai%10007, where Ai is the number of sequences in the ith case, and 'x%y' represents the remainder when x is divided by y.

Example


Input
2
1
2

Output
1
3

Explanation: In the given example, 11, 12 and 21 are the possible sequences.


Added by:Kashyap KBR
Date:2006-10-10
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:Fair Isaac Programming Challenge - prelims 2006









SPOJ Problem Set (classical)

972. Birthday

Problem code: BIRTHDAY

It is Byteman’s birthday today. There are n children at his birthday party (including Byteman). The children are numbered from 1 to n. Byteman’s parents have prepared a big round table and they have placed n chairs around the table. When the children arrive, they take seats. The child number 1 takes one of the seats. Then the child number 2 takes the seat on the left. Then the child number 3 takes the next seat on the left, and so on. Finally the child number n takes the last free seat, between the children number 1 and n−1. Byteman’s parents know the children very well and they know that some of the children will be noisy, if they sit too close to each other. Therefore the parents are going to reseat the children in a specific order. Such an order can be described by a permutation p1, p2, . . . , pn (p1, p2, . . . , pn are distinct integers from 1 to n) — child pi (for i = 2,3, . . . ,n) should sit on child pi−1’s left, and child p1 should sit on child pn’s left. To seat all the children in the given order, the parents must move each child around the table to the left or to the right some number of seats. For each child, they must decide how the child will move — that is, they must choose a direction of movement (left or right) and distance (number of seats). On the given signal, all the children stand up at once, move to the proper places and sit down. The reseating procedure throws the birthday party into a mess. The mess is equal to the total distance any child moves. The children can be reseated in many ways. The parents choose one with minimum mess. Help them to find such a way to reseat the children.

Input

The first line of standard input contains one integer n (1 ≤ n ≤ 50000). The second line contains n integers p1, p2, . . . , pn, separated by single spaces. Numbers p1, p2, . . . , pn form a permutation of the set {1,2, . . . ,n} describing the desired order of the children.

Output

The first and the only line of standard output should contain one integer: the minimum possible mess.

Example

Input:
5
1 5 4 3 2

Output:
6

Added by:Lê Ðôn Khuê
Date:2006-10-11
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:2nd round of Hanoi University of Science - Based on a problem from IOI 2005









SPOJ Problem Set ()

987. Mobile

Problem code: MOBILE

Mobile
Manfred loves to build mobiles out of old CDs. For each one, he has an exact plan how it should look like: The CDs are all hanging exactly on the same height. For each pair of CDs, he writes down the height of the lowest bar such that both CDs are hanging somewhere under this bar. For example, the following mobile and distance matrix fit together:



After a while, Manfred realizes that he does not succeed to build every mobile he planned to. For example, there is no solution for the following distance matrix:
0 1 2
1 0 3
2 3 0
So, he decides to write a computer program that checks the distance matrices and tells him if there is a solution.

Input

Several matrices to check. The first row contains the size of the matrix N (N <= 2048), the next N rows contain the distances in the matrix. Then, the data of the next matrix comes, and so on. All distances are positive integers smaller than 2048. The input is terminated by a zero as matrix size.

Output

For each matrix, write true if Manfred can build a mobile, false otherwise.

Example

Input:
5
0 1 1 1 3
1 0 1 1 3
1 1 0 1 3
1 1 1 0 3
3 3 3 3 0
3
0 1 2
1 0 3
2 3 0
3
1 1 1
1 0 2
1 1 0
0

Output:
true
false
false


Added by:Martin Bader
Date:2006-10-17
Time limit:15s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
Resource:Ulm Bioinformatics Course WS 06/07









SPOJ Problem Set (classical)

996. Continuous Fractions

Problem code: CFRAC


A simple continuous fraction has the form:

subir imagenes



where the ai’s are integer numbers.


The previous continuous fraction could be noted as [a1, a2, . . . , an]. It is not difficult to show that any rational number p / q , with integers p > q > 0, can be represented in a unique way by a simple continuous fraction with n terms, such that p / q = [a1, a2, . . . , an−1, 1], where n and the ai’s are positive natural numbers.


Your task is to find and print the simple continuous fraction that corresponds to a given rational number.

Input

Input will consist of a series of cases, each one in a line. A line describing a case contains p and q, two integer numbers separated by a space, with 10^20 > p > q > 0.


The end of the input is indicated by a line containing 0 0.

Output

Cases must be analyzed in the order that are read from the input. Output for each case will consist of several lines. The first line indicates the case number, starting at 1, using the format:


Case i:
replacing i by the corresponding case number. The second line displays the input data in the form p / q.


The remaining lines must contain the continuous fraction corresponding to the rational number, p q , specified in the given input line. The continuous fraction must be printed accordingly to the following rules:


Example


Input:
75 34
65 60
0 0

Output:
Case 1:
75 / 34
..........1......
2.+.-------------
............1....
....4.+.---------
..............1..
........1.+.-----
................1
............5.+.-
................1
Case 2:
65 / 60
......1...
1.+.------
.........1
....11.+.-
.........1

Added by:Camilo Andrés Varela León
Date:2006-10-24
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:XX Colombian National Programming ACM 2006









SPOJ Problem Set (classical)

999. Generalized Matrioshkas

Problem code: MATRIOSH


Vladimir worked for years making matrioshkas, those nesting dolls that certainly represent truly Russian craft. A matrioshka is a doll that may be opened in two halves, so that one finds another doll inside. Then this doll may be opened to find another one inside it. This can be repeated several times, till a final doll -that cannot be opened- is reached.


Recently, Vladimir realized that the idea of nesting dolls might be generalized to nesting toys. Indeed, he has designed toys that contain toys but in a more general sense. One of these toys may be opened in two halves and it may have more than one toy inside it. That is the new feature that Vladimir wants to introduce in his new line of toys.


Vladimir has developed a notation to describe how nesting toys should be constructed. A toy is represented with a positive integer, according to its size. More precisely: if when opening the toy represented by m we find the toys represented by n1, n2, . . ., nr, it must be true that n1 +n2 +. . .+nr < m. And if this is the case, we say that toy m contains directly the toys n1, n2, . . ., nr . It should be clear that toys that may be contained in any of the toys n1, n2, . . ., nr are not considered as directly contained in the toy m.


A generalized matrioshka is denoted with a non-empty sequence of non zero integers of the form: a1 a2 . . . aN such that toy k is represented in the sequence with two integers −k and k, with the negative one occurring in the sequence first that the positive one.


For example, the sequence


−9 −7 −2 2 −3 −2 −1 1 2 3 7 9


represents a generalized matrioshka conformed by six toys, namely, 1, 2 (twice), 3, 7 and 9.
Note that toy 7 contains directly toys 2 and 3. Note that the first copy of toy 2 occurs left from the second one and that the second copy contains directly a toy 1. It would be wrong to understand that the first −2 and the last 2 should be paired.


On the other hand, the following sequences do not describe generalized matrioshkas:


−9 −7 −2 2 −3 −1 −2 2 1 3 7 9


because toy 2 is bigger than toy 1 and cannot be allocated inside it.


−9 −7 −2 2 −3 −2 −1 1 2 3 7 −2 2 9


because 7 and 2 may not be allocated together inside 9.


Input

The input file contains several test cases, each one of them in a separate line. Each test case is a sequence of non zero integers, each one with an absolute value less than 10^7.


Output

Output texts for each input case are presented in the same order that input is read. For each test case the answer must be a line of the form


:-) Matrioshka!


if the design describes a generalized matrioshka. In other case, the answer should be of the form


:-( Try again.

Example

Input:
-9 -7 -2 2 -3 -2 -1 1 2 3 7 9
-9 -7 -2 2 -3 -1 -2 2 1 3 7 9
-9 -7 -2 2 -3 -1 -2 3 2 1 7 9
-100 -50 -6 6 50 100
-100 -50 -6 6 45 100
-10 -5 -2 2 5 -4 -3 3 4 10
-9 -5 -2 2 5 -4 -3 3 4 9

Output:
:-) Matrioshka!
:-( Try again.
:-( Try again.
:-) Matrioshka!
:-( Try again.
:-) Matrioshka!
:-( Try again.

Added by:Camilo Andrés Varela León
Date:2006-10-24
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:XX Colombian National Programming ACM 2006









SPOJ Problem Set (classical)

1000. Equidivisions

Problem code: EQDIV

An equidivision of an n × n square array of cells is a partition of the n^2 cells in the array in exactly n sets, each one with n contiguous cells. Two cells are contiguous when they have a common side.


A good equidivision is composed of contiguous regions. The figures show a good and a wrong equidivision for a 5×5 square:


subir imagenes


Note that in the second example the cells labeled with 4 describe three non-contiguous regions and cells labeled with 5 describe two non-contiguous regions. You must write a program that evaluates if an equidivision of the cells in a square array is good or not.

Input

It is understood that a cell in an n×n square array is denoted by a pair (i, j), with 1 <= i, j <= n. The input file contains several test cases. Each test case begins with a line indicating n, 0 < n < 100, the side of the square array to be partitioned. Next, there are n − 1 lines, each one corresponding to one partition of the cells of the square, with some non-negative integer numbers.


Consecutive integers in a line are separated with a single blank character. A line of the form


a1 a2 a3 a4 ...


means that cells denoted with the pairs (a1, a2), (a3, a4), ... belong to one of the areas in the partition. The last area in the partition is defined by those cells not mentioned in the n − 1 given lines. If a case begins with n = 0 it means that there are no more cases to analyze.


Output

For each test case good must be printed if the equidivision is good, in other case, wrong must be printed. The answers for the different cases must preserve the order of the input.

Example

Input:
2
1 2 2 1
5
1 1 1 2 1 3 3 2 2 2
2 1 4 2 4 1 5 1 3 1
4 5 5 2 5 3 5 5 5 4
2 5 3 4 3 5 4 3 4 4
5
1 1 1 2 1 3 3 2 2 2
2 1 3 1 4 1 5 1 4 2
4 5 5 2 5 3 5 5 5 4
2 4 1 4 3 5 4 3 4 4
0

Output:
wrong
good
wrong

Added by:Camilo Andrés Varela León
Date:2006-10-25
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:XX Colombian National Programming ACM 2006









SPOJ Problem Set (classical)

1001. Babylonian Roulette

Problem code: BROUL


People of Babylon were devoted to chance games and one of the most popular was a special kind of roulette. Recently, some old Babylonian tablets were found. They described details of the roulette game.


In modern terms, the rules of the game were as follows:


Beside the tablets that explained the rules some other tablets were found. These had lines with three numbers. Archeologists conjecture that each of these lines were part of a kind of accountability system for the game, where numbers represented, for a given day, the value of the pot at the beginning, the bet and the value of the pot at the end.


For example, a line with the numbers


10000 1500 11500


could mean that there was only one turn where the player won with label 1. Another possibility is that there were three turns with results 2, 1 and -2.


On the other hand, there were found other tablets with triplets of numbers that seem like the above described that, however, cannot represent results of a game day. There is no hypothesis of what they are.


Archeologists want to validate their hypothesis analyzing batches of tablets with triplets. They want to estimate the number of people that played in a day. To begin, they want to establish, for each triplet of numbers in a tablet that could represent a result of a game day, the minimal number of players that played that day. In the above example the answer to this question is 1. Tablets that cannot represent results should be identified. You are hired to help with this task.


Input

The input file contains several test cases, each one of them in a separate line. Each test case is a triplet of non negative integers, indicating the initial pot, the bet and the final pot for a day.


Each of the input numbers is less than 108. The initial pot and the bet are greater than 0.


A line with a triplet of 0’s denotes the end of the input.

Output

Output texts for each input case are presented in the same order that input is read. For each test case the answer must be a printed line.


If the test case cannot represent the result of a game day, the output line has the words No accounting tablet. In other case, the printed answer is one positive integer number telling the minimal number of players that could turn the roulette for the day corresponding to the annotations.

Example

Input:
10000 1000 22000
24 13 2
5100 700 200
54 16 158
360 6 72
25 10 5
0 0 0

Output:
4
No accounting tablet
3
No accounting tablet
16
1

Added by:Camilo Andrés Varela León
Date:2006-10-25
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:XX Colombian National Programming ACM 2006









SPOJ Problem Set (classical)

1002. Uncle Jack

Problem code: UJ

Dear Uncle Jack is willing to give away some of his collectable CDs to his nephews. Among the titles you can find very rare albums of Hard Rock, Classical Music, Reggae and much more; each title is considered to be unique. Last week he was listening to one of his favorite songs, Nobody’s fool, and realized that it would be prudent to be aware of the many ways he can give away the CDs among some of his nephews.


So far he has not made up his mind about the total amount of CDs and the number of nephews. Indeed, a given nephew may receive no CDs at all.


Please help dear Uncle Jack, given the total number of CDs and the number of nephews, to calculate the number of different ways to distribute the CDs among the nephews.


Input

The input consists of several test cases. Each test case is given in a single line of the input by, space separated, integers N (1 <= N <= 1000) and D (0 <= D <= 2500), corresponding to the number of nephews and the number of CDs respectively. The end of the test cases is indicated with N = D = 0.


Output

The output consists of several lines, one per test case, following the order given by the input. Each line has the number of all possible ways to distribute D CDs among N nephews.

Example

Input:
1 20
3 10
0 0

Output:
1
59049

Added by:Camilo Andrés Varela León
Date:2006-10-25
Time limit:1s
Source limit:512B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:XX Colombian National Programming ACM 2006









SPOJ Problem Set (classical)

1003. Little Quilt

Problem code: QUILT

Little Quilt is a small language introduced by Ravi Sethi in his book ‘Programming Languages’.


Here, a restricted version of Little Quilt is presented. The language is defined by the following BNF grammar:


< QUILT > ::= A | B | turn(< QUILT >) | sew(< QUILT >,< QUILT >)


A and B represent the two primitive quilts. Each primitive quilt corresponds to a matricial arrangement of 2 × 2 characters. turn() and sew() are operations over quilts.


The instruction turn(x) turns the quilt x 90 degrees clockwise. The following table illustrates the primitive quilts as well as examples of the effect of the turn() operation:


subir imagenes


Accordingly, the instruction sew(x,y) sews quilt x to the left of quilt y. Both x and y must have the same height, otherwise an error will be generated. The following figure represents the result of sew(A,turn(B)):


subir imagenes


while the sew(turn(sew(B,turn(B))),A) generates an error message.


Your job is to build an interpreter of the Little Quilt language.


Input

The input file will be a text file containing different Little Quilt expressions, each one ended by a semicolon character (;). Space and new line characters must be ignored; this means that an expression may span several lines.


Output

The output file contains the quilts produced as a result of interpreting the input expressions.


Each quilt must be preceded by a line, left aligned, with the format


Quilt i:
where i is the quilt number, starting at 1. If the expression interpretation generates and error, the word


error
must be printed.


Example

Input:
sew(turn(sew(B,turn(B))),
turn(sew(turn(B),B))) ;


sew(turn(sew(B,turn(B))),A); sew(turn(sew(A,turn(A))), turn(turn(
turn(sew(A,turn(A)))))) ; Output: Quilt 1: ||-- ||-- --|| --|| Quilt 2: error Quilt 3: \\// +\/+ +/\+ //\\

Added by:Camilo Andrés Varela León
Date:2006-10-25
Time limit:1s-2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:XX Colombian National Programming ACM 2006









SPOJ Problem Set (classical)

1004. Polygon Encoder

Problem code: POLYCODE

Imagine an infinite table with rows and columns numbered using the natural numbers. The following figure shows a procedure to traverse such a table assigning a consecutive natural number to each table cell:


subir imagenes


This enumeration of cells can be used to represent complex data types using natural numbers:



L(ha1, ..., ani) = P2(n, Pn(a1, ..., an)).


For example, L(h0, 1i) = 12.


The Association of Convex Makers (ACM) uses this clever enumeration scheme in a polygon representation system. The system can represent a polygon, defined by integer coordinates, using a natural number as follows: given a polygon defined by a vertex sequence h(x1, y1), ..., (xn, yn)i assign the natural number:


L((hP2(x1, y1), ..., P2(xn, yn))).


ACM needs a program that, given a natural numbers that represents a polygon, calculates the area of the polygon. It is guaranteed that the given polygon is a simple one, i.e. its sides do not intersect.


As an example of the problem, the triangle with vertices at (1,1), (2,0) and (0,0) is codified with the number 2141. The area of this triangle is 1.


Input

The input consists of several test cases. Each test case is given in a single line of the input by a natural number representing a polygon. The end of the test cases is indicated with *.


Output

One line per test case, preserving the input order. Each output line contains a decimal number telling the area of the corresponding encoded polygon. Areas must be printed with 1 decimal place, truncating less significative decimal places.


Example

Input:
2141
206
157895330
*

Output:
1.0
0.5
1.0

Added by:Camilo Andrés Varela León
Date:2006-10-25
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:XX Colombian National Programming ACM 2006









SPOJ Problem Set (classical)

1021. Aibohphobia

Problem code: AIBOHP

BuggyD suffers from AIBOHPHOBIA - the fear of Palindromes. A palindrome is a string that reads the same forward and backward.

To cure him of this fatal disease, doctors from all over the world discussed his fear and decided to expose him to large number of palindromes. To do this, they decided to play a game with BuggyD. The rules of the game are as follows:

BuggyD has to supply a string S. The doctors have to add or insert characters to the string to make it a palindrome. Characters can be inserted anywhere in the string.

The doctors took this game very lightly and just appended the reverse of S to the end of S, thus making it a palindrome. For example, if S = "fft", the doctors change the string to "ffttff".

Nowadays, BuggyD is cured of the disease (having been exposed to a large number of palindromes), but he still wants to continue the game by his rules. He now asks the doctors to insert the minimum number of characters needed to make S a palindrome. Help the doctors accomplish this task.

For instance, if S = "fft", the doctors should change the string to "tfft", adding only 1 character.

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

Each test case consists of one line, the string S. The length of S will be no more than 6100 characters, and S will contain no whitespace characters.

Output

For each test case output one line containing a single integer denoting the minimum number of characters that must be inserted into S to make it a palindrome.

Example

Input:
1
fft

Output:
1

Added by:Matthew Reeder
Date:2006-10-29
Time limit:8s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1022. Angels and Devils

Problem code: ANGELS

It's the year 21546 AD, and due to increased population (you wouldn't believe me if I gave you the actual numbers), land has become very expensive. Because of the lack of space, Heaven and Hell were built in the same area. The area can be represented as a grid of X × Y unit squares. Some of the squares were captured by the Devil (and thus belong to Hell) and the rest is the Almighty's property. On each square, a room has been built with transparent glass walls. However, some of the heavenly rooms are already occupied by Angels. For security purposes, rooms occupied by Angels have concrete opaque walls.

Recently many fighters were killed in a tournament. Fighting is no longer considered cruel, so all the fighters will deserve spots in heaven. However, because of the space shortage, all of them may not be able to recieve a spot in heaven. The fighters still hold a grudge against each other so a fighter cannot be placed in a room from which he can see any other fighter. A fighter can only see in the four cardinal directions (North, South, East and West). He cannot look diagonally or in any other direction.

Find the maximum number of fighters who can have a heavenly room.

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

The first line of each test case consists of two integers X <= 300 and Y <= 300, separated by a single space. Next, X lines follow, each having Y letters separated by spaces. The jth letter on the i-th line is one of the following (quotes are for clarity, and do not appear in the input):

  1. "H", if the room at location (i, j) is heavenly and vacant.
  2. "A", if the room at location (i, j) is heavenly and is already occupied by an angel. Note that these rooms are not transparent.
  3. "D", if the room at location (i, j) belongs to the Devil.
Output

A single line for each test case containing an integer denoting the maximum number of fighters that can fit in heaven.

Example

Input:
1
4 7
H H H H H H H
H H H H H H H
H H H H H H H
H H H H H H H

Output:
4

Added by:Matthew Reeder
Date:2006-10-29
Time limit:7s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1024. Complete Chess Boards

Problem code: COMCB

BuggyD has always been fascinated with chess boards (though he really sucks at chess). He makes an observation that a chess board is complete with respect to knights and rooks and incomplete with respect to bishops (unless the dimensions are 1 × 1). A complete chess board is one in which it is possible to traverse all the squares starting from one possible square. Knights have always been his favourite pieces and he has decided to analyze completeness with respect to knights. Given the dimesions of the chess board help BuggyD find the lexicographically first path that visits all squares of a chess board with a knight.

Each square must be traversed only once. Note that a knight can only move two squares in one direction and one square perpendicular to the previous direction.

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

Each test case consists of a single line cotaining two integers (X and Y) separated by a single space, specifying the dimensions of the chess board. The numbers 1 to X denote rows and the capital letters A to Y denote the coloumns. Each square is represented by its column index followed by it's row index - for example, B4 denotes the square in the 4th row and 2nd column.

The total number of squares on the chess board will be no more than 26.

Output

For each test case output one line consisting of the lexicographically first path of the knight, or "-1" (quotes for clarity) if the chess board is incomplete with respect to a knight.

Example

Input:
1
4 5

Output:
A1B3C1A2B4D3E1C2D4E2C3A4B2D1E3C4A3B1D2E4

Added by:Matthew Reeder
Date:2006-10-29
Time limit:3s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1025. Fashion Shows

Problem code: FASHION

A fashion show rates participants according to their level of hotness. Two different fashion shows were organized, one for men and the other for women. A date for the third is yet to be decided ;) .

Now the results of both fashion shows are out. The participants of both the fashion shows have decided to date each other, but as usual they have difficuly in choosing their partners. The Maximum Match dating serive (MMDS) comes to their rescue and matches them in such a way that that maximizes the hotness bonds for all couples.

If a man has been rated at hotness level x and a women at hotness level y, the value of their hotness bond is x*y.

Both fashion shows contain N participants each. MMDS has done its job and your job is to find the sum of hotness bonds for all the couples that MMDS has proposed.

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

Each test case consists of 3 lines:

  • The first line contains a single integer N (1 <= N <= 1000).
  • The second line contains N integers separated by single spaces denoting the hotness levels of the men.
  • The third line contains N integers separated by single spaces denoting the hotness levels of the women.

All hotness ratings are on a scale of 0 to 10.

Output

For each test case output a single line containing a single integer denoting the sum of the hotness bonds for all pairs that MMDS has proposed.

Example

Input:
2
2
1 1
3 2
3
2 3 2
1 3 2

Output:
5
15

Added by:Matthew Reeder
Date:2006-10-29
Time limit:2s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1026. Favorite Dice

Problem code: FAVDICE

BuggyD loves to carry his favorite die around. Perhaps you wonder why it's his favorite? Well, his die is magical and can be transformed into an N-sided unbiased die with the push of a button. Now BuggyD wants to learn more about his die, so he raises a question:

What is the expected number of throws of his die while it has N sides so that each number is rolled at least once?

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

Each test case consists of a single line containing a single integer N (1 <= N <= 1000) - the number of sides on BuggyD's die.

Output

For each test case, print one line containing the expected number of times BuggyD needs to throw his N-sided die so that each number appears at least once. The expected number must be accurate to 2 decimal digits.

Example

Input:
2
1
12

Output:
1.00
37.24

Added by:Matthew Reeder
Date:2006-10-29
Time limit:2s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1027. Fool the Police

Problem code: FPOLICE

Dhamaka Singh (a crook) has just robbed a bank and would like to get out of the country as soon as possible. But there is a slight problem, the police! On his way out of the country he has to pass through some police stations. Each police station has a certain risk (for Dhamaka Singh) associated with it. He wants to get to the airport within a certain time T or else he'll miss his flight. He also wants to take a path that minimizes the total risk associated with it. Help Dhamaka Singh get out of the country.

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

The first line of each test case contains 2 integers N (3 <= N 100) and T (1 <= T <= 250), denoting the number of police stations and the total time he has to reach the airport, respectively.

Dhamaka Singh has to start from the first police station and reach the Nth one (the airport is just after the Nth police station). You can consider the time taken between the Nth police station and the airport to be negligible.

Next there are N lines with N numbers in each line, separated by single spaces. All numbers are separated by a single space. The jth integer in the ith line represents the time taken to reach the jth police station from the ith police station.

Next there are another N lines with N numbers in each line. All numbers are separated by a single space. The jth integer in the ith line represents the risk involved in travelling to the jth police station from the ith police station.

Output

For each test case output one line containing 2 integers separated by a single space.

The first integer denotes the minimum total risk to reach the airport. The second integer denotes the minimum time required to reach the airport at the minimum total risk.

If it is impossible to reach the airport within time T (inclusive), just print "-1" (quotes for clarity).

Example

Input:
1
4 10
0 6 2 3
6 0 2 3
3 1 0 2
3 3 2 0
0 2 2 7
2 0 1 2
2 2 0 5
7 2 5 0

Output:
4 9

Added by:Matthew Reeder
Date:2006-10-29
Time limit:3s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1028. Hubulullu

Problem code: HUBULLU

After duelling in quake (a multiplayer game), Airborne and Pagfloyd decide do test themselves out in another game called Hubulullu. The rules of the game are as follows:

N wooden pieces (marked with numbers 1 to N) are placed in a transparent bottle. On his turn the first player takes out some piece (numbered x) and all the pieces numbered by divisors of x that are present in the transparent bottle. The second player picks another number and removes it and its divisors as well. Play continues in an alternating fashion until all pieces have been removed from the bottle. The player who removes the last piece from the bottle wins the game.

Both players play optimally. Given N (the number of wooden pieces in the transparent bottle initially) and the name of the player who starts the game, determine the winner.

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

Each test case consists of a single line containing two integers separated by a single space. The first integer is N (1 <= N <= 2000000000), indicating the number of pieces, and the second integer indicates the player who starts - "0" means Airborne starts the game and "1" means Pagfloyd starts the game (quotes for clarity).

Output

For each test case output one line containing either "Airborne wins." or "Pagfloyd wins."

For each N, it's possible to determine a winner if both players play optimally.

Example

Input:
1
1 0

Output:
Airborne wins.

Added by:Matthew Reeder
Date:2006-10-29
Time limit:7s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1029. Matrix Summation

Problem code: MATSUM


A N × N matrix is filled with numbers. BuggyD is analyzing the matrix, and he wants the sum of certain submatrices every now and then, so he wants a system where he can get his results from a query. Also, the matrix is dynamic, and the value of any cell can be changed with a command in such a system.

Assume that initially, all the cells of the matrix are filled with 0. Design such a system for BuggyD. Read the input format for further details.

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

The first line of each test case contains a single integer N (1 <= N <= 1024), denoting the size of the matrix.

A list of commands follows, which will be in one of the following three formats (quotes are for clarity):

  1. "SET x y num" - Set the value at cell (x, y) to num (0 <= x, y < N).
  2. "SUM x1 y1 x2 y2" - Find and print the sum of the values in the rectangle from (x1, y1) to (x2, y2), inclusive. You may assume that x1 <= x2 and y1 <= y2, and that the result will fit in a signed 32-bit integer.
  3. "END" - Indicates the end of the test case.

Output

For each test case, output one line for the answer to each "SUM" command. Print a blank line after each test case.

Example

Input:
1
4
SET 0 0 1
SUM 0 0 3 3
SET 2 2 12
SUM 2 2 2 2
SUM 2 2 3 3
SUM 0 0 2 2
END

Output:
1
12
12
13
Warning: large Input/Output data, be careful with certain languages

Added by:Matthew Reeder
Date:2006-10-29
Time limit:7s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1030. Triple Fat Ladies

Problem code: EIGHTS

Pattern Matchers have been designed for various sorts of patterns. Mr. HKP likes to observe patterns in numbers. After completing his extensive research on the squares of numbers, he has moved on to cubes. Now he wants to know all numbers whose cube ends in 888.

Given a number k, help Mr. HKP find the kth number (indexed from 1) whose cube ends in 888.

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

Each test case consists of a single line containing a single integer k (1 <= k <= 2000000000000).

Output

For each test case, output a single integer which denotes the kth number whose cube ends in 888. The result will be less than 263.

Example

Input:
1
1

Output:
192

Added by:Matthew Reeder
Date:2006-10-30
Time limit:5s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1031. Up Subsequence

Problem code: UPSUB

If x = a0a1a2...an-1 is a string where ai denotes the character at index i, a subsequence aj0aj1aj2...ajn is called an upsubsequence if aj0 <= aj1 <= aj2 <= ... <= ajn and j0 < j1 < j2 < ... < jn.

A maximal upsubsequence of a string is defined as the upsubsequence of maximum length. BuggyD observes that a string x can have many maximal upsubsequences. Help him find all the maximal upsubsequences in x.

Input

The first line of the input contains an integer t, the number of test cases. t test cases follow.

Each test case consists of a single line containing a string x, where the length of x is no more than 100. x will not contain any spaces, tabs or other whitespace characters.

Output

For each test csae, output all of the maximal upsubsequences of x in lexicographical order. Print a blank line after each test case.

Example

Input:
1
abcbcbcd

Output:
abbbcd
abbccd
abcccd

Added by:Matthew Reeder
Date:2006-10-30
Time limit:3s
Source limit:30000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Al-Khawarizm 2006









SPOJ Problem Set (classical)

1043. Can you answer these queries I

Problem code: GSS1

You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| ≤ 15007 , 1 ≤ N ≤ 50000 ). A query is defined as follows:
Query(x,y) = Max { a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }.
Given M queries, your program must output the results of these queries.

Input

  • The first line of the input file contains the integer N.
  • In the second line, N numbers follow.
  • The third line contains the integer M.
  • M lines follow, where line i contains 2 numbers xi and yi.

Output

    Your program should output the results of the M queries, one query per line.

Example

Input:
3 
-1 2 3
1
1 2
Output:
2

Added by:Nguyen Dinh Tu
Date:2006-11-01
Time limit:1s-2s
Source limit:5000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6









SPOJ Problem Set ()

1108. Card Trick

Problem code: CTRICK

The magician shuffles a small pack of cards, holds it face down and performs the following procedure:


1. The top card is moved to the bottom of the pack. The new top card is dealt face up onto the table. It is the Ace of Spades.


2. Two cards are moved one at a time from the top to the bottom. The next card is dealt face up onto the table. It is the Two of Spades.


3. Three cards are moved one at a time…


4. This goes on until the nth and last card turns out to be the n of Spades.


This impressive trick works if the magician knows how to arrange the cards beforehand (and knows how to give a false shuffle). Your program has to determine the initial order of the cards for a given number of cards, 1 ≤ n ≤ 20000.


Input

On the first line of the input is a single positive integer, telling the number of test cases to follow. Each case consists of one line containing the integer n.

Output

For each test case, output a line with the correct permutation of the values 1 to n, space separated. The first number showing the top card of the pack, etc…

Example

Input:
2
4
5

Output:
2 1 4 3
3 1 4 5 2

Added by:Camilo Andrés Varela León
Date:2006-11-23
Time limit:11s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:Nordic Collegiate Contest 2006









SPOJ Problem Set (classical)

1110. Sudoku

Problem code: SUDOKU

A Sudoku grid is a 16x16 grid of cells grouped in sixteen 4x4 squares, where some cells are filled with letters from A to P (the first 16 capital letters of the English alphabet), as shown in the figure. The game is to fill all the empty grid cells with letters from A to P such that each letter from the grid occurs once only in the line, the column, and the 4x4 square it occupies. The initial content of the grid satisfies the constraints mentioned above and guarantees a unique solution.


A C O I
J A B P C G F H
D F I E P
G E L H M J
E C G
I K G A B E J
D G P J F A
E C B D P O
E F M D L K A
C O I L
H P C F A B
G O D J H
K J H A P L
B P E K A
H B K F I C
F C D H N

a) Sudoku grid


F P A H M J E C N L B D K O G I
O J M I A N B D P K C G F L H E
L N D K G F O I J E A H M B P C
B G C E L K H P O F I M A J D N
M F H B E L P O A C K J G N I D
C I L N K D G A H B M O P E F J
D O G P I H J M F N L E C A K B
J E K A F C N B G I D P L H O M
E B O F P M I J D G H L N K C A
N C J D H B A E K M O F I G L P
H M P L C G K F I A E N B D J O
A K I G N O D L B P J C E F M H
K D E M J I F N C H G A O P B L
G L B C D P M H E O N K J I A F
P H N O B A L K M J F I D C E G
I A F J O E C G L D P B H M N K

b) Solution

Input

The first line of the input contains an integer K - determining the number of datasets (K<=10). Each data set encodes a grid and contains 16 strings on 16 consecutive lines as shown in the example input below. The ith string stands for the ith line of the grid, is 16 characters long, and starts from the first position of the line. String characters are from the set {A,B,…,P,-}, where – (minus) designates empty grid cells. The data sets are separated by single empty lines.

Output

For each data set in the input print the completed 16x16 Sudoku as specified by the rules above. The program prints the solution of the input encoded grids in the same format and order as used for input. The output for each data set should be separated by single empty lines.

Example

Input:

1
--A----C-----O-I 
-J--A-B-P-CGF-H-
--D--F-I-E----P-
-G-EL-H----M-J--
----E----C--G---
-I--K-GA-B---E-J 
D-GP--J-F----A--
-E---C-B--DP--O-
E--F-M--D--L-K-A 
-C--------O-I-L-
H-P-C--F-A--B---
---G-OD---J----H 
K---J----H-A-P-L 
--B--P--E--K--A-
-H--B--K--FI-C--
--F---C--D--H-N-

Output:

FPAHMJECNLBDKOGI 
OJMIANBDPKCGFLHE 
LNDKGFOIJEAHMBPC 
BGCELKHPOFIMAJDN 
MFHBELPOACKJGNID 
CILNKDGAHBMOPEFJ 
DOGPIHJMFNLECAKB 
JEKAFCNBGIDPLHOM 
EBOFPMIJDGHLNKCA 
NCJDHBAEKMOFIGLP 
HMPLCGKFIAENBDJO 
AKIGNODLBPJCEFMH 
KDEMJIFNCHGAOPBL 
GLBCDPMHEONKJIAF 
PHNOBALKMJFIDCEG 
IAFJOECGLDPBHMNK

Added by:P.Kasthuri Rangan­
Date:2006-11-24
Time limit:7s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM Southeastern European Regional Programming Contest - 2006









SPOJ Problem Set (classical)

1112. Number Steps

Problem code: NSTEPS

Starting from point (0,0) on a plane, we have written all non-negative integers 0, 1, 2,... as shown in the figure. For example, 1, 2, and 3 has been written at points (1,1), (2,0), and (3, 1) respectively and this pattern has continued.

 

Illustration



You are to write a program that reads the coordinates of a point (x, y), and writes the number (if any) that has been written at that point. (x, y) coordinates in the input are in the range 0...10000.

 

Input

The first line of the input is N, the number of test cases for this problem. In each of the N following lines, there is x, and y representing the coordinates (x, y) of a point.

 

Output

For each point in the input, write the number written at that point or write No Number if there is none.

 

Example

Input:
3
4 2
6 6
3 4

Output:
6
12
No Number

Added by:Camilo Andrés Varela León
Date:2006-11-25
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Asia - Tehran 2000









SPOJ Problem Set (classical)

1161. Tic-Tac-Toe ( I )

Problem code: TOE1

Tic Tac Toe is a child's game played on a 3 by 3 grid. One player, X, starts by placing an X at an unoccupied grid position. Then the other player, O, places an O at an unoccupied grid position. Play alternates between X and O until the grid is filled or one player's symbols occupy an entire line (vertical, horizontal, or diagonal) in the grid.


We will denote the initial empty Tic Tac Toe grid with nine dots. Whenever X or O plays we fill in an X or an O in the appropriate position. The example below illustrates each grid configuration from the beginning to the end of a game in which X wins.


subir imagenes



Your job is to read a grid and to determine whether or not it could possibly be part of a valid Tic Tac Toe game. That is, is there a series of plays that can yield this grid somewhere between the start and end of the game?


Input

The first line of input contains N, the number of test cases. 4N-1 lines follow, specifying N grid configurations separated by empty lines.

Output

For each case print "yes" or "no" on a line by itself, indicating whether or not the configuration could be part of a Tic Tac Toe game.

Example

Input:
2
X.O
OO.
XXX

O.X
XX.
OOO

Output:
yes
no

Added by:Camilo Andrés Varela León
Date:2006-12-14
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Waterloo local 2002.09.21









SPOJ Problem Set (classical)

1162. Tic-Tac-Toe ( II )

Problem code: TOE2

In the game of tic-tac-toe, two players take turns marking squares of an initially empty 3 × 3 grid with either X’s or O’s. The first player always marks squares using X’s, whereas the second player always marks squares using O’s. If at any point during the game either player manages to mark three consecutive squares in a row, column, or diagonal with his/her symbol, the game terminates.


Given a board configuration, your goal is to determine whether the board configuration represents the possible final state of a valid tic-tac-toe game.


Input

The input test file will contain multiple cases. Each test case consists of a single line containing 9 characters, which represent the 9 squares of a tic-tac-toe grid, given one row at a time. Each character on the line will either be ‘X’, ‘O’ (the letter O), or ‘.’ (indicating an unfilled square). The end-of-file is marked by a single line containing the word “end”.


Output

For each input test case, write a single line containing either the word “valid” or “invalid” indicating whether the given board configuration is the final state of some possible tic-tac-toe game.


Example

Input:
XXXOO.XXX
XOXOXOXOX
OXOXOXOXO
XXOOOXXOX
XO.OX...X
.XXX.XOOO
OOXXXOOXO
end

Output:
invalid
valid
invalid
valid
valid
invalid
invalid

Added by:Camilo Andrés Varela León
Date:2006-12-14
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Stanford Local 2006









SPOJ Problem Set (classical)

1163. Java vs C ++

Problem code: JAVAC

Apologists of Java and C++ can argue for hours proving each other that their programming language is the best one. Java people will tell that their programs are clearer and less prone to errors, while C++ people will laugh at their inability to instantiate an array of generics or tell them that their programs are slow and have long source code.


Another issue that Java and C++ people could never agree on is identifier naming. In Java a multiword identifier is constructed in the following manner: the first word is written starting from the small letter, and the following ones are written starting from the capital letter, no separators are used. All other letters are small. Examples of a Java identifier are javaIdentifier, longAndMnemonicIdentifier, name, nEERC.


Unlike them, C++ people use only small letters in their identifiers. To separate words they use underscore character ‘_’. Examples of C++ identifiers are c_identifier, long_and_mnemonic_identifier, name (you see that when there is just one word Java and C++ people agree), n_e_e_r_c.


You are writing a translator that is intended to translate C++ programs to Java and vice versa. Of course, identifiers in the translated program must be formatted due to its language rules — otherwise people will never like your translator.


The first thing you would like to write is an identifier translation routine. Given an identifier, it would detect whether it is Java identifier or C++ identifier and translate it to another dialect. If it is neither, then your routine should report an error. Translation must preserve the order of words and must only change the case of letters and/or add/remove underscores.


Input

The input file consists of several lines that contains an identifier. It consists of letters of the English alphabet and underscores. Its length does not exceed 100.


Output

If the input identifier is Java identifier, output its C++ version. If it is C++ identifier, output its Java version. If it is none, output 'Error!' instead.


Example

Input:
long_and_mnemonic_identifier
anotherExample
i
bad_Style

Output:
longAndMnemonicIdentifier
another_example
i
Error!

Added by:Camilo Andrés Varela León
Date:2006-12-14
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Northeastern Europe 2006









SPOJ Problem Set (classical)

1166. Dead Fraction

Problem code: DEADFR

Mike is frantically scrambling to finish his thesis at the last minute. He needs to assemble all his research notes into vaguely coherent form in the next 3 days. Unfortunately, he notices that he had been extremely sloppy in his calculations. Whenever he needed to perform arithmetic, he just plugged it into a calculator and scribbled down as much of the answer as he felt was relevant. Whenever a repeating fraction was displayed, Mike simply reccorded the first few digits followed by "...". For instance, instead of "1/3" he might have written down "0.3333...". Unfortunately, his results require exact fractions! He doesn't have time to redo every calculation, so he needs you to write a program (and FAST!) to automatically deduce the original fractions.


To make this tenable, he assumes that the original fraction is always the simplest one that produces the given sequence of digits; by simplest, he means the the one with smallest denominator. Also, he assumes that he did not neglect to write down important digits; no digit from the repeating portion of the decimal expansion was left unrecorded (even if this repeating portion was all zeroes).


Input

There are several test cases. For each test case there is one line of input of the form "0.dddd..." where dddd is a string of 1 to 18 digits, not all zero. A line containing 0 follows the last case.


Output

For each case, output the original fraction.


Example

Input:
0.2...
0.20...
0.474612399...
0

Output:
2/9
1/5
1186531/2500000

Added by:Camilo Andrés Varela León
Date:2006-12-16
Time limit:4s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Waterloo Local Contest Sep. 27, 2003









SPOJ Problem Set (classical)

1167. Move To Invert

Problem code: MINCOUNT

A triangle made of coins of height h is as follows
It has h coins at the base and h-1 coins one level above base and so on.(Coins are placed as shown in the figure below)
And at the top most level there will be only one coin
Now given h the task is to invert this triangle by moving minimum number of coins. For example when h=4 triangle is
Invert
For h=4 at least 3 coins must be moved to invert it.

Input

In the first line N will be given and then N lines follow with each line having a integer which is the height of triangle in that test case.00≤h<1010;

Output

For each test case output in a seperate line the minimum number of moves required to invert the triangle. Output fits in long long data type

Example

Inputt:
1
3

Output:
2

Added by:Abhilash I
Date:2006-12-16
Time limit:1s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS
Resource:IIIT Hyderabad Local Programming Contest









SPOJ Problem Set (classical)

1182. Sorted bit squence

Problem code: SORTBIT


Let's consider the 32 bit representation of all integers i from m up to n inclusive (m ≤ i ≤ n; m × n ≥ 0, -2^31 ≤ m ≤ n ≤ 2^31-1). Note that a negative number is represented in 32 bit Additional Code. That is the 32 bit sequence, the binary sum of which and the 32 bit representation of the corresponding positive number is 2^32 (1 0000 0000 0000 0000 0000 0000 0000 0000 in binary).

For example, the 32 bit representation of 6 is 0000 0000 0000 0000 0000 0000 0000 0110

and the 32 bit representation of -6 is 1111 1111 1111 1111 1111 1111 1111 1010

because

0000 0000 0000 0000 0000 0000 0000 0110 (6)
+
1111 1111 1111 1111 1111 1111 1111 1010 (-6)
-------------------------------------------------
= 1 0000 0000 0000 0000 0000 0000 0000 0000 (2^32)

Let's sort the 32 bit representations of these numbers in increasing order of the number of bit 1. If two 32 bit representations that have the same number of bit 1, they are sorted in lexicographical order.

For example, with m = 0 and n = 5, the result of the sorting will be

No.

Decimal number

Binary 32 bit representation

1

0

0000 0000 0000 0000 0000 0000 0000 0000

2

1

0000 0000 0000 0000 0000 0000 0000 0001

3

2

0000 0000 0000 0000 0000 0000 0000 0010

4

4

0000 0000 0000 0000 0000 0000 0000 0100

5

3

0000 0000 0000 0000 0000 0000 0000 0011

6

5

0000 0000 0000 0000 0000 0000 0000 0101

with m = -5 and n = -2, the result of the sorting will be

No.

Decimal number

Binary 32 bit representation

1

-4

1111 1111 1111 1111 1111 1111 1111 1100

2

-5

1111 1111 1111 1111 1111 1111 1111 1011

3

-3

1111 1111 1111 1111 1111 1111 1111 1101

4

-2

1111 1111 1111 1111 1111 1111 1111 1110

Given m, n and k (1 ≤ k ≤ min{n − m + 1, 2 147 473 547}), your task is to write a program to find a number corresponding to k-th representation in the sorted sequence.

Input

The input consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 1000. The following lines describe the data sets.

For each data set, the only line contains 3 integers m, n and k separated by space.

Output

For each data set, write in one line the k-th number of the sorted numbers.

Example

Sample input:
2
0 5 3
-5 -2 2

Sample output:
2
-5 

Added by:Lê Ðôn Khuê
Date:2006-12-28
Time limit:20s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:ACM ICPC 2006, Asia Regional Contest, site Hanoi









SPOJ Problem Set (classical)

1183. Accomodate the palace

Problem code: PALACE

There is a big palace in which rooms are constructed in the from of a square matrix.Now these rooms have to be filled with people.
As there are conflicts between people to maintain the equilibrium total number of people must be odd in every row and every column.
A room can accomodate only a single person.
Given the size of palace N one has to find total number of ways people can be accomodatede in that.

Input

First line consits of an integer K and then K test cases follow.

Output

For each test case you have to output the result%98777 in a seperate line.

Example

Input:
1
3
Output:
16

Added by:Abhilash I
Date:2006-12-30
Time limit:3s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:IIIT Hyderabad Local Programming Contest









SPOJ Problem Set ()

1267. Origin of Life

Problem code: ORIGLIFE

Conway's Game of Life is not really a game, but a cellular automaton -- a set of rules describing interactions among adjacent cells on a grid. In our game, we have an n by m rectangular grid of cells identified by integer coordinates (x, y). The game progresses through a series of steps; at each step a new generation is computed from the current generation. The game begins with the first generation. In any given generation, which we shall call the current generation, each cell is either live or dead. In the next generation, each cell's status may change, depending on the status of its immediate neighbours in the current generation. Two distinct cells (x1, y1) and (x2, y2) are immediate neighbours if they are horizontally, vertically, or diagonally adjacent; that is, if |x1 - x2 ≤ 1| and |y1 - y2 ≤ 1|. Each cell that is not on the border of the grid has eight immediate neighbours. There are three integer parameters (a, b, c) which affect the game. The rules of the game are:

  • If a live cell has fewer than a live neighbours in the current generation it dies of loneliness. That is, it is dead in the next generation.
  • If a live cell has more than b live neighbours in the current generation it dies of overcrowding. That is, it is dead in the next generation.
  • If a dead cell has more than c live neighbours in the current generation it is born. That is, it is live in the next generation.
  • Otherwise, a cell's status is unchanged from the current generation to the next.

This process continues indefinitely. Eventually, a generation may be repeated in which case life goes on forever. Or all the cells may die. Similarly, if we explore previous generations that may have led to the current one, we may find one that is necessarily a first generation; that is, it could not have been created from a previous generation by following the rules. Such a generation is known as a Garden of Eden. Given the game parameters and the current generation, you are to determine whether or not the game might have started with a Garden of Eden. If so, output the number of steps necessary to reach the current generation from the Garden of Eden. If there are several possible answers, find the smallest. If there is none, output -1.

Input

Input begins with a single integer, the number of test cases. For each test case, there are m+1 lines of input in total. The first line contains the game parameters, which are five integers m,n,a,b,c each separated by one space. The constraints are 1≤m≤4, 1≤n≤5, 1≤a<b≤8, 1≤c≤8. The next m lines each contain a string of n characters representing a row of the current generation. In the string, an asterisk ("*") indicates live while a period (".") indicates dead. There are no blank lines between test cases.

Output

Output is one integer per test case denoting the minimum number of steps required to reach the input from a Garden of Eden. If there is no Garden of Eden, output -1.

Example

Input:
1
4 5 2 3 2
.****
.****
.****
.****

Output:
2

Output Explanation:

Assume the sample input is the "current" generation. A possible previous generation is

**.**
..*.*
....*
*****

The above generation can be derived from the following previous generation

.****
**.*.
*****
*..*.

This generation cannot be derived from any other generation. Furthermore, there is no shorter series of generations that has these properties.


Added by:Bobby Xiao
Date:2007-01-24
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Canadian Computing Competition, 2006 Senior Stage 1









SPOJ Problem Set (classical)

1268. CN Tower (Easy)

Problem code: CNEASY

Christy C. Coder is traveling to Waterloo for a programming competition. On the way, she stops in Toronto to do some sightseeing. The unfortunate thing about travelling is that everyone back home expects her to bring back pictures of everything. Christy hates taking pictures: it makes her look like such a tourist! Fortunately, Christy has a plan to make her picture-taking quite painless.

At 553 m tall, CN Tower is the world's tallest free-standing building. 351 m up the tower is the "360" rotating restaurant, which rotates a full 360 degrees every 72 minutes. From there, Christy can see the whole city, and take close-up pictures of all the landmarks using her fancy new 100x optical zoom camera. Since the restaurant itself rotates, she only needs to stand in one place to take pictures in all directions.

The waiters insist that she order something or leave, and Christy is not interested in any of the items on the menu. Therefore, she must act quickly before she gets kicked out. Given the locations of the landmarks of which Christy wants to take a picture, your task is to determine the minimum amount of time that she must spend in the restaurant in order for it to rotate enough to bring all the landmarks in view. Assume that Christy always points her camera exactly perpendicular to the window to minimize distortion due to the glass. Note that multiple landmarks may occupy the same (angular) position, and these landmarks would only require one photograph to capture them.

Since the restaurant staff only realize she is a tourist once she starts taking pictures, we begin measuring the time required once she takes her first picture. Therefore, Christy can move to any position in the restaurant without hassle from the restaurant staff and begin taking pictures from there.

Input

The first line of input consists of the number of test cases. For each test case, the first line is an integer n (2 ≤ n ≤ 1000), the number of landmarks Christy wants to photograph. Each of the following n lines specify a landmark. Each landmark specification consists of the landmark name (a string of uppercase and lowercase letters of length at most 40 characters), a space, and the compass angle d, in degrees, to the landmark from the CN Tower (0 = north, 90 = east, 180 = south, 270 = west). Note that d is a real number which satisfies 0 ≤ d < 360, with d specified to the hundredth of a degree (i.e., at most two decimal places).

Output

For each test case, output a single integer, the minimum number of seconds that Christy must remain in the restaurant. If the time is not an integer number of seconds, round it up to the nearest second (i.e., take the ceiling of the number).

Example

Input:
1
5
CasaLoma 231.0
OntarioParliament 123.0
SkyDome 75.0
RoyalYorkHotel 340.0
PearsonAirport 165.0

Output:
3012

Added by:Bobby Xiao
Date:2007-01-24
Time limit:2s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All
Resource:Canadian Computing Competition, 2006 Senior Stage 2









SPOJ Problem Set ()

1269. CN Tower (Hard)

Problem code: CNHARD

Christy C. Coder is traveling to Waterloo for a programming competition. On the way, she stops in Toronto to do some sightseeing. The unfortunate thing about travelling is that everyone back home expects her to bring back pictures of everything. Christy hates taking pictures: it makes her look like such a tourist! Fortunately, Christy has a plan to make her picture-taking quite painless.

At 553 m tall, CN Tower is the world's tallest free-standing building. 351 m up the tower is the "360" rotating restaurant, which rotates a full 360 degrees every 72 minutes. From there, Christy can see the whole city, and take close-up pictures of all the landmarks using her fancy new 100x optical zoom camera. Since the restaurant itself rotates, she only needs to stand in one place to take pictures in all directions.

The elevator normally takes 61 seconds to get from the ground up to the rotating restaurant. Unfortunately, when Christy arrives at the CN Tower, she learns that the elevator is out of service, so she has to take the stairs, which takes somewhat longer. Christy arrives at the top at 9:36 pm, by which time it is dark. She can only take pictures with a very powerful flash, which takes a long time to recharge between pictures. While the flash is charging, she cannot take any pictures. Thus, Christy needs a new program to calculate the minimum time that she must spend in the restaurant in order for it to rotate enough to bring all the landmarks in view, and taking into consideration the charging time of the flash. In addition to these difficulties, the restaurant closes at midnight. Thus, Christy may not have enough time to take pictures of all the landmarks.

As before, assume that Christy does not move around in the restaurant after choosing her initial position, but waits for it to rotate to the angle required to take each picture. As with the daytime problem (CNEASY), Christy can (very quickly) pick her initial position, since the restaurant is not that big. Christy always points her camera exactly perpendicular to the window to minimize distortion due to the glass. After taking the last picture, Christy must stay in the restaurant until her flash recharges. Since it is dark outside, if more than one landmark occupies an angular position, Christy can capture only one one landmark per photo (in order to keep the desired landmark in focus, blurring all others).

Input

The first line of input consists of the number of test cases. For each test case, the first line is an integer n (1 ≤ n ≤ 1000), the number of landmarks Christy wants to photograph. Each of the following n lines specify a landmark. Each landmark specification consists of the landmark name (a string of uppercase and lowercase letters), a space, and the compass angle, in degrees (specified with a maximum of 2 decimal places), to the landmark from the CN Tower (0 = north, 90 = east, 180 = south, 270 = west). Finally, the last line contains the amount of time, in seconds, required for the flash to charge.

Output

For each test case, output a single integer, the minimum number of seconds that Christy must remain in the restaurant. If the time is not an integer number of seconds, round it up to the nearest second. If it is not possible for Christy to take all the pictures before closing, instead output "not possible".

Example

Input:
1
5
CasaLoma 231.0
OntarioParliament 123.0
SkyDome 75.0
RoyalYorkHotel 340.0
PearsonAirport 165.0
10

Output:
3022

Added by:Bobby Xiao
Date:2007-01-24
Time limit:4s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
Resource:Canadian Computing Competition, 2006 Senior Stage 2









SPOJ Problem Set (classical)

1270. Paint By Numbers

Problem code: PNTBYNUM

Years ago, there was a really bad craft/hobby called paint-by-numbers: you were given a line drawing, with numbers in each enclosed region, and the number corresponded to a particular colour. An example is shown below (unsolved on the left; solved on the right):


(images from ThisLife.org)

The problem you have to solve is much more linear, in a way.

You will be given an n-by-m grid (1 ≤ n, m ≤ 32) which you will "colour" in with either a dot ('.') or a star ('*').

Of course, the grid will not be specified in the usual paint-by-numbers way, since this would be too easy.

Instead, you will you have to infer which cells are blank and which contain a star. The only information you will be given are a collection of n + m sequences of numbers, one sequence for each row and column. The sequence will indicate the size of each continuous block of stars. There must be at least one dot between two consecutive blocks of stars.

An example is shown below (which is supposed to look fish-like):

You may notice that some paint-by-number patterns are not uniquely solvable. For this problem, you may assume that any solution which satisfies the specification is correct.

Input

Input begins with a line with the number of test cases. Each test case consists of a total of n + m + 2 lines. The first line of the test case consists of an integer n (1 ≤ n ≤ 32), the number of rows. The second line consists of an integer m (1 ≤ m ≤ 32), the number of columns. On the next n lines, there will be sequences which describe each of the n rows (from top to bottom). Each line will contain some positive integers, with a space between adjacent integers, and the sequence will terminate with the integer 0. On the next m lines describe the m columns (from left to right), the same format as the rows are specified.

Output

Output consists of n lines for each corresponding test case, each line composed of m characters, where each character is either a dot ('.') or a star ('*'). Separate test cases with a blank line.

Example

Input:
2
4
7
2 2 0
5 0
5 0
2 2 0
1 1 0
1 1 0
2 0
2 0
4 0
4 0
2 0
4
4
2 1 0
3 0
3 0
1 1 0
4 0
3 0
3 0
1 0

Output:
**..**.
..*****
..*****
**..**.

**.*
***.
***.
*.*.

Added by:Bobby Xiao
Date:2007-01-24
Time limit:5s
Source limit:50000B
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages:All except: ERL JS NODEJS PERL 6
Resource:Canadian Computing Competition, 2006 Senior Stage 2









SPOJ Problem Set (classical)

1285. Continuous Fractions Again

Problem code: CFRAC2


A simple continuous fraction has the form:


subir imagenes



where the ai’s are integer numbers.


The previous continuous fraction could be noted as [a1, a2, . . . , an]. It is not difficult to show that any rational number p / q , with integers p > q > 0, can be represented in a unique way by a simple continuous fraction with n terms, such that p / q = [a1, a2, . . . , an−1, 1], where n and the ai’s are positive natural numbers.


Now given a simple continuous fraction, your task is to calculate a rational number which the continuous fraction most corresponds to it.


Input

Input for each case will consist of several lines. The first line is two integer m and n,which describe a char martrix,then followed m lines,each line cantain n chars. The char martrix describe a continuous fraction The continuous fraction is described by the following rules:


  • Horizontal bars are formed by sequences of dashes `-'.


  • The width of each horizontal bar is exactly equal to the width of the denominator under it.
  • Blank characters should be printed using periods `.'


  • The number on a fraction numerator must be printed center justified. That is, the number of spaces at either side must be same, if possible; in other case, one more space must be added at the right side.

    The end of the input is indicated by a line containing 0 0.

    Output

    Output will consist of a series of cases, each one in a line corresponding to the input case. A line describing a case contains p and q, two integer numbers separated by a space, and you can assume that 10^20 > p > q > 0.

    Example

    Input:
    9 17
    ..........1......
    2.+.-------------
    ............1....
    ....4.+.---------
    ..............1..
    ........1.+.-----
    ................1
    ............5.+.-
    ................1
    5 10
    ......1...
    1.+.------
    .........1
    ....11.+.-
    .........1
    0 0
    
    Output:
    75 34
    13 12
    

    Added by:Camilo Andrés Varela León
    Date:2007-01-31
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:HNU Contest









    SPOJ Problem Set (classical)

    1296. 4 values whose sum is 0

    Problem code: SUMFOUR

    The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) belongs to A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n

    Input

    The first line of the input file contains the size of the lists n (this value can be as large as 4000). We then have n lines containing four integer values (with absolute value as large as 228 ) that belong respectively to A, B, C and D .

    Output

    Output should be printed on a single line.

    Example

    Input:
    6
    -45 22 42 -16
    -41 -27 56 30
    -36 53 -37 77
    -36 30 -75 -46
    26 -38 -10 62
    -32 -54 -6 45
    Output:
    5
    

    Added by:Abhilash I
    Date:2007-02-06
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:South western 05-06









    SPOJ Problem Set (classical)

    1325. Partial Sums

    Problem code: PARTSUM

    Given a sequence of positive integers a1, a2, ..., aN, and 1 ≤ ijN, the partial sum from
    i to j is ai + ai+1 + ... + aj.

    In this problem, you will be given such a sequence and two integers P and K. Your task is to find the smallest partial sum modulo P that is at least K.

    For example, consider the following sequence of integers:

    12     13     15     11     16     26     11

    Here N = 7. Suppose K = 2 and P = 17. Then, the answer is 2 because 11 + 16 + 26 = 53 and 53 mod 17 is 2. On the other hand, if K = 0 the answer is 0 since 15 + 11 + 16 + 26 = 68 and 68 mod 17 is 0.

    You may assume 1 ≤ N ≤ 100000.

    Input

    The first line of the input contains the number of test cases, T.

    Each test case begins with a line containing three integers, N, K and P. This is followed by the values of a1, a2, ..., aN, one per line.

    Output

    Output one line per test case, containing the smallest partial sum modulo P that is at least K, as described above.

    Example

    Input:
    1
    7 2 17
    12
    13
    15
    11
    16
    26
    11
    
    Output:
    2
    
    Warning: large Input/Output data, be careful with certain languages
    Added by:Stephen Merriman
    Date:2007-02-22
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Indian Computing Olympiad, Online Programming Contest, July 06









    SPOJ Problem Set (classical)

    1326. A Chase In WonderLand

    Problem code: CHASE

    Alice is in Wonderland. It is March and March Hare is raving mad. It begins to chase Alice. Alice runs as fast as she can, but she comes to the the edge of a quicksand pool. Now this pool has several safe spots where she may comfortably step on without being swallowed by the quicksand. She may step onto any safe spot from solid ground, but thereafter she can jump from spot to spot only in a straight line, and she cant turn back. March Hare is still hot on her heels, so she needs to know the maximum number of jumps she can make.

    Input

    On the first line there will be a single integer n, denoting the number of test cases. Each test case will consist of a single integer k by itself on a line, followed by k lines containing the x and y co-ordinates of the safe spots , seperated by a single space. Both coordinates are integer values. There are no leading or trailing spaces or blank lines. 0<k≤2200

    Output

    For each case print a single integer by itself on a line, with no leading or trailing spaces. Do not print blank lines.

    Example

    Input:
    2
    5
    0 0
    1 1
    2 2
    4 8
    2 75
    3
    0 0
    1 2
    3 4
    
    
    Output:
    2
    1
    

    Added by:Abhilash I
    Date:2007-02-22
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Code Craft 2007









    SPOJ Problem Set (classical)

    1329. Matrix

    Problem code: KPMATRIX

    The company you work in has got a secret job to do. Just a few persons know what it is all about. To keep a secret every programmer works on a small part of the project.

    Your job is as follows. You are given a matrix of integer numbers with N rows and M columns. Also two integer numbers A and B are given. Your task is to find a number of submatrices of a given matrix with the sum of elements between A and B inclusively.

    Input

    The first line contains two integer numbers N and M (1 ≤ N, M ≤ 250). After that matrix description follows. N lines with M numbers each. The last line contains two integer numbers A and B (-10^9 ≤ A ≤ B ≤ 10^9). All numbers separated with spaces. It's guaranteed that for every submatrix the absolute value of sum of it's elements will not exceed 10^9.

    Output

    Write to the output the number of submatrices of a given matrix with sum of their elements between A and B inclusively.

    Example

    Input:
    3 3
    1 0 0
    0 1 0
    0 0 1
    1 3
    
    Output:
    26
    

    Added by:Pavel Kuznetsov
    Date:2007-02-23
    Time limit:1s-10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:IT Festival Arkhangelsk 2006









    SPOJ Problem Set (classical)

    1335. Maze

    Problem code: KPMAZE


    The King of Byteland likes Greek mythology very much. The most impressive myth for him is the one about Minotaur. A creature which was imprisoned in a maze-like construction. Now The King wants to have similar maze. He ordered to his architect to build such construction.

    The architect decided that maze will have rectangular form. Its floor will be made from large square plates. Also there will be many walls, each of which will separate two common floor plates. From the bird's eye whole construction will look like a grid with some cells separated by walls. The maze should be very tricky, that's why he calls the maze correct if and only if for every two plates there is exactly one path between them. Here path is a sequence of moves between plates that share a common side and are not separated by wall. Each plate can only appear once in a path.

    Sooner or later, the architect started his work. After a couple of months he created a rectangular area with H rows and W columns. Also he has built K walls. Sounds perfect but he was seized with a lingering doubt about correctness of his maze.

    That's why he asks you to help him. He wants to know how many different correct mazes can be built based on his current maze i.e. you can only add new walls but not to break any of the old ones.

    For example (see figure 1.) the maze size is 2x2 and there are no walls. All four ways to complete this maze are shown on the right of the figure (new walls are dashed).

    Figure 1

    Figure 2. illustrates maze of size 3x3 with 3 walls. There are exactly 4 ways to complete it.

    Figure 2

    Figure 3. shows the maze that cannot be completed, because there is no path from lower right plate to upper left one.

    Figure 3

    Input

    The first line contains two integer numbers W and H (1 ≤ W, H ≤ 5). Second line contains one integer number K (K ≥ 0). Next K lines contain description of walls. Each wall is determined by two plates it separates. Thus, each line contains four integer numbers: R_1, C_1, R_2 and C_2, here R_1 and C_1 - row and column coordinates of the first plate. Similar, R_2 и C_2 - are coordinates of the second plate (1 ≤ R_1, R_2 ≤ H, 1 ≤ C_1, C_2 ≤ W). Rows are numbered from up to bottom, colums - left to right started from 1. It is guaranteed that all walls are correct and there are no duplicates. Walls that form perimeter of the maze will not be specified.

    Output

    Output the number of different correct mazes that can be built based on the given one. There should be no leading zeroes.

    Example

    Input:
    2 2
    0
    
    Output:
    4
    
    Input:
    3 3
    3
    3 1 3 2
    2 2 2 3
    2 3 3 3
    
    Output:
    4
    
    Input:
    3 3
    5
    3 1 3 2
    2 2 2 3
    2 3 3 3
    2 2 2 1
    1 2 2 2
    
    Output:
    0
    

    Added by:Pavel Kuznetsov
    Date:2007-02-24
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:IT Festival Arkhangelsk 2006









    SPOJ Problem Set (classical)

    1391. Summing to a Square Prime

    Problem code: CZ_PROB1

    SP2 = {p | p = x12 + x22 for some x1, x2 belonging to Z} is the set of all primes that can be represented as the sum of any two squares. The function SP2(n) gives the nth prime number from the set SP2. Now, given two integers n (0P2(n), k) where p(a, b) gives the number of unordered ways to sum to the given total ‘a’ with ‘b’ as its largest part. For example: p(5, 2) = 3 {2+2+1, 2+1+1+1, and 1+1+1+1+1}. Here 5 is the total with 2 as the largest part.

    Input

    The first line gives the number of test cases T followed by T lines of integer pairs, n and k.
    Scope:
    0 < T < 501
    0 < n < 501
    1 < SP2(n) < 7994
    0 < k < 4

    Output

    The p(SP2(n), k) for each n and k. Append a newline character to every test cases’ answer.

    Example

    Input:
    3
    2 2
    3 2
    5 3
    
    Output:
    3
    7
    85
    
    

    Added by:Rahul
    Date:2007-03-10
    Time limit:2s
    Source limit:3000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Sam Collins









    SPOJ Problem Set (classical)

    1418. The Cats and the Mouse

    Problem code: CATM

    In a rectangular field of size n by m squares there is a mouse and two cats. The mouse is the first to make a move, then each of the cats makes a move, then again its the mouse's turn, and so on. In each move both the mouse and the cats can move exactly one square vertically or horizontally. If the mouse is standing at the edge of the field then in its next move it can jump off the field and is saved from the cats. If in the next move one of the cats moves to the field with the mouse then there is no escape for the mouse ... =(

    You are to write a program which, knowing the initial positions of mouse and the two cats, will find out if there is any way for the mouse to escape from the cats, assuming of course that each cat will do its best to catch the mouse.

    Input

    In the first line of input two integers n and m are given, not exceeding 100, where n is the number of rows, and m - the number of columns. The second line contains a number k [k <= 10], which defines the number of test cases for the given field. In the next k lines the initial positions of the mouse and the cats are given. The position in the field is given by two numbers: the first is the number of the row, the second is the number of the column. The first two integers are the coordinates of the mouse, the next four integers are the coordinates of the cats.

    Output

    You must output k lines with answers for each test case. The answer is YES, if the mouse can escape or NO otherwise.

    Example

    Input:
    5 3
    3
    2 2 1 1 3 3
    2 3 1 3 5 2
    3 2 1 2 4 3
    
    Output:
    NO
    YES
    YES
    

    Author: Filimonenkov D.O.


    Added by:Roman Sol
    Date:2006-05-04
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ZCon 2007









    SPOJ Problem Set (classical)

    1419. A Game with Numbers

    Problem code: NGM

    Nikifor and Trofim play the following game: they write some integer smaller then 2000000000 and take turns one after another. Nikifor is the first to make a move. The turn is made by the following rule: from the written integer any non-zero digit is subtracted, and the new integer replaces the old one on the desk. For example for integer 40534, the next move can be: 40530, 40531 or 40529. The winner is the player who writes zero on the desk.

    Write a program to decide who will win if both players do their best.

    Input

    The input contains the integer from which the game is started.

    Output

    In the first line you must write 1 if Nikifor wins and 2 otherwise. If Nikifor wins then in the second line you must output the move in the first turn which guarantees victory for him. If there are many such moves then output any of them.

    Example

    Input:
    14
    
    Output:
    1
    4
    

    Author: Filimonenkov D.O.


    Added by:Roman Sol
    Date:2006-05-05
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ZCon 2007









    SPOJ Problem Set (classical)

    1420. Geometry and a Square

    Problem code: GEOM

    Is there anyone who doesn't love geometry?! Just imagine: on the plane you are given a square ABCD, with vertices given in the clockwise direction. Also given is a point P which is different from all of A, B, C or D. Have you imagined it? Interested? Ok, let's continue!

    Through vertex A a line a is drawn that is perpendicular to line BP, through vertex B a line b is drawn that is perpendicular to line CP, through vertex C a line c is drawn that is perpendicular to line DP, through vertex D a line d is drawn that is perpendicular to line AP. Do the lines a, b, c and d cross each other in one point? Ok, it depends on what the square is and what point P is given. Write the program that discovers if these lines cross in one point, and if so, finds the coordinates of this point.

    Input

    In the first line you are given the integer coordinates of the point in which diagonals of the square intersect. In the second line you are given one integer - the length of the side of the square. In the third line you are given the integer coordinates of point P. The integers do not exceed 100, in terms of absolute value.

    Output

    For each test case you must output YES if the sought point exsists, and NO otherwise. If you answer YES then in the second line you must output the coordinates of the intersection point. Coordinates must be rounded to one digit after the point.

    Example

    Input:
    10 10
    20
    5 12
    
    Output:
    YES
    8.0 5.0
    

    Author: Filimonenkov D.O.


    Added by:Roman Sol
    Date:2006-05-05
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:ZCon 2007









    SPOJ Problem Set (classical)

    1421. Goods

    Problem code: FIRM


    There are n dealers in the market. Each of them has some unique goods (nobody else has the same goods). Besides, each of them wants to obtain some other goods, which exist in the market. This is rather strange, but for each kind of goods on the market there exists exactly one dealer who wants to obtain it.

    To prevent fraud, only exchanges in pairs are allowed in this market. Moreover, each dealer is allowed to make at most one exchange a day. But the total number of transactions isn’t limited. A transaction means that all the goods of one dealer are exchanged for all the goods of the other participating dealer (partial transactions are not allowed).

    You are to write a program which outputs the minimum number of days needed for each dealer to get the goods that he wants. Also output one of the possible variants of exchanges leading to this goal.

    Input

    The first line contains an integer n [n <= 5000]. In the second line exactly n numbers of goods are given, which the dealers require. If integer j appears as the i-th at input, then this means that goods required by dealer i are initially owned by dealer j.

    Output

    You must output the minimum number of days m which are needed to complete the transactions. In the next m lines you must output the way these transactions should be managed by the dealers. One line corresponds to one day. At the beginning of each line you must output the number of transactions on this day. After that output the pairs of dealers who exchange their goods on this day. Dealers in pairs are separated by '-' symbol. If there are many ways to perform the exchanges then output any of them.

    Example

    Input:
    7
    2 1 3 5 6 7 4
    
    Output:
    2
    3 1-2 4-5 7-6
    1 5-7
    

    Author: Filimonenkov D.O.


    Added by:Roman Sol
    Date:2006-05-05
    Time limit:1s-10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ZCon 2007









    SPOJ Problem Set (classical)

    1431. Projections Of A Polygon

    Problem code: KPPOLY

    You are given a convex polygon on Cartesian coordinate system. It has projections on X and Y-axis. You can arbitrary rotate this polygon. What minimum and maximum sum of projections can you achieve?

    Input

    First line contains one integer number N (3 ≤ N ≤ 100) - number of polygon's vertices. Following N lines contain vertex coordinates Xi and Yi. All numbers are integers. Vertices are given in clockwise or anticlockwise direction. No two vertices coincide. No three consecutive vertices lie on the same line. All coordinates do not exceed 10000 by absolute value.

    Output

    Write minimum and maximum value of sum of the polygon's projections. Separate them by a space. Your answer should not differ with the correct one more than 10-6.

    Example

    Input:
    4
    0 0
    0 1
    1 1
    1 0
    
    Output:
    2 2.828427124
    

    Added by:Pavel Kuznetsov
    Date:2007-03-25
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:Vologda 2007









    SPOJ Problem Set (classical)

    1433. The Sum

    Problem code: KPSUM

    One of your friends wrote numbers 1, 2, 3, ..., N on the sheet of paper. After that he placed signs + and - between every pair of adjacent digits alternately. Now he wants to find the value of the expression he has made. Help him.

    For example, if N=12 then +1 -2 +3 -4 +5 -6 +7 -8 +9 -1+0 -1+1 -1+2 = 5

    Input

    Each line contains one integer number N (1≤ N ≤ 1015). Last line contains 0 and shouldn't be processed. Number of lines in the input does not exceed 40.

    Output

    For every line in the input write the answer on a separate line.

    Example

    Input:
    12
    0
    
    Output:
    5
    

    Added by:Pavel Kuznetsov
    Date:2007-03-26
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Vologda 2007









    SPOJ Problem Set (classical)

    1434. Equation

    Problem code: KPEQU

    You are given integer positive number N. Find the number of solutions in positive integer numbers of the following equation:

    1/N! = 1/X + 1/Y

    Input

    Each line of input file contains one integer number N (1 ≤ N ≤ 104). The last line contains 0 and shouldn't be processed. Number of lines in the input does not exceed 30.

    Output

    For every line in the input write the answer on a separate line.

    Example

    Input:
    1
    2
    0
    
    Output:
    1
    3
    

    Added by:Pavel Kuznetsov
    Date:2007-03-27
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Vologda 2007









    SPOJ Problem Set (classical)

    1435. Vertex Cover

    Problem code: PT07X

    You are given an unweighted, undirected tree. Write a program to find a vertex set of minimum size in this tree such that each edge has as least one of its end-points in that set.

    Input

    The first line of the input file contains one integer N --- number of nodes in the tree (0 < N <= 100000). Next N-1 lines contain N-1 edges of that tree --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).

    Output

    Print number of nodes in the satisfied vertex set on one line.

    Example 1

    Input:
    3
    1 2
    1 3
    
    Output:
    1
    
    Explanation:
    The set can be {1}
    

    Example 2

    Input:
    3
    1 2
    2 3
    
    Output:
    1
    
    Explanation:
    The set can be {2}
    

    Added by:Thanh-Vy Hua
    Date:2007-03-28
    Time limit:1.200s-8s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Co-author Amber









    SPOJ Problem Set (classical)

    1436. Is it a tree

    Problem code: PT07Y


    You are given an unweighted, undirected graph. Write a program to check if it's a tree topology.

    Input

    The first line of the input file contains two integers N and M --- number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).

    Output

    Print YES if the given graph is a tree, otherwise print NO.

    Example

    Input:
    3 2
    1 2
    2 3
    
    Output:
    YES
    

    Added by:Thanh-Vy Hua
    Date:2007-03-28
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:Co-author Amber









    SPOJ Problem Set (main)

    1437. Longest path in a tree

    Problem code: PT07Z

    You are given an unweighted, undirected tree. Write a program to output the length of the longest path (from one node to another) in that tree. The length of a path in this case is number of edges we traverse from source to destination.

    Input

    The first line of the input file contains one integer N --- number of nodes in the tree (0 < N <= 10000). Next N-1 lines contain N-1 edges of that tree --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).

    Output

    Print the length of the longest path on one line.

    Example

    Input:
    3
    1 2
    2 3
    
    Output:
    2
    

    Added by:Thanh-Vy Hua
    Date:2007-03-28
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:C C++ 4.0.0-8
    Resource:Co-author Amber









    SPOJ Problem Set (classical)

    1440. Use of Function Arctan

    Problem code: ARCTAN

    It's easy to know that arctan(1/2)+arctan(1/3)=arctan(1).The problem is,to some fixed number A,you have to write a program to calculate the minimum sum B+C.A,B and C are all positive integers and satisfy the equation below:

    arctan(1/A)=arctan(1/B)+arctan(1/C)

    Input

    The first line contains a integer number T(about 1000).T lines follow,each contains a single integer A, 1<=A<=60000.

    Output

    T lines,each contains a single integer which denotes to the minimum sum B+C.

    Example

    Sample input:
    1
    1
    
    Sample output:
    5
    

    Some new test data has been added on Feb.15, 2009, 36 users lose their Accepted.


    Added by:[Trichromatic] XilinX
    Date:2007-03-31
    Time limit:10s
    Source limit:256B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2001,Day 1; translated by Blue Mary









    SPOJ Problem Set (classical)

    1441. The Clever Typist

    Problem code: CLEVER

    Blue Mary is a typist of some secret department.Now she have to type in many passwords in an hour,each of which has a fixed length: 6.Of course,the less times she presses the keyboard,the happier she is.

    Unfortunately,the keyboard to type in the password is extraordinary designed to keep secrets.The keyboard has 6 particular keys instead of 10 number keys.To explain the uses of these keys,let's define the 6 position on the screen 1,2,3,4,5,6 from left to right.The keys' uses are shown below:

    • Swap0: swap the digit in the cursor position and the digit in position 1.The cursor doesn't move.If the cursor is now in position 1,the digits on the screen won't be changed.
    • Swap1: swap the digit in the cursor position and the digit in position 6.The cursor doesn't move.If the cursor is now in position 6,the digits on the screen won't be changed.
    • Up: increase the digit in the cursor position by 1.If the digit in the cursor position is 9,no change will happen.
    • Down: decrease the digit in the cursor position by 1.If the digit in the cursor position is 0,no change will happen.
    • Left: move the cursor one position left.If the cursor is in position 1,no change will happen.
    • Right: move the cursor one position right.If the cursor is in position 6,no change will happen.

    At start,6 random digits will be given on the screen,and the cursor will in position 1.After some smart presses,she can type in the correct password,at that time the cursor position is unimportant.

    Here is an example("()"denotes to the cursor):

    key pressed       screen
                      (1)23456
    Swap1             (6)23451
    Right             6(2)3451
    Swap0             2(6)3451
    Down              2(5)3451
    Right             25(3)451
    Up                25(4)451
    Right             254(4)51
    Down              254(3)51
    Right             2543(5)1
    Up                2543(6)1
    Swap0             6543(2)1
    

    Now Mary wants to know the minimal number of keys she has to press.Can you help her?

    Input

    The first line contains a single integer t(about 1000).t lines follow,each contains two 6-digit string,which show the digits on the screen at start and the password Mary is to type in,separated by a single space.

    Output

    t lines,each contains a single integer - the answer.

    Example

    Sample input:
    1
    123456 654321
    
    Sample output:
    11
    

    Some new test data has been added on Feb 15,2009. 26 users lose their Accepted.


    Added by:[Trichromatic] XilinX
    Date:2007-03-31
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2001,Day 1; translated by Blue Mary









    SPOJ Problem Set (classical)

    1442. Strange Food Chain

    Problem code: CHAIN

    There are 3 kinds of animals A,B and C. A can eat B,B can eat C,C can eat A. It's interesting,isn't it?

    Now we have n animals,numbered from 1 to n. Each of them is one of the 3 kinds of animals:A,B,C.

    Today Mary tells us k pieces of information about these n animals. Each piece has one of the two forms below:

    • 1 x y: It tells us the kind of x and y are the same.
    • 2 x y: It tells us x can eat y.

    Some of these k pieces are true,some are false. The piece is false if it satisfies one of the 3 conditions below, otherwise it's true.

    • X or Y in this piece is larger than n.
    • This piece tells us X can eat X.
    • This piece conflicts to some true piece before.

    Input

    The first line contains a single integer t.t blocks follow.

    To every block,the first line contains two integers n(1<=n<=50000) and k (1<=k<=100000). k lines follow,each contains 3 positive integers D(1<=D<=2),X,Y,separated by single spaces.

    Output

    t lines,each contains a single integer - the number of false pieces in the corresponding block.

    Example

    Sample input:
    1
    100 7
    1 101 1
    2 1 2
    2 2 3
    2 3 3
    1 1 3
    2 3 1
    1 5 5
    
    Sample output:
    3
    
    Hint:
    

    The false pieces are the 1st,the 4th and the 5th ones.

    Warning: large Input/Output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-03-31
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2001,Day 1; translated by Blue Mary









    SPOJ Problem Set (classical)

    1444. DEL Command II

    Problem code: DELCOMM2


    It is required to find out what's the maximum number of files that can be deleted from MS-DOS directory executing the DEL command of MS-DOS operation system only once. There are no nested subdirectories.

    A note

    DEL command has the following format: DEL wildcard


    The actual wildcard as well as a full file name can be made up of a name containing 1 up to 8 case-sensitive characters. In a wildcard the characters '?' and '*' can be used. A question mark substitutes exactly one character of the full file name, an asterisk any sequence of characters even empty one.


    MS-DOS system can permit maybe other wildcards but they can not be used in this task. File names consist only of Latin letters and digits.

    Input

    The first line of the input is an integer M, then a blank line followed by M datasets. There is a blank line between datasets.

    Input data for each dataset contains a list of full file names without any extra empty lines and spaces. Each name is written in a separate line of input data file and ended with a control sign: '+' for delete or '-' for keep. Full file names are not repeated. The list comprises at least one file, and at least one file is marked to be deleted. There are no more than 250 files.

    Output

    For each dataset, write to the first line of output the maximum number of files one DEL command can delete.

    Example

    Input:
    
    2
    
    BP +
    BPC +
    TURBO -
    
    EXCHANGE +
    EXT +
    HARDWARE +
    MOUSE –
    NETWORK –
    
    Output:
    
    2
    2
    
    Hint:

    For the two tests above,the corresponding DEL commands are DEL BP* and DEL EX*.

    Link

    You can try problem DELCOMM first. It's far easier than this problem.


    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:35s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 1997,Day 1









    SPOJ Problem Set (classical)

    1447. A Game of Toy Bricks

    Problem code: BRCKGAME

    Blue Mary invents a game with toy bricks. The player has N cuboids numbered from 1 to N.

    The rule of the game is discribed below:

    • Choose some cuboids among the N cuboids, and divide them into M(1 <= M <= N) piles,named them Pile1,Pile2 ... PileM. There are at least 1 cuboid in each pile. To make the game easier, for any cuboid in PileK,its id should greater than any one in PileK+1 (1 <= K < M).
    • For each pile of cuboids,the player will put them as a tower, and he should follow the two rules below:
    • The up surface of each cuboid is touched and only touched another down surface. Luckily,to make the pile looking like a tower,the up surface of the lower cuboid should cover the down surface of the higher cuboid,i.e. the length of the lower up surface is not less than that of the higher down surface, and also to the width.
    • In each pile,the lower cuboid has a less id than the higher cuboid.

    Your task is to find a method,to make the sum of the height of each pile maximum.

    Input

    The very first line of the input contain the number t,then t cases follow.

    For each case,The first line contain two integer number N and M. N(N<=100) is the total number of the cuboids, M(M<=N) is the number of the piles, separated by a single space.

    Then N line follow, which are the description of the cuboids 1..N. Each line contains three integer numbers(<=1000)- the length, width and height of that cuboid,separated by spaces.

    Output

    For each case, the output contains only one line with a single integer number - the maximum sum.

    Example

    Sample Input:
    1
    4 2
    10 5 5
    8 7 7
    2 2 2
    6 6 6
    
    Sample Output:
    24
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 1997,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1448. 3D Cover

    Problem code: COVER2

    In the 3D Cartesian coordinate system, there are n cubes.These cubes are all axis-paralleled. What's the volume of the union of these cubes?

    Input

    There is a single integer m in the very first line of the input, the number of test cases. m blocks follow.

    For each test, the first line contains a single integer n(1<=n<=100), the number of cubes. n lines follow, each contains four integers x,y,z,r(-1000<=x,y,z<=1000,1<=r<=200), separated by spaces. x,y,z are the X,Y,Z coordinates of the center of the cube, and r is the distance between the center and any surface of the cube.

    Output

    m lines,each contains a single integer - the answer.

    Example

    Sample Input:
    1
    3
    0 0 0 3
    1 -1 0 1
    19 3 5 6
    Sample Output:
    1944
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 1997,Day 2; description by Blue Mary









    SPOJ Problem Set (classical)

    1451. 01 Sequence

    Problem code: SEQ1


    The input consists of exactly 5 test cases in the following format:

    Input

    N A0 B0 L0 A1 B1 L1 [3<=N<=1000,1<=A0<=B0<=L0<=N,1<=A1<=B1<=L1<=N]
    

    Output

    Exactly 5 lines,each contains:

    a) A sequence (We name it S) consisting only characters '0' and '1' and no extra whitespaces, which satisfy the following conditions:

    • The number of '0' in any consecutive subsequence of S whose length is L0 is not more than B0 and not less than A0.
    • The number of '1' in any consecutive subsequence of S whose length is L1 is not more than B1 and not less than A1.

    or

    b)A single number -1,if the sequence which satisfies the conditions above doesn't exist.

    Example

    Input:
    6 1 2 3 1 1 2
    [and 4 test cases more]
    
    Output:
    010101
    [and 4 test cases more]
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 1999,Day 1; translated by Blue Mary









    SPOJ Problem Set (classical)

    1452. Birthday Cake

    Problem code: CAKE

    Adolf wants to send a cake to Blue Mary to celebrate her birthday. The cake looks like a tower which has M floors, each floor is a cylinder. The i-th cylinder counted from downside to upside has a integer height hi and a integer radius ri. These numbers fulfill the following two conditions:

    • h1 > h2 > h3 > ... > hM
    • r1 > r2 > r3 > ... > rM

    Adolf is interested in minimising the area of the surface of the cake, except for the underside of the lowest cylinder. He needs your help because of his poor math knowledge.

    Input

    The very first line contains a integer number T. T test cases follow.

    For each test case, the first line contains a single integer number N (N<=10000), the second line contains a single integer number M (M<=10). The cake must be made of M cylinders and its volume must be N*Pi.

    Output

    For each test case, a single line containing a single integer S must be written to output. The required minimum area must be S*Pi.

    Example

    Sample Input:
    1
    100
    2
    
    Sample Output:
    68
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 1999,Day 1; translated by Blue Mary









    SPOJ Problem Set (classical)

    1453. Optimal Connected Subset

    Problem code: OPTSUB


    • A point P(x,y) is called an integer point if and only if both x and y are integers.
    • W is the set which contains all the integer points on the plane.
    • Two integer point P(x,y) and Q(x',y') are called adjacent if and only if |x-x'|+|y-y'|=1.
    • S is a set of integer points if and only if S is a limited subset of W.
    • If S is a set of integer points, R and T belong to S,and there exist a limited integer point sequence Q0(=R),Q1,Q2,...,Qk,Qk+1(=T) which satisfies that
      • Qi!=Qj iff i!=j
      • Qi and Qi+1 are adjacent, for each 0<=i<=k.
      • Qi belongs to S, for each 0<=i<=k+1.
      we call R and T are connected and the sequence Qi(0<=i<=k) is a path that connect R and T.
    • If S is a set of integer points, X and Y are some integer points that belong to S, there exists one and only one path connected X and Y, then S is called an optimal set.

    Given an optimal set V, your task is to find an optimal set B, satisfying that B is a subset of V and the sum of the weights of each integer point is maximum.

    Input

    The very first line of the input contains a single integer T, the number of test cases. T blocks follow.

    For each test case, the first line contains a single integer N=|V|(N<=1000). N lines follow, each contains 3 integers, the X-coordinate, the Y-coordinate and the weight(the absolute value of the weight<=100) of the ith integer point, separated by single spaces.

    Output

    T lines,each contains a single integer - the maximum sum of weights.

    Example

    Input:
    1
    5
    0 0 -2
    0 1 1
    1 0 1
    0 -1 1
    -1 0 1
    
    Output:
    2
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 1999,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1454. Memory Distribution

    Problem code: MEMDIS


    EMS memory (called memory for short) is some important resource of a computer. When a program is running, the computer must distribute the memory for it.

    The classical memory distribution process is like the following:

    • The basic unit of the memory is called a cell, each cell is assigned to a fixed integer number called its address. The address starts from number 0. If two cell's address numbers are two consecutive integer numbers, the two cells are called (logically) consecutive. We name the s consecutive cells starting from address i a piece whose length is s and first address is i.
    • Many programs need memory during their running. For each program, we need a application time X, a number of cells needed M and a running time P to describe it. When the program is running(during it starts running (time T) to T+P, including the left end and excluding the right end),The M cells cannot be used by other programs.
    • Suppose a program apply M cells at time X and its running time is P,then
      • (A) If there is a piece in the memory at time X, each cell of which is not being used, and whose length is M, the computer will distribute these M cells to this program. If there are more pieces, the computer will choose the one whose first address is minimum.
      • (B) If such piece does not exist at time X, the program will be put into a queue.If after some time, there exist a piece whose length is M and the corresponding program is at the head of the queue, the computer will pop this program and distribute memory for it like (A) immediately. During the process of memory distribution, the programs which are not at the head of the queue cannot start to run before the one at the head of the queue.

    Input

    Ten test cases (given one after another, you have to process all!).For each test case:

    The first line is a number N, which shows the number of memory cells. There addresses are 0..n-1. Less than 10000 lines follow, each contains 3 integers X, M(M<=N), P describing the programs. A line containing three zeroes denotes the end of a test case. The programs have been sorted by there application time X.

    All numbers in the input and output file will be less than 109.

    Output

    For each test case output two lines. The first line contains a single integer, which shows the time when all the programs have been run and stops normally. The second line contains a single integer, which is the number of programs which has been put into the queue.

    Example

    Input:
    10
    1 3 10
    2 4 3
    3 4 4
    4 1 4
    5 3 4
    0 0 0
    [and 9 test cases more]
    
    Output:
    12
    2
    [and 9 test cases more]
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:17s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 1999,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1455. Program Analyser

    Problem code: ANALYSER

    Input

    A Program which has the following format:

    <Program>::=<sentence><line break>{<sentence><line break>}
    <setence>::=<level><space><body>
    <body>::=<addition> | <output> | <goto> | <condition> | <end>
    <addition>::=<variable>+<integer>
    <output>::=<variable>?
    <goto>::=GO<space><level>
    <condition>::=IF<space><variable>=<integer><space><goto>
    <end>::=END
    <variable>::=<character>
    <level>::=<integer>
    <integer>::=<digit>{<digit>}
    <character>::=A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z
    <digit>::= 0|1|2|3|4|5|6|7|8|9
    <line break>::=(ASCII 10)
    <space>::=(ASCII 32)
    

    The program runs following the following rules:

    • Program starts from the sentence whose level is minimum, and executed by the level from low to high except that the sentence is<goto>or<condition>.
    • All variables are initialized to 0.
    • <Addition>means<variable>+=<integer>in C++.
    • <output>means write the value of<variable>to the output file(we aren't interesting about the real output file.)
    • <condition>means if and only if the value of the <variable> equals to <integer>, <goto> will be executed, otherwise the next sentence executed is as usual.
    • After<goto>, the next sentence executed is the sentence with level which equals to the level in<goto>.
    • Program terminates by itself when <end> is executed.
    • The numbers during the program is running will fit in a signed 32-bit integer.
    • The number of sentences in the program is not more than 100.
    • The length of each line in the input file is not more than 20.
    • The input is correct.
    • The sentence with the maximum level is always <end>.
    • Any level is not more than 3000.

    Input terminate by EOF.

    Output

    Output the number of sentences executed.If the program can not terminate by itself,output -1.

    Example

    Input:
    10 A+1
    20 IF A=5 GO 60
    60 END
    30 A+2
    40 A?
    50 GO 20
    
    Output:
    11
    
    Hint:
    10->20->30->40->50->20->30->40->50->20->60
    

    Note

    You may try problem ANALYS_T first. It's the same problem with this one and its time limit is not so strict.

    Log

    The time limit of this problem has been changed from 0.4/0.5 second to 1 second per test on Jun.5, 2008. All the solutions have been rejudged.


    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2000,Day 1; translated by Blue Mary









    SPOJ Problem Set (classical)

    1457. Help Blue Mary Please! (Act I)

    Problem code: BLUEEQ

    This morning Blue Mary wrote some equations on a piece of paper and left it on her desk. After solving some problems in SPOJ, she found that her classmate H.L. replaced all characters on the paper with some other ones. H.L. told her he replaced the same characters with the same ones, and different characters with different ones because of his goodness. Now Mary needs your help to get the original equations back.

    In Mary's equations, only 13 characters appear:0,1,2,3,4,5,6,7,8,9,+,*,=. There is one and only one "=" in each equation. In H.L.'s equations,only 13 Latin letters appear: a,b,c,d,e,f,g,h,i,j,k,l,m. All the equations are correct in decimal notation.

    For example. If Mary wrote down 2+29=31, H.L. replaced 2 with i, + with l, 9 with k, = with e, 3 with m and 1 with a, we got ilikema .

    Input

    The first line contains a single integer t.t blocks follow.

    To every block,the first line contains a single integer n(1<=n<=1000). n lines follow,each contains a string whose length is more than 4 and less than 12.The string contains only a-m and doesn't contain any whitespaces.

    At least 90% of test cases satisfy that n<=5.

    At least 80% of test cases satisfy that n<=2.

    In at least 70% of test cases, there are at most 5 different characters in all the equations.

    Output

    If there doesn't exist n equations that can be translated to H.L.'s equations,print a line contains the word noway .Otherwise you should output all the corresponding relations that can be fixed in lexicographic order,see the example.

    Example

    Input
    1
    2
    abcdec
    cdefe
    
    Output
    a6
    b*
    d=
    f+
    

    hint

    The two strings can be translated to the following equations possibly:

    6*2=12 2=1+1
    6*4=24 4=2+2
    6*8=48 8=4+4
    

    So the corresponding relations above can be fixed,others can not.


    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:17s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2000,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1458. Help Blue Mary Please! (Act II)

    Problem code: BLUEEQ2

    Today Mary's math homework is to solve an equation.

    She knows all ki and pi, and 1<=xi<=M. All xi must be integers. She must work out the number of different solutions of this equation this day.Can you give her a hand?

    Input

    There is a single integer T in the very first line of the input denoted the number of tests.T blocks follow.

    For each test case:

    The first line contains a single integer n(n<=6).The second line contains a single integer m(m<=150).n lines follow,each contains two space-separated integers ki and pi, i=1,2,...,n. All pi are positive.

    Output

    For each test case output a single line ,which contains a single integer - the answer.You may assume this number is less than 2^31.

    Example

    Input:
    1
    3
    150
    1 2
    -1 2
    1 2
    
    Output:
    178
    
    Warning: The time limit is very strict for this problem.

    Blue Mary's Note: test data were modified on Dec.4, 2007. All the solutions have been rejudged.


    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:11s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2001,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1459. The Secret of an Aerolite

    Problem code: AEROLITE

    A huge aerolite had fallen in Antarctica!!!Many disasters happened and lots of people lost their lives, homes or even everything.Blue Mary, the well-known scientist, is to work out the secret of this aerolite for further study.

    Blue Mary has found out that their are some numbers on this aerolite, 5 per line:

    1 1 1 1 6
    0 0 6 3 57
    8 0 11 3 2845
    

    With her genius, Blue Mary knows that the 5th number is the key to solve the problem, but in some lines the 5th numbers were destoryed and we cannot know what they are instantly.

    After some days, she finds out the way to calculate the 5th number finally, which is:

    • A Regular Expression(RE) is a string which only contains characters '{','[','(',')',']','}' and satisfies the rules below.
    • An empty string is an RE.
    • If there's no character '[',']','{','}' in RE A, then (A) is an RE.
    • If there's no character '{','}' in RE A, then [A] is an RE.
    • If A is an RE, {A} is an RE.
    • If both A and B are REs, AB is an RE.

    For example "()(())[]", "{()[()]}", "{{[[(())]]}}"(all without quotes) are REs and "()([])()","[()" are not REs.

    The deep of an RE A, D(A), is defined as below:

    • If A is an empty string,D(A)=0;
    • If A can be written as BC, D(A)=max(D(B),D(C));
    • If A can be written as (B) or [B] or {B}, D(A)=D(B)+1.

    Such as D("(){()}[]")=2.

    Suppose the first 4 numbers in current line are L1,L2,L3 and D, then the 5th number in current line is the number of REs modudo 11380.Each of the REs must have a depth of D and is made of L1 {}, L2 [] and L3 ().

    Now Mary needs your help to work out the 5th number.

    Input

    Input contains exactly 10 test cases.Each test case contains one line, which contains 4 numbers L1,L2,L3,D(0<=L1,L2,L3<=10, 0<=D<=30), separated by single spaces.

    Output

    Ten lines, each contains a single integer denoted the 5th number.

    Example

    Input:
    1 1 1 1
    0 0 6 3
    1 1 1 2
    [and 7 test cases more]
    
    Output:
    6
    57
    8
    [and 7 test cases more]
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2001,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1460. A Simple Calculator in the Galaxy

    Problem code: GALAXY

    Background

    So if you want to survive the Earth's demise and see the galaxy, make sure you are wearing something more substantial than pajamas and a ratty bathrobe, watch the skies for flying saucers, start worrying when all the dolphins on the planet vanish, and keep your eyes peeled for an electronic gizmo with the words "Don't Panic" printed in large friendly letters on the cover.

    --The Hitchhiker's Guide to the Galaxy

    Problem

    Addition,subtration and multiplication is necessary wherever you are in the galaxy.You are to write a program to perform these operations, and you can see 6*7=42 or 67-25=42 or 31+11=42, maybe one of them is the problem of Life, the Universe and Everything.

    Please note that the solution may only be submitted in Brainf**k, Whitespace and Intercal, other languages like C/C++/Pascal/Java are not allowed! If you want to use other languages to solve this problem, you may try this one.

    Input

    Multiple test cases, the number of them T is given in the very first line, T<=99.

    Each test case contains one line which has the following form:

    num oper num

    where num is an integer number between 1 and 99, and oper is '+' or '-' or '*' (without quotes).

    There's no extra whitespace and leading zero in the input.

    Output

    For each test case you should output one line which contains the answer without any leading zeros.You may assume this number is always a positive one.

    Example

    Input:
    3
    6*7
    67-25
    31+11
    
    Output:
    42
    42
    42
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:17s
    Source limit:17000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:BF ICK WSPC
    Resource:Folklore, description and test data by Blue Mary









    SPOJ Problem Set (classical)

    1461. Greedy Hydra

    Problem code: DRAGON

    Hydra is some very greedy animal. A hydra has 9 heads when he is born, and many more new heads will come out when he grows up. Of course, some old heads will break off because of caducidy.

    One day, a hydra with M heads finds a tree with N fruits on it. He is very delighted and wants to eat this tree instantly. Since he has M heads, he must divide these N fruit into M groups, each group contains at least 1 fruit, and each head will eat a group of fruits.

    The biggest head among the M heads is named "Boss", it must eat neither more nor less than K fruits, and, in the nature of things, the biggest fruit included. These fruits are connected by N-1 branches, and there exists a path made up with branches between each pair of fruit.

    If two fruit connected by a single branch is put in different groups, the corresponding two heads will break the branch and eat the two fruits, otherwise the corresponding head will eat the two fruits without breaking the branch. Eating branches is not very comfortable of course, so every branch has a weight of illness, and the weight of illness of this hydra is the sum of the weights of illness of all brances he has eaten.

    Your task is to help the hydra to minimize his weight of illness.

    The picture below is an example.

    N=8,M=2,K=4.The bigger head eats 4 fruits(full points), the smaller head eats 4 fruits(empty points). The branch signed by a thin segment is eaten by the hydra.

    Input

    Ten test cases(Given one after another, you have to process all!). For each test case the first line contains 3 integers N(1<=N<=300),M(2<=M<=N),K(1<=K<=N), separated by single spaces. The N fruits are numbered 1..N, and the biggest fruit is always numbered 1. N-1 lines follow, each contains 3 integers i,j,k separated by spaces denoted that there is a branch between fruit i(1<=i<=N) and fruit j(1<=j<=N) and the weight of illness of this branch is k(0<=k<=100000).

    Output

    Ten lines, each contains a single integer - the minimum weight of illness of the hydra. If we can't divide the fruit into M groups, output "-1"(without quotes).

    Example

    Input:
    8 2 4
    1 2 20
    1 3 4 
    1 4 13
    2 5 10
    2 6 12
    3 7 15
    3 8 5
    [and 9 test cases more]
    
    Output:
    4
    [and 9 test cases more]
    

    Link

    After solving this problem you can try the problem DRAGON2.

    Blue Mary's Note: test data has been modified on Dec.12, 2007. All the solutions have been rejudged.


    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:9s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2002,Day 1; translated by lcosvse









    SPOJ Problem Set (classical)

    1462. Barbarians

    Problem code: BARB

    There are N Barbarians living on an unknown island. On the island there are M caves, we can number them 1, 2, ..., M clockwise. When we find the island, the barbarians are living in N distinct caves numbered C1,C2,...,CN.Every year each barbarian walks out of his cave and goes along the road,passes Pi caves and then go into that cave.Every Barbarian has a living time: Li years, after Li years the ith barbarian died.

    We are surprised to find out that no two barbarians live in one cave in the same year so no conflicts have happened.We are interesting about the minimum number of caves on the island.

    Please note that this problem has a somewhat strict source limit and time limit.

    Input

    The very first line contains a single integer T,the number of test cases.T blocks follow.

    For each test case, the first line contains a single integer N(N<=15).N lines follow,each contains 3 integers Ci(1<=Ci<=100),Pi(1<=Pi<=100),Li (1<=Li<=1,000,000).

    Output

    For each test case, the first and only line contains a single integer M - the answer.You may assume M<=1,000,000.

    Example

    Input:
    1
    3
    1 3 4
    2 7 3
    3 2 1
    
    Output:
    6
    Hints
    -------------------------------------------------
    | Year | Barb. No.1 | Barb. No. 2 | Barb. No. 3 |
    -------------------------------------------------
    |  0   |     1      |      2      |      3      |
    -------------------------------------------------
    |  1   |     4      |      3      |      5      |
    -------------------------------------------------
    |  2   |     1      |      4      |    Died     |
    -------------------------------------------------
    |  3   |     4      |      5      |    Died     |
    -------------------------------------------------
    |  4   |     1      |    Died     |    Died     |
    -------------------------------------------------
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:5s
    Source limit:2048B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2002,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1463. Robot Number M

    Problem code: ROBOT

    Blue Mary, the well-known astronaut, had sent Robot No.1 to Mars finally.Robot No.1 was so smart that he could make one robot per second.

    Assume the time Robot No.1 arrived was second 1. At second i, Robot No.1 made a new Robot: Robot No.i. (i>=2)

    The new robots started work as soon as he was produced successfully. Robot No.M only had a rest at second t, where t is a multiple of M. For example, Robot No.3 worked at second 4,5,7,8,... and had a rest at second 6,9,...

    When a robot was having a rest, he could send his own informations to the newly produced robot. For example, when Robot No.6 was produced successfully, Robot No.2 and Robot No.3 are having a rest, so Robot No.6 would get informations from Robot No.2 and No.3. We call Robot No.2 and No.3 are teachers of Robot No.6.

    We call two Robots are independent if each of them wasn't a teacher of the other one and they had no common teachers. Please note that Robot No.1 was independent to any other robots and wasn't a teacher of any other robots, since only Robot No.1 could make robots.

    The good number of Robot No.M is the number of robots who was produced earlier than No.M and independent to No.M. Here are some examples:

    The good number of Robot No.1 is 0.

    The good number of Robot No.2 is 1. No.1 was that robot.

    The good number of Robot No.6 is 2. No.1 and No.5 were those robots. No.2 and No.3 were his teachers. No.4 and him had a common teacher: No.2.

    The Robots had 3 kinds of occupations. To Robot No.M:

    • If M can be written as the multiple of an even number of distinct odd primes, he was a businessman.
    • If M can be written as the multiple of an odd number(1 included) of distinct odd primes, he was a hacker.
    • All other robots were doctors.

    Now Blue Mary was interesting to Robot No.M. She wants to know the sum of good numbers of all businessmen, hackers and doctors among Robot No.M and his teachers. She comes up with the answer quickly, and so can you.

    Blue Mary is so kind that she gives you the prime divisors of M and you can only tell her the answers modudo 10000.

    Input

    The very first line contains a single integer T,the number of test cases.T blocks follow.

    For each block, the first line contains a single integer K.K lines follow, each contains two integers pi and ai separated by a single space.

    M = p1a1 * p2a2 * p3a3 * ... * pKaK.

    You can assume that:

    • All pi are distinct primes and are less than 10,000.
    • p1 < p2 < p3 < ... n.
    • All ai are positive and no more than 1,000,000.
    • 1 <= k <= 1000.

    Output

    For each test case, output 3 lines.

    The first line contains a single integer denotes to the sum of good numbers of all businessmen among Robot No.M and his teachers modudo 10000.

    The second line contains a single integer denotes to the sum of good numbers of all hackers among Robot No.M and his teachers modudo 10000.

    The third line contains a single integer denotes to the sum of good numbers of all doctors among Robot No.M and his teachers modudo 10000.

    Example

    Input:
    1
    3
    2 1
    3 2
    5 1
    
    Output:
    8
    6
    75
    

    Hints

    In the sample input, M=21*32*51=90. Robot No.90 has 10 teachers.Among Robot No.90 and his teachers, Robot No.15 is a businessman; No.3 and No.5 are hackers; all others are doctors, their numbers are 2,6,9,10,18,30,45,90.


    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2002,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1464. Editor II

    Problem code: EDIT3

    Background

    After trying to solve problem EDIT1(Editor) and being ****ed by Brainf**k, Blue Mary decided to set another difficult problem about editor.

    Description

    Some definations:

    • Text: It's a sequence that consists characters whose ASCII code is in [32,126].
    • Cursor: It's a sign for pointing out the current position.It can be at the start or the end of the text or between two consecutive characters of the text.

    Editor is a structure.It contains one text and one cursor.The operations are listed below:

    --------------------------------------------------------------------------
    | Name        | Input format |              function                     |
    --------------------------------------------------------------------------
    | Move(k)     | Move k       | Move the cursor after the kth character   |
    |             |              | in the text. If k=0, you should put       |
    |             |              | the cursor at the start of the text.      |
    --------------------------------------------------------------------------
    | Insert(n,s) | Insert n s   | Insert string s whose length is n(>=1)    |
    |             |              | after the cursor.The cursor doesn't move. |
    --------------------------------------------------------------------------
    | Delete(n)   | Delete n     | Delete n(>=1) characters after the cursor.|
    |             |              | The cursor doesn't move.                  |
    --------------------------------------------------------------------------
    | Get(n)      | Get n        | Output n(>=1) characters after the cursor.|
    --------------------------------------------------------------------------
    | Prev()      | Prev         |  Move the cursor one character forward.   |
    --------------------------------------------------------------------------
    | Next()      | Next         |  Move the cursor one character backward.  |
    --------------------------------------------------------------------------
    

    If the text of a editor is empty,we say the editor is empty.

    Here is an example._ denotes to the cursor,$ denotes to the start and the end.At start the editor is empty.

    ------------------------------------------------------------------------------
    |         Operation          |  Text after the operation |        Output     |
    ------------------------------------------------------------------------------
    | INSERT(13,"Balanced tree") |  $_Balanced tree$         | $$                |
    ------------------------------------------------------------------------------
    | MOVE(2)                    |  $Ba_lanced tree$         | $$                |
    ------------------------------------------------------------------------------
    | DELETE(5)                  |  $Ba_d tree$              | $$                |
    ------------------------------------------------------------------------------
    | NEXT()                     |  $Bad_ tree$              | $$                |
    ------------------------------------------------------------------------------
    | INSERT(7," editor")        |  $Bad_ editor tree$       | $$                |
    ------------------------------------------------------------------------------
    | MOVE(0)                    |  $_Bad editor tree$       | $$                |
    ------------------------------------------------------------------------------
    | GET(15)                    |  $_Bad editor tree$       | $Bad editor tree$ |
    ------------------------------------------------------------------------------
    

    Your task is:

    • Build an empty editor.
    • Read some operations from the standard input and operate them.
    • For each Get operation, write the answer to the output.

    Input

    the very first line contains the number of testcases T(T<=4).T tests follow.

    For each test, the first line is the number of operations N.N operations follow.

    Blue Mary is so depressed with the problem EDIT1 that she decides to make the problem more difficult.So she inserts many extra line breaks in the string of the Insert operation.You must ignore them.

    Except line breaks, all the charaters' ASCII code are in [32,126]. There's no extra space at the end of a line.

    You can assume that for each test case:

    • No invalid operation is in the input.
    • Number of move operations is no more than 50000.
    • Number of the total of insert and delete operations is no more than 4000.
    • Number of the total of prev and next operations is no more than 200000.
    • The characters inserted will not more than 2MB.The valid output will not more than 3MB.

    Output

    The output should contain T blocks corresponding to each testcase.

    For each test case, the output should contain as many lines as the get operations in the input.Each line should contains the output of each get operation.

    Example

    Input:
    1
    15
    Insert 26
    abcdefghijklmnop
    qrstuv wxy
    Move 15
    Delete 11
    Move 5
    Insert 1
    ^
    Next
    Insert 1
    _
    Next
    Next
    Insert 4
    .\/.
    Get 4
    Prev
    Insert 1
    ^
    Move 0
    Get 22
    
    Output:
    .\/.
    abcde^_^f.\/.ghijklmno
    
    Warning: large Input/Output data, be careful with certain languages

    Blue Mary's note: the test case #1 has something wrong and it has been fixed on April 27th, 2007.Solutions has been rejudged. Please accept my apology.


    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2003,Day 1









    SPOJ Problem Set (classical)

    1465. On the Way to Find Chris

    Problem code: CHRIS

    Do you know the famous game THE KING OF FIGHTERS? If the answer is yes, I'm sure you know THE THREE BLACK GROUP: Chris, Shermie and Yashiro. Today Chris is invited to one of his friends' home to play THE KING OF FIGHTERS.Blue Mary is now at Chris' home, she knows where Shermie's and Yashiro's home is, but she doesn't know where Chris actually is.So she decides that:

    • If Yashiro's home is nearer than Shermie's, she will go to Yashiro's home first, if she doesn't find Chris, she will then go to Shermie's, and vice versa.
    • The map of the city is strange. Each of the houses is assigned to a unique number in the range[1,n], where n is the number of houses. Between some pairs of houses there are some roads. There exists one and only one path from any house to any other house. She will go along the only path between the two houses.

    Unfortunately, you don't know where Chris' home actually is, and the same as Yashiro's and Shermie's. Now you are interesting in the maximum time from the time when Blue Mary starts from Chris' home to the time when Blue Mary finds Chris in the worst case.

    Input

    The number of test cases T is given in the very first line.T blocks follow.

    For each test case, the first line contains 2 space-separated integers N(3<=N<=200000) and M, which denotes the number of houses and the number of roads in the city.M lines follow, each contains 3 space-separated integers x,y,z(1<=x,y<=n,1<=z<=109).It tells us there exist a road between house No.x and house No.y, and to go from x to y or from y to x along this road will take z minutes.No two roads are repeated.

    Output

    For each test case you should output a single line, which contains a single integer - the maximum time measured in minutes.

    Example

    Input:
    1
    4 3
    1 2 1
    2 3 1
    3 4 1
    
    Output
    4
    
    Warning: large Input/Output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2003,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1466. Blue Mary Needs Help Again

    Problem code: CASHIER

    Blue Mary is a cashier of a big company.The boss of this company is so annoying that he always increases or decreases wage of all workers.He increases all the workers' wage with a same number when he is happy or decreases all the worker's wage with a same number when he is depressed.

    All the workers are angry with the boss, especially when he decreases their wage. A worker will leave the company and never go back when he finds his wage is lower than the least wage written on his contract. Blue Mary must delete the worker's files at that time. Another task she is to do is to build a file when a new worker joins this company.

    The boss usually asks Blue Mary how much money the worker who gets the k-th most wage gets. Blue Mary is very tired with her work. Could you give her a hand?

    Input

    T

    [the number of tests <= 10]

    M MIN

    [M is the number of commands below, MIN is the least wage]

    C K

    [C is one of the 4 characters I,A,S,F. I denotes that Mary should build a new file, and the new worker's wage is K(0<=K<=100000) at start.If K is less than MIN, the worker will not join the company. A denotes that the boss increases all the workers' wage with K(0<=K<=1000). S denotes that the boss decreases all the workers' wage with K(0<=K<=1000). F denotes that the boss asks Blue Mary a question: how much money does the worker who gets the k-th most wage get(K>0)?]

    [M-1 other commands]

    [other tests]

    You may assume that:

    • The number of worker in the company at start is 0.
    • The number of command I is no more than 100000.
    • The total numner of command A and S is no more than 100.
    • The number of command F is no more than 100000.

    Output

    For each test case:

    For each F command you must output one line contains a single integer which is the answer or -1 if K is more than the number of workers in the company at that time.

    In the last line you must output a single integer - the number of workers who leave the company(excluded the ones who don't join the company)

    Example

    Sample Input:
    1
    9 10
    I 60
    I 70
    S 50
    F 2
    I 30
    S 15
    A 5
    F 1
    F 2
    
    Sample Output:
    10
    20
    -1
    2
    
    Warning: large Input/Output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2004,Day 1; translated by Blue Mary









    SPOJ Problem Set (classical)

    1468. Outside it is now raining

    Problem code: RAIN2

    Country M is pluvian. In City P, it rains frequently and many people complain that they always have trouble crossing the streets when raining. To make people cross the streets easier, the government set many "Automatic Umbrellas" above every crosswalk, shown in the picture below.

    Each of these "Automatic Umbrellas" looks like a rectangle board, and their thickless is approximate zero. They can sop up the rain instantly. They are left unused when it's not raining and shuttle from one side to another in the same speed otherwise. The walkers will not be wringing-wet if he walks under the umbrella when it's raining.

    When many people want to cross the street, one "Automatic Umbrella" is not enough obviously. The government set many "Automatic Umbrella" on some main crosswalks. The width of each of the "Automatic Umbrella" equals to the width of the crosswalk, and any two of these umbrellas have different height.Their length and speed may be different.

    You are to write a program to calculate the total volume of the rain falling to the ground from the time when it starts to rain to T seconds later.

    Input

    The very first line comes a single integer Q, the number of test cases.Q blocks follow.

    For each test case:

    The first line contains 4 space-separated integers N(<=10), W(<=100), T(<=100), V(<=50), the number of "Automatic Umbrella", the length of the crosswalk in meters, the total time in seconds and the volume of rain falling to the ground per square meter per second.

    To simplify the description, we can build a Cartesian coordinate system in the following way: let the left side of the street be the origin, the street be the positive Ox-axes, and the vertical line to the ground be the positive Oy-axes,see the picture below.

    Each of the next N lines contains 3 integers xi, li, vi, the initial position(in meter), the length(in meter), the speed(in meter per second) of the i-th umbrella. If vi>0, the umbrella moves to the right side initially; if vi<0, the umbrella moves to the left side initially;if vi=0, the umbrella doesn't move at all.

    You can assume that the width of the umbrella and the crosswalk is 1 meter, the rain falls vertically, the speed of the rain will not change and the umbrellas and the crosswalk are absolutely horizontal.

    Output

    For each test case, you should output a single real number(rounded to 2 decimal places) - the answer.You can assume the total distance of all the umbrella's movement will not exceed 550*W.

    Example

    Input:
    1
    2 4 3 10
    0 1 1
    3 1 -1
    
    Output:
    65.00
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2004,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1470. Another Sequence Problem

    Problem code: SEQ2

    You are to write a program to perform some operations on a given sequence.These operations are listed below:

    ---------------------------------------------------------------------------------------------
    | Name        | Input format   |              function                                      |
    ---------------------------------------------------------------------------------------------
    | Modify      | MAKE-SAME i t c| Modify all the t numbers from the ith number(included) to  |
    |             |                | number c.                                                  |
    ---------------------------------------------------------------------------------------------
    | Insert      | INSERT i t s   | Insert t numbers after the ith number.s is a sequence of t |
    |             |                | numbers which should be inserted one-to-one.If i=0,you     |
    |             |                | should insert s in the first of the sequence.              |
    ---------------------------------------------------------------------------------------------
    | Delete      | DELETE i t     | Delete t numbers after the ith number(included).           |
    ---------------------------------------------------------------------------------------------
    | Reverse     | REVERSE i t    | Reverse t numbers after the ith number(included).          |
    ---------------------------------------------------------------------------------------------
    | Get sum     | GET-SUM i t    | Output the sum of t numbers after the ith number(included).|
    ---------------------------------------------------------------------------------------------
    | Get maximum | MAX-SUM        | Output the maximum partial sum in the sequence now.        |
    | partial sum |                |                                                            |
    ---------------------------------------------------------------------------------------------
    

    See the example.

    Input

    The very first line contains a single integer T(T<=4), the number of test cases.T blocks follow.

    For each test case:

    The first line contains two integers n and m(m<=20000), the number of numbers in the sequence in the beginning and the number of operations.

    The second line contains n integers seperated by spaces, the sequence in the beginning.

    Next m lines, each contains an operation listed above.

    You can assume that for each test case:

    • No invalid operation is in the input.
    • Number of numbers in the sequence is no more than 500000 and not less than 1 at any time.
    • All the numbers in the sequence is in range[-1000,1000] at any time.
    • The total number of numbers inserted will be not more than 4,000,000.The input is no more than 20MB.

    Output

    For each Get sum and Get maximum partial sum operation,you should write the answer to the output,one per line.

    Example

    Input:
    1
    9 8
    2 -6 3 5 1 -5 -3 6 3
    GET-SUM 5 4
    MAX-SUM
    INSERT 8 3 -5 7 2
    DELETE 12 1
    MAKE-SAME 3 3 2
    REVERSE 3 6
    GET-SUM 5 4
    MAX-SUM
    
    Output:
    -1
    10
    1
    10
    
    Hints:
    

    After the 3rd op., the sequence is

    2 -6 3 5 1 -5 -3 6 -5 7 2 3

    After the 4th op., the sequence is

    2 -6 3 5 1 -5 -3 6 -5 7 2

    After the 5th op., the sequence is

    2 -6 2 2 2 -5 -3 6 -5 7 2

    After the 6th op., the sequence is

    2 -6 6 -3 -5 2 2 2 -5 7 2
    Warning: enormous Input/Output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2005,Day 1; translated by lcosvse









    SPOJ Problem Set (classical)

    1471. A Game of Pearls

    Problem code: PRLGAME

    The game of pearls is to use the following 12 kinds of pearl designs each one and only one time to make the big pearl design.The pearl designs can be rotated and turned over arbitrarily. See the pictures below.

    
                       The empty grids
    
    
    
                      A sample big pearl design
    
    
    
    A sample big pearl design used characters instead of colors
    
    
    
              Part A
    
    
    
              Part B
    
    
    
              Part C
    
    
    
              Part D
    
    
    
              Part E
    
    
    
              Part F
    
    
    
              Part G
    
    
    
              Part H
    
    
    
              Part I
    
    
    
              Part J
    
    
    
              Part K
    
    
    
              Part L
    
    
    
    

    Input

    Ten test cases(given one after another,you have to process all!), Each contains a big design, 'A'-'L' denote the filled grids, '.' denotes the empty grids,see the example. You can assume that the pearl designs used are completely put into the empty grids.

    Output

    A big design which has no grids that haven't been filled and each pearl design is used one and only one time in it,or 'No solution'(without quotes) if there's no solution.If there are multiple solutions,output any.

    Example

    Input:
    .
    ..
    ...
    ....
    .....
    .....C
    ...CCC.
    EEEHH...
    E.HHH....
    E.........
    [and 9 test cases more]
    
    Output:
    B
    BK
    BKK
    BJKK
    JJJDD
    GJGDDC
    GGGCCCI
    EEEHHIIA
    ELHHHIAAF
    ELLLLIFFFF
    [and 9 test cases more]
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2005,Day 1; translated by Blue Mary









    SPOJ Problem Set (classical)

    1472. Tom and Jerry

    Problem code: TOMJERRY

    You may know the great American cartoon called Tom and Jerry. In that cartoon, Tom is a stupid cat, and Jerry is a cute mouse. They are all living in Blue Mary's house. (Maybe the name of the owner of the house they living in is not Blue Mary, but this is not important. ^_^)

    One day Jerry gets a GPS, so after that he can detect Tom's position accurately. He decides to play tricks on Tom again. The house has N (1<= N <= 1000) rooms numbered from 1 to n and E(1<= E <=1000) corridors, each connects two different rooms, and there is at most one corridor between two rooms. When Jerry gets the GPS, he is in room No.P(1<= P <=N) while Tom is in room No.Q(1<= Q <= N). You may assume that room No.P and room No.Q is in one connected componenet and they are not the same room. Since Jerry is very cute and Tom is very stupid, if they are in the same room, Jerry can befool Tom as soon as possible. Now Jerry wants to get to Tom's room as soon as possible. At each time unit, he will detect Tom's position, and choose the room next to his room which is the nearest to Tom's position and go to that room. If there are several rooms satisfied the condition above, he will choose the one with the least room number. After that, if they are in the same room, Jerry will stay and play tricks on Tom, or he will repeat this progress one more time otherwise.

    Now poor Tom doesn't know he'll be played, he is taking a walk in the house leisurely. Each time unit he will choose a room next to the room he is in and go to that room or stay in the room he is in now, with equal probability. For example, if Tom is now in room 1, room 2 and room 3 are the only neighbors of room 1 (i.e. there is a corridor between room 1 and room 2, and there is a corridor between room 1 and room 3), at the next time unit, the probability of that Tom is in room 1,2 or 3 are all 1/3.

    Suppose at each time unit, Jerry moves first, and Tom will move after Jerry complete his move. You task is to calculate the expected time unit from the time when Jerry gets the GPS to the time when Jerry and Tom are in the same room.

    Input

    Multiple test cases, the number of them is given in the very first line.

    For each test case:

    The first line contains two space-separated integers N and E. The second line contains two space-separated integers P and Q. E lines then follow, each contains 2 space-separated integers A and B which shows that there is a corridor between room A and room B.

    Output

    For each test case:

    Output one line, which contains a single real number - the expected time unit, rounded to 3 decimal places.

    Example

    Input:
    2
    4 3
    1 4
    1 2
    2 3
    3 4
    9 9
    9 3
    1 2
    2 3
    3 4
    4 5
    3 6
    4 6
    4 7
    7 8
    8 9
    
    Output:
    1.500
    2.167
    
    Hint
    The calculations for the first example can be found here.
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:6s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2005,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1473. Lemon Tree in the Moonlight

    Problem code: LEMON


    Blue Mary extremely like lemon trees. When the softness moon shines the ground, she lies under the lemon tree, thinking about the true meaning of life, the universe and everything quietly.

    Before long, she is shadowed by the lemon tree. Blue Mary is such a cute girl, that she soon comes up with a question: what is the area of the shadow?

    She knows it's hard for her to measure the shadow directly. So that, she tries to calculate it in geometrical way.

    As Mary knows well about this beautiful lemon tree, she regards it as N frustums of cones,each frustums of cone is defined as a floor, numbered 1..N from the bottom to top. Of course, the Nth(Top) is a cone. Each frustum has two circle surfaces. Each two adjacent frustums shares a same circle surface. All the centres of the circle surfaces are on a plumb line. Mary knows that the height of every frustums is h1,h2,..,hn, and the undersurface of the 1st frustum has a height h0 from the ground.

    Mary measures that the included angle of the moonshine and the ground is Alpha, which is an acute angle.

    For briefness, we suppose the moonshine is parallel and the ground is aclinic.

    And we ignore the bole of the tree. Mary comes up with the answer quickly, and she wants your ideas all the same.

    Input

    The very first line of the input data contains one integer T, the number of tests. T blocks follow.

    For each test:

    The first line of the input data contains one integer number N(N<=500) and a real number Alpha (Alpha>0.3).

    N denote the number of floors, Alpha denote the included angle of the moonshine and the ground(radian).

    The second line contains N + 1 real number h0 h1 h2... hn.(hi<=100) h0 denotes the height of the undersurface of the 1st frustum. h1 .. hn denote the height of each floor.

    The third line contains N real number r1 r2 .. rn(ri<=100), the radii of the undersurface in each floor.

    All the data in each line is seperated by spaces.

    Output

    For each data set you should output one line containing a single real number - the area of the shadow. Numbers should be rounded to two decimal places.

    Example

    Input:
    1
    2 0.7853981633
    10.0 10.00 10.00
    4.00 5.00
    
    Output:
    171.97
    
    Time limit has been changed from 30 seconds to 13 seconds, some naive solution gets TLE.
    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:13s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2005,Day 2; translated by g201513









    SPOJ Problem Set (classical)

    1475. VII - Act IV

    Problem code: WORMS


    Background

    This problem is completely unrelated to its problem code ^_^.

    Description

    A natural number x is called a good number if one or two of the next two conditions is satisfied:

    • 7 is a divisor of x.
    • 7 is a digit of x.

    Task

    Write a program that:

    • reads a number n from the standard input,
    • computes the number of good numbers in range[1,10n],
    • writes the result to the standard output.
    Solve the problem in at most 0.5kB of source code.

    Input

    The input begins with an integer t(t<= 210), the number of test cases.t test cases follow.

    For each test case, the first and only line contains an integer n (1<=n<=500).

    Output

    For each test case the output consists of one line that contains the answer.

    Example

    Sample input:
    3
    1
    2
    1
    
    Sample output:
    1
    30
    1
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:2s
    Source limit:512B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Folklore, description, standard program and test data by Blue Mary









    SPOJ Problem Set (classical)

    1476. Maximum Profit

    Problem code: PROFIT

    CS&T, the well-known cellphone company, is going to set some new service stations among n possible ones, which are numbered 1,2,...,n. The costs of setting these stations are known as P1,P2,..,Pn. Also the company has made a survey among the cellphone users, and now they know that there are m user groups numbered 1,2,...,m, which will communicate by service station Ai and Bi, and the company can profit Ci.

    Now CS&T wants to know which service stations are to be set that the company will profit most.

    Input

    T [The number of tests]
    n m [n<=5000 m<=50000]
    P1 P2 P3 ... Pn [Pi<=100]
    A1 B1 C1 
    A2 B2 C2
    ...
    Am Bm Cm [1<=Ai,Bi<=n, Ci<=100]
    [other tests]
    

    At least 80% of the tests satisfy that n<=200, m<=1000.

    Output

    MaximumProfit
    [other tests]
    

    Example

    Input:
    1
    5 5
    1 2 3 4 5
    1 2 3
    2 3 4
    1 3 3
    1 4 2
    4 5 3
    
    Output:
    4
    Hints:
    The service stations to be set are 1,2,3.
    

    Added by:[Trichromatic] XilinX
    Date:2007-04-01
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2006,Day 2; translated by Blue Mary









    SPOJ Problem Set (classical)

    1477. Play with a Tree

    Problem code: PT07A

    Hey, ACRush and Jelly are playing a game ! Let take a look at its rule:

    You are given a tree. Two players take turns cutting edges on a tree. Some nodes is on the "ground". When a player cuts an edge, all the edges that are no longer connected to the ground disappear. The player who can not take a move loses.

    ACRush plays first. Both of them are very good players. If you know state of the tree they are playing with, can you guess who will win?

    Node 4 is on the ground.

    Input

    Input consists of multiple test-cases. The first line contains one integer t - number of cases (0 < t <= 20). For each case, the input format is following. The first line contains one integer N (1 <= N <= 100000). The next line N integers s[i] (1 or 0). If s[i] is 1, the i-th node is on the ground. If s[i] is 0, the i-th node is not on the ground. Each line of the following N - 1 lines contains two integers u, v. They denote there is an edge between node u and node v (1 <= u,v <= N).
    There is no blank line after each case.

    Output

    For each case, output who will win the game. If ACRush wins, output 1; otherwise, output 0 (Jelly wins).
    There is no blank line after each case.

    Example

    Input:
    1
    4
    0 0 0 1
    1 2
    2 3
    2 4
    
    Output:
    1
    

    Added by:Thanh-Vy Hua
    Date:2007-04-07
    Time limit:0.5s-1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Co-author Amber









    SPOJ Problem Set (classical)

    1478. The Easiest Problem

    Problem code: PT07B

    You are given an unweighted, undirected tree T. We say T is special iff it has this property:

    "All nodes of degree greater than or equal to 3 are surrounded by at most two nodes of degree two or greater."

    Finding maximal size subtree of this tree so that it's a special tree.

    Input

    The first line of the input file contains one integer N --- number of nodes in the tree (0 < N <= 106). Next N-1 lines contain N-1 edges of that tree --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u, v <= N).

    Output

    At the first line, output number of nodes in the optimal subtree you found. Next lines, print all edges belong to that subtree, each line contains a pair u v means an edge between node u and node v.

    Example

    Input:
    5
    1 2
    2 3
    2 4
    2 5
    
    Output:
    5
    1 2
    2 3
    2 4
    2 5
    

    Added by:Thanh-Vy Hua
    Date:2007-04-07
    Time limit:0.100s-10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Co-author Amber









    SPOJ Problem Set (classical)

    1479. The GbAaY Kingdom

    Problem code: PT07C

    Jiajia is the king of the GbAaY Kingdom. He always squeezes his 20 ministers as coolies. There are n cities and m two-way roads connecting cities in the kingdom. Because of the increasing of the oil fee, he want to simplify the road system in the GbAaY Kingdom to save the traffic cost. Thus, some of roads will be removed. But he requests the ministers guarantee that there is always a path between any two cities. GbAaY Minister Loner suggests Jiajia for the convenience of the traffic management, the farthest distance between cities should be minimal. Unhesitatingly, Jiajia agrees this resolution. As the GbAaY Kingdom's minister (cooly), you must work hard for Jiajia to make the simplification plan.

    Input

    The first line contains two integers n, m (1 <= n <= 200, n - 1 <= m <= 20000). Each line of the following m lines contains three integers u, v, w (u != v, 0 <= w <= 105). They denote there is a road with length w between city u and city v.

    Output

    The first line contains one integer which is the farthest distance between cities after the simplification. Each line of the follow n - 1 contains two integers u, v (u < v). They denote there is an road between city u and city v in the simplification plan. If there are many optimal solutions, any of them will be accepted.

    Example

    Input:
    3 3
    1 2 1
    2 3 1
    1 3 1
    
    Output:
    2
    1 2
    1 3
    
    

    Added by:Thanh-Vy Hua
    Date:2007-04-07
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:Co-author Amber









    SPOJ Problem Set (main)

    1480. Let us count 1 2 3

    Problem code: PT07D

    Given two integer n, p. 4 kinds of query is needed to solve:

    1. Counting the number of labeled unrooted trees with n nodes
    2. Counting the number of labeled rooted trees with n nodes
    3. Counting the number of unlabeled rooted trees with n nodes
    4. Counting the number of unlabeled unrooted trees with n nodes
    Calculate the answer modulo p.

    Input

    Each line contains three integers k, n, p. k denotes which kind of query this case is.
    For Kind 1 or Kind 2 query, 1 <= n <= 109.
    For Kind 3 or Kind 4 query, 1 <= n <= 103 and n <= p.
    For all queries, 2 <= p <= 104 and p is a prime.

    Output

    For each query, output a line which contains only one integer.

    Example

    Input:
    1 2 2
    2 2 3
    3 2 5
    4 2 3
    
    Output:
    1
    2
    1
    1
    

    Added by:Thanh-Vy Hua
    Date:2007-04-07
    Time limit:0.300s-4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:Co-author Amber









    SPOJ Problem Set (main)

    1482. A short vacation in Disneyland

    Problem code: PT07F

    After a lot of exams at school, Amber and his friends Ahyangyi, Dragon have a short vacation in Hong Kong Disneyland. Many interesting places they want to visit there: resort, castle,... . In each place and between them, there are special bidirectional rails, so that the visitors can drive a small special car, go around and have a sightseeing tour. This rail system is quite optimal it has tree shape ! Each time, you start a new route (or you can call it "path") with a car, you must purchase a new ticket.

    Amber and his friends surely want to visit all places, and each place exactly once, so bored to visit one place many times. But the trouble is they don't carry much money. So Amber thinks about a good way to purchase as small number of tickets as possible (i.e. minimal number of routes). We don't care how they can switch cars during their trip.

    Now you're given maps of the Disneyland, please help them to find an optimal solution.

    Take a look at the figure below:

    There are many optimal solutions here and Amber must purchase at least 3 tickets, for 3 disjoint routes. Two possible solutions are:
    Solution 1:
    1-st route: they visit 1 2 3
    2-nd route: they visit 4
    3-rd route: they visit 5 6 7
    Solution 2:
    1-st route: they visit 1 2 4 6 5
    2-nd route: they visit 3
    3-rd route: they visit 7

    Input

    There may be many maps in one input file. The first line of file is number of maps T (0 < T <= 10). The following line is blank. Then, there are the descriptions of T maps.

    For each map, the first line contains one integer N --- number of places in the Disneyland (0 < N <= 10000). We number places from 1 to N. Next N-1 lines contain N-1 rails between places --- Each line contains a pair (u, v) means there is a rail between place u and place v (1 <= u,v <= N).
    There is a blank line after each description.

    Output

    For each map, the first line, write minimal number of routes K. Next K lines, show out the routes in your solution, each has form u[1] u[2]...u[m], means the route starts at place u[1] then visits place u[2],..., ends at place u[m]. So between 2 consecutive places in each route must have a rail. If there are many solutions, any of them will be accepted.
    There is no blank line after each case.

    Example

    Input:
    1
    
    7
    1 2
    2 3
    2 4
    4 6
    5 6
    6 7
    
    Output:
    3
    1 2 3
    4
    5 6 7
    

    Added by:Thanh-Vy Hua
    Date:2007-04-07
    Time limit:0.100s-0.5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:Co-author Amber









    SPOJ Problem Set (main)

    1483. Colorful Lights Party

    Problem code: PT07G

    ACRush and his friends want to open a party to celebrate the good result of THU in ICPC 2007. They will use all halls in THU for their party. There are 2 kinds of hall: the small and the large one. In each hall, there is an electronic light system, which forms a tree topology to reduce redundant wires.

    • In a small hall, the light system is a general tree with n lights. The lights are numbered from 1 to n
    • In a large hall, the light system is obtained from k chains of lights, each chain has length t. The first lights of these k chains are connected with a big light at the central stage of the hall. The big light has id 1, the first light of each chain has id from 2 to k+1, then we continue with the second light of each chain, so on...

    Take a look at the figure below:

    ACRush hopes in every hall, each light has an unique color and so do the wires!

    For easier to remember and to hang up lights against the walls, he sets a rule:

    • For each hall, we number the color from 0 to n-1, so each light will get a color id in set {0, 1, ..., n-1}.
    • Color id of the wire connects i-th light and j-th light uniquely identified by the positive difference between color ids of i-th light and j-th light.

    At first view, the rule seems easy, so everyone agrees with him. But it's really tough if the room is quite large, too hard to set colors for lights. After few seconds, ACRush says "So in this hall, the 1-st light should have color 3, the 2-nd one should have color 0,...". Well, how can he do it very fast?

    How about you ? Let write a program to help ACRush's friends setting colors for lights in all T halls.

    Input

    The first line of file is T -- number of halls in THU (0 < T <= 10). The following line is blank. Then, there are the descriptions of T halls.

    For each hall, the first line contains one integer kind. kind denotes which kind of the current hall: 1 is a small hall, 2 is a large one. On next line, there are two cases:

    • For Kind 1, first line is n (1 <= n <= 27) -- number of lights. Next n - 1 lines describe wires in this hall. Each line is pair (u, v) -- there is a wire between light u and v (1 <= u, v <= n).
    • For Kind 2, only one line contains two numbers k and t (1 <= k, t <= 1000).

    There is a blank line after each description.

    Output

    For each hall, show us n numbers on one line, i-th number is the color id of i-th light. If there are many solutions any of them will be accepted. Otherwise, if there is no solution, all color id should be -1.
    The color ids on one line are separated by exactly one blank, and you'd better not print any redundant blanks. There is no blank line after each case.

    Example

    Input:
    2
    
    1
    3
    1 2
    2 3
    
    2
    2 1
    
    Output:
    0 2 1
    0 4 2 1 3
    

    Added by:Thanh-Vy Hua
    Date:2007-04-07
    Time limit:0.100s-2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:Co-author Amber









    SPOJ Problem Set (main)

    1484. Search in XML

    Problem code: PT07H


    The XML (eXtensible Markup Language) is gaining popularity as a new standard for data representation and exchange on the internet. XML provides a text-based means to describe and apply a tree-based structure to information. The XML document consists of nested elements, some of which usually have attributes and content. But for simplifying this problem, we needn't consider the attributes and content, i.e. only tags allowed. An element typically consists of two tags, a start tag and an end tag. The start tag consists of a name surrounded by angle brackets, like "<tag>"; the end tag consists of the same name surrounded by angle brackets, but with a slash preceding the name, like "</tag>". The element's content is empty or other sub-element (child) that appears between the start tag and the end tag. Specially, no XML element that has the same tag in its direct sub-elements (children), i.e. All sibling elements have different tag names. The following is an valid example for XML documents.

    <THU>
    <Team>
    <ACRush></ACRush>
    <Jelly></Jelly>
    <Cooly></Cooly>
    </Team>
    <JiaJia>
    <Team>
    <Ahyangyi></Ahyangyi>
    <Dragon></Dragon>
    <Cooly><Amber></Amber></Cooly>
    </Team>
    </JiaJia>
    </THU>

    For identifying the elements in a document, we number the elements in according to the order that the start tags of the elements appear in the document. For instances, "THU" is numbered 1. The first "Team" is numbered 2. "ACRush" is numbered 3. "Ahyangyi" is numbered 8.

    The problem of querying XML documents has been given much attention by researchers. Now we are given a querying pattern of XML documents and a text of XML documents. The following is an valid example for pattern.

    <Team><Cooly></Cooly></Team>

    And we are requested to find all occurrences of the pattern in the text of XML documents. Here, the pattern occurs at a particular text position if placing the pattern with root element at that text position leads to a situation in which each pattern element overlaps some text element with the same label. Because the sibling elements have different labels, there is only one way to put the pattern into the text.

    Input

    There are two parts in the input file. The first part is a valid XML documents with exactly one root element. The second part is a valid XML documents as querying pattern with exactly one root element. Please ignore all whitespaces (unvisiable characters) in the input file, i.e. only consider the uppercase and lowercase letter and "/", "<", ">". Assume XML documents is always strictly a rooted tree. The input file is less than 100kb.

    Output

    Output all the occurrences of pattern in a text of XML documents. The first line consists of an integer n that denotes the number of the occurrences. Then the next n line, each line consists of an id number of an element that occurs the query pattern. Please print them in increasing order.

    Example

    Input:
    <THU>
    <Team>
    <ACRush></ACRush>
    <Jelly></Jelly>
    <Cooly></Cooly>
    </Team>
    <JiaJia>
    <Team>
    <Ahyangyi></Ahyangyi>
    <Dragon></Dragon>
    <Cooly><Amber></Amber></Cooly>
    </Team>
    </JiaJia>
    </THU> <Team><Cooly></Cooly></Team> Output: 2 2 7

    Added by:Thanh-Vy Hua
    Date:2007-04-07
    Time limit:0.100s-3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:Co-author Amber









    SPOJ Problem Set (main)

    1487. Query on a tree III

    Problem code: PT07J


    You are given a node-labeled rooted tree with n nodes.

    Define the query (x, k): Find the node whose label is k-th largest in the subtree of the node x. Assume no two nodes have the same labels.

    Input

    The first line contains one integer n (1 <= n <= 105). The next line contains n integers li (0 <= li <= 109) which denotes the label of the i-th node.

    Each line of the following n - 1 lines contains two integers u, v. They denote there is an edge between node u and node v. Node 1 is the root of the tree.

    The next line contains one integer m (1 <= m <= 104) which denotes the number of the queries. Each line of the next m contains two integers x, k. (k <= the total node number in the subtree of x)

    Output

    For each query (x, k), output the index of the node whose label is the k-th largest in the subtree of the node x.

    Example

    Input:
    5
    1 3 5 2 7
    1 2
    2 3
    1 4
    3 5
    4
    2 3
    4 1
    3 2
    3 2
    
    Output:
    5
    4
    5
    5
    

    Added by:Thanh-Vy Hua
    Date:2007-04-07
    Time limit:1s-1.100s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:Co-author Amber









    SPOJ Problem Set ()

    1505. Whac-a-Mole

    Problem code: MOLE

    Map While visiting a traveling fun fair you suddenly have an urge to break the high score in the Whac-a-Mole game. The goal of the Whac-a-Mole game is to... well... whack moles. With a hammer. To make the job easier you have first consulted the fortune teller and now you know the exact appearance patterns of the moles. The moles appear out of holes occupying the n2 integer points (x, y) satisfying 0 ≤ x, y <n in a two-dimensional coordinate system. At each time step, some moles will appear and then disappear again before the next time step. After the moles appear but before they disappear, you are able to move your hammer in a straight line to any position (x2 , y2 ) that is at ditance at most d from your current position (x1 , y1 ). For simplicity, we assume that yo can only move your hammer to a point having integer coordinates. A mole is whacke if the center of the hole it appears out of is located on the line between (x1 , y1 ) an (x2 , y2 ) (including the two endpoints). Every mole whacked earns you a point. Whe the game starts, before the first time step, you are able to place your hammer anywher you see fit.

    Input

    The input consists of several test cases. Each test case starts with a line containing three integers n, d and m, where n and d are as described above, and m is the total number of moles that will appear (1 ≤ n ≤ 20, 1 ≤ d ≤ 5, and 1 ≤ m ≤ 1000). Then follow m lines, each containing three integers x, y and t giving the position and time of the appearance of a mole (0 ≤ x, y < n and 1 ≤ t ≤ 10). No two moles will appear at the same place at the same time. The input is ended with a test case where n = d = m = 0. This case should not be processed.

    Output

    For each test case output a single line containing a single integer, the maximum possible score achievable.

    Example

    Input:
    4 2 6
    0 0 1
    3 1 3
    0 1 2
    0 2 2
    1 0 2
    2 0 2
    5 4 3
    0 0 1
    1 2 1
    2 4 1
    0 0 0
    
    
    Output:
    4
    2
    
    

    Added by:Abhilash I
    Date:2007-04-19
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6









    SPOJ Problem Set (classical)

    1526. Ranklist Sorting

    Problem code: RSORTING


    You are given the scores of several players in a competition. Your task is to create a ranklist of the players, sorted in decreasing order by score.

    Unfortunately, the data structure used for the list of players supports only one operation, which moves a player from position i to position j without changing the relative order of other players. If i > j, the positions of players at positions between j and i − 1 increase by 1, otherwise if i < j the positions of players at positions between i + 1 and j decrease by 1.

    This operation takes i steps to locate the player to be moved, and j steps to locate the position where he or she is moved to, so the overall cost of moving a player from position i to position j is i + j. Here, positions are numbered starting with 1.

    Determine a sequence of moves to create the ranklist such that the sum of the costs of the moves is minimized.

    Input

    The input consists of exactly 10 test cases. The first line of each test case contains n (2 ≤ n ≤ 1000), the number of players. Each of the following n lines contains one non-negative integer si (0 ≤ si ≤ 1000000), the scores of the players in the current order. You may assume that all scores are distinct.

    Output

    For each test case, print in one line the number of moves used to create the ranklist. The following lines should specify the moves in the order in which they are applied. Each move should be described by a line containing two integers i and j, which means that the player at position i is moved to position j. The numbers i and j must be separated by a single space.

    Example

    here only one test case
    Input:
    5
    20
    30
    5
    15
    10
    
    Output:
    2
    2 1
    3 5
    

    Added by:Adrian Kuegel
    Date:2007-05-04
    Time limit:4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:own problem, used in BOI 2007









    SPOJ Problem Set (classical)

    1536. Help Blue Mary Please! (Act III)

    Problem code: BLUEEQ3


    Background

    This morning Blue Mary wrote some equations on a piece of paper and left it on her desk.After solving some problems in SPOJ,she found that her classmate H.L. replaced all characters on the paper with some other ones.H.L. told her he replaced the same characters with the same ones,and different characters with different ones because of his goodness.Now Mary needs your help to get the original equations back.(See problem BLUEEQ)

    Input

    Ten test cases(given one after another,you have to process all!)For each test case, the first line is a single integer n(n<=21).Next 3 lines contains 3 strings, each of them has a length of n and contains only first n capital latin characters.The sum of the numbers the first two strings indicates equals to the number the third string incicates.The numbers can have leading zeros and each of their bases is n.

    Output

    For each test case you should output one line contains n numbers separated by spaces, which is a permutation of integer numbers 0 to n-1.Number x is on the k-th position iff x is replaced by the kth capital latin character.There is one and only one solution for each test case.

    Example

    Input:
    5
    ABCED
    BDACE
    EBBAA
    [and 9 test cases more]
    Output:
    1 0 3 4 2
    [and 9 test cases more]
    

    Added by:[Trichromatic] XilinX
    Date:2007-05-08
    Time limit:17s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:description by Blue Mary









    SPOJ Problem Set (classical)

    1538. Making Jumps

    Problem code: MKJUMPS

    A knight is a piece used in the game of chess. The chessboard itself is square array of cells. Each time a knight moves, its resulting position is two rows and one column, or two columns and one row away from its starting position. Thus a knight starting on row r, column c – which we’ll denote as (r,c) – can move to any of the squares (r-2,c-1), (r-2,c+1), (r-1,c-2), (r-1,c+2), (r+1,c-2), (r+1,c+2), (r+2,c-1), or (r+2,c+1). Of course, the knight may not move to any square that is not on the board.


    Suppose the chessboard is not square, but instead has rows with variable numbers of columns, and with each row offset zero or more columns to the right of the row above it. The figure to the left illustrates one possible configuration. How many of the squares in such a modified chessboard can a knight, starting in the upper left square (marked with an asterisk), not reach in any number of moves without resting in any square more than once?


    subir imagenes



    If necessary, the knight is permitted to pass over regions that are outside the borders of the modified chessboard, but as usual, it can only move to squares that are within the borders of the board.

    Input

    There will be multiple cases to consider. The input for each case begins with an integer n, between 1 and 10, that specifies the number of rows in the modified chessboard. Following n there will be n pairs of integers, with the ith pair corresponding to the ith row of the chessboard. The first integer of each pair indicates the number of squares skipped at the beginning of the row. The second integer indicates the number of squares in the row (which will always be at least 1).The last case will be followed by the integer 0.


    For example, input for the case illustrated by the chessboard shown above would be:


    7 0 3 0 3 0 4 0 4 1 3 1 7 4 4


    The maximum dimensions of the board will be 10 rows and 10 columns. That is, any modified chessboard specified by the input will fit completely on a 10 row, 10 column board.

    Output

    For each input case, display the case number (1, 2, …), and the number of squares that the knight can not reach. Display the results in the format shown in the examples below.

    Example


    Input:
    7 0 3 0 3 0 4 0 4 1 3 1 7 4 4
    3 0 3 0 3 0 3
    2 0 1 2 1
    0
    
    Output:
    Case 1, 4 squares can not be reached.
    Case 2, 1 square can not be reached.
    Case 3, 0 squares can not be reached.
    

    Added by:Camilo Andrés Varela León
    Date:2007-05-11
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:North Central North America Regional Programming Contest - 2003









    SPOJ Problem Set (classical)

    1552. Mobiles

    Problem code: MOBILE2


    You have been asked to buy a gift for your baby brother, Ike. However, you have noticed that Ike has a very particular taste in gifts. He only likes gifts that are configured in his particular style.

    You have found a shop that sells mobiles. A mobile is a multi-layered decoration that is typically hung from the roof. Each mobile consists of a series of horizontal rods connected by vertical wires. Each rod has a wire hanging from both ends, which holds either another horizontal rod or a toy.

    A sample mobile is shown below:

    To satisfy your brother, you need to find a mobile that can be reconfigured so that:

    (i) any two toys are either at the same level (that is, joined to the roof by the same number of rods), or di.er by only one level;

    (ii) for any two toys that differ by one level, the toy to the left is further down than the toy to the right.

    Mobiles can be reconfigured by performing swaps. A swap involves taking some rod, unhooking whatever is hanging beneath the left and right ends, and reattaching them at opposite ends (that is, the right and left ends respectively). This process does not modify the ordering of any rods or toys further down.

    Since you are training for the Informatics Olympiad, you decide to write a program to test whether a given mobile can be reconfigured into a gift that Ike will like!

    As an example, consider the mobile illustrated earlier. Ike will not like this mobile. Although it satisfies condition (i), it breaks condition (ii) — the toy at the leftmost end is at a higher level than the toys to its right.

    However, the mobile can be reconfigured into a mobile that Ike will like. The following swaps are required:

    1. First, the left and right ends of rod 1 are swapped. This exchanges the positions of rods 2 and 3, resulting in the following configuration:

    2. Second, and finally, the left and right ends of rod 2 are swapped. This moves rod 4 to the left end of rod 2, and the toy to the right end of rod 2.

    It can be seen that this final mobile satisfies Ike's requirements. All toys are at most one level apart, and the toys at a lower level are further to the left than the toys at a higher level.

    Your task is, given a description of a mobile, to determine the smallest number of swaps required to reconfigure it so that Ike will like it (if this is possible). You may assume that the toys can never get in each other's way.

    Input

    Multiple test cases, the number of them will be given at the very first line.

    For each test case:

    The first line of input will contain the single integer n (1 <= n <= 100 000) representing the number of rods in the mobile. The rods are numbered 1, 2 , ..., n.

    The following n lines will describe the connections for each rod. Specifically, the ith of these lines will describe rod i. Each of these lines will contain two integers l r separated by a single space, indicating what is hung beneath the left and right ends of the rod respectively. If a toy is hung beneath this rod, the corresponding integer l or r will be -1. Otherwise the integer l or r will be the number of a rod that is hung beneath this rod.

    If there are any rods hanging beneath rod i, these rods will have numbers strictly greater than i. Rod 1 is the single rod at the top of the mobile.

    Output

    Output should consist of a single line containing a single integer, giving the smallest number of swaps required to reconfigure the mobile according to Ike's constraints. If this is not possible, you should output the integer -1.

    Example

    Input:
    1
    6
    2 3 
    -1 4 
    5 6 
    -1 -1 
    -1 -1 
    -1 -1 
    
    Output:
    2
    
    Warning: large input/output data,be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-05-14
    Time limit:17s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Asia-Pacific Informatics Olympiad(APIO) 2007









    SPOJ Problem Set (classical)

    1553. Backup Files

    Problem code: BACKUP

    You run an IT company that backs up computer data for large offices. Backing up data is not fun, and so you design your system so that the different offices can back up each others' data while you sit at home and play computer games instead.

    The offices are all situated along a single street. You decide to pair up the offices, and for each pair of offices you run a network cable between the two buildings so that they can back up each others' data.

    However, network cables are expensive. Your local telecommunications company will only give you k network cables, which means you can only arrange backups for k pairs of offices (2k offices in total). No office may belong to more than one pair (that is, these 2k offices must all be different). Furthermore, the telecommunications company charges by the kilometre. This means that you need to choose these k pairs of offices so that you use as little cable as possible. In other words, you need to choose the pairs so that, when the distances between the two offices in each pair are added together, the total distance is as small as possible.

    As an example, suppose you had five clients with offices on a street as illustrated below. These offices are situated 1 km, 3 km, 4 km, 6km and 12km from the beginning of the street. The telecommunications company will only provide you with k = 2 cables.

    The best pairing in this example is created by linking the first and second offices together, and linking the third and fourth offices together. This uses k = 2 cables as required, where the first cable has length 3km - 1km = 2 km, and the second cable has length 6km - 4km = 2 km. This pairing requires a total of 4km of network cables, which is the smallest total possible.

    Input

    Multiple test cases, the number of them will be given at the very first line.

    For each test case:

    The first line of input will contain the integers n and k, representing the number of offices on the street (2 <= n <= 100 000) and the number of available network cables (1 <= k <= n/2).

    The following n lines will each contain a single integer (0 <= s <= 1 000 000 000), representing the distance of each office from the beginning of the street. These integers will appear in sorted order from smallest to largest. No two offices will share the same location.

    Output

    Output should consist of a single positive integer, giving the smallest total length of network cable required to join 2k distinct offices into k pairs.

    Example

    Input:
    1
    5 2
    1
    3
    4
    6
    12
    
    Output:
    4
    
    Explanation
    

    The sample input above represents the example scenario described earlier.

    Warning: large input/output data,be careful with certain languages

    Blue Mary's Note: test data has been modified on Dec. 5, 2007. All the solutions have been rejudged.


    Added by:[Trichromatic] XilinX
    Date:2007-05-14
    Time limit:17s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Asia-Pacific Informatics Olympiad(APIO) 2007









    SPOJ Problem Set (classical)

    1554. Zoo

    Problem code: ZOO


    The pride of the Asia-Pacific region is the newly constructed Great Circular Zoo. Situated on a small Pacific island, it consists of a large circle of different enclosures, each containing its own exotic animal as illustrated below.

    You are in charge of public relations for the zoo, which means it is your job to keep people as happy as possible. A busload of schoolchildren has just arrived, and you are eager to please them. However, this is no easy task|there are animals that some children love, and there are animals that some children fear. For example, little Alex loves monkeys and koalas because they are cute, but fears lions because of their sharp teeth. On the other hand, Polly loves lions because of their beautiful manes, but fears koalas because they are extremely smelly.

    You have the option of removing some animals from their enclosures, so that children are not afraid. However, you are worried that if you remove too many animals then this will leave the children with nothing to look at. Your task is to decide which animals to remove so that as many children can be made happy as possible.

    Each child is standing outside the circle, where they can see five consecutive enclosures. You have obtained a list of which animals each child fears, and which animals each child loves. A child will be made happy if either at least one animal they fear is removed from their field of vision, or at least one animal they love is not removed from their field of vision.

    For example, consider the list of children and animals illustrated below:

    -----------------------------------------------------------------------
    |Child      |Enclosures Visible |Fears                |Loves          |
    |Alex       |2, 3, 4, 5, 6      |Enclosure 4          |Enclosures 2, 6|
    |Polly      |3, 4, 5, 6, 7      |Enclosure 6          |Enclosure 4    |
    |Chaitanya  |6, 7, 8, 9, 10     |Enclosure 9          |Enclosures 6, 8|
    |Hwan       |8, 9, 10, 11, 12   |Enclosure 9          |Enclosure 12   |
    |Ka-Shu     |12, 13, 14, 1, 2   |Enclosures 12, 13, 2 |-              |
    -----------------------------------------------------------------------
    

    Suppose you remove the animals from enclosures 4 and 12. This will make Alex and Ka-Shu happy, because at least one animal that they fear has gone. This will also keep Chaitanya happy, since both enclosures 6 and 8 still contain animals that he loves. However, both Polly and Hwan will be unhappy, since they cannot see any animals that they love but they can still see all the animals that they fear. This arrangement therefore gives a total of three happy children.

    Now suppose you put these animals back into their enclosures, and remove the animals from enclosures 4 and 6 instead. Alex and Polly will be happy because the animals that they fear in enclosures 4 and 6 have gone. Chaitanya will be happy because, even though animal 6 has gone, he can still see the animal in enclosure 8 which he loves. Likewise, Hwan will be happy because she can now see the animal in enclosure 12, which she loves. The only person unhappy will be Ka-Shu.

    Finally, suppose you put the animals back once more and then remove only the animal from enclosure 13. Ka-Shu will now be happy since one animal that he fears has been removed, and Alex, Polly, Chaitanya and Hwan will all be happy since they can all see at least one animal that they love. Thus this arrangement gives five happy children, the largest number possible.

    Input

    Multiple test cases, the number of them will be given at the very first line.

    For each test case:

    The first line will be of the form N C, where N is the number of animal enclosures (10 <= N <= 10 000) and C is the number of children (1 <= C <= 50 000). The enclosures are numbered 1, 2, ...,N clockwise around the circle.

    Following this will be C additional lines of input, where each line describes a single child. Each of these lines will be of the form:

    E F L X1 X2 ... XF Y1 Y2 ... YL;

    where:

    • E is the first enclosure that the child can see (1 <= E <= N). In other words, the child can see enclosures E, E + 1, E + 2, E + 3 and E + 4. Note that numbers larger than N wrap back around the circle, so if N = 14 and E = 13 then the child can see enclosures 13, 14, 1, 2 and 3.
    • F is the number of animals that the child fears, and L is the number of animals that the child loves.
    • Enclosures X1,...,XF contain the animals that the child fears (1<=X1,...,XF<=N).
    • Enclosures Y1,...,YL contain the animals that the child loves (1<=Y1,...,YL<=N).
    • No two of the integers X1,...,XF,Y1,...,YL are equal, and all of these integers describe enclosures that the child can see.

    Children will be listed in sorted order according to the first enclosure E (so the child with lowest E will appear first and the child with largest E will appear last). Note that more than one child may have the same first enclosure E.

    Output

    Output must consist of a single integer, giving the largest number of children that can be made happy.

    Example

    Sample Input:
    2
    14 5
    2 1 2 4 2 6
    3 1 1 6 4
    6 1 2 9 6 8
    8 1 1 9 12
    12 3 0 12 13 2
    12 7
    1 1 1 1 5
    5 1 1 5 7
    5 0 3 5 7 9
    7 1 1 7 9
    9 1 1 9 11
    9 3 0 9 11 1
    11 1 1 11 1
    Sample Output:
    5
    6
    
    Explanation:
    

    The first sample case is the example discussed earlier, in which all C = 5 children can be made happy. The second sample case is an example in which it is impossible to make all C = 7 children happy.

    Warning: large input/output data,be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-05-14
    Time limit:17s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Asia-Pacific Informatics Olympiad(APIO) 2007









    SPOJ Problem Set (classical)

    1557. Can you answer these queries II

    Problem code: GSS2


    Being a completist and a simplist, kid Yang Zhe cannot solve but get Wrong Answer from most of the OI problems. And he refuse to write two program of same kind at all. So he always failes in contests.

    When having a contest, Yang Zhe looks at the score of every problems first. For the problems of the same score, Yang Zhe will do only one of them. If he's lucky enough, he can get all the scores wanted.

    Amber is going to hold a contest in SPOJ. She has made a list of N candidate problems, which fit Yang Zhe very well. So Yang Zhe can solve any problem he want. Amber lined up the problems, began to select. She will select a subsequence of the list as the final problems. Being A girl of great compassion, she'd like to select such a subsequence (can be empty) that Yang Zhe will get the maximal score over all the possible subsequences.

    Amber found the subsequence easily after a few minutes. To make things harder, Amber decided that, Yang Zhe can take this contest only if Yang Zhe can answer her Q questions. The question is: if the final problems are limited to be a subsequence of list[X..Y] (1 <= X <= Y <= N), what's the maximal possible score Yang Zhe can get?

    As we know, Yang Zhe is a bit idiot (so why did he solve the problem with a negative score?), he got Wrong Answer again... Tell him the correct answer!

    Input

    • Line 1: integer N (1 <= N <= 100000);
    • Line 2: N integers denoting the score of each problem, each of them is a integer in range [-100000, 100000];
    • Line 3: integer Q (1 <= Q <= 100000);
    • Line 3+i (1 <= i <= Q): two integers X and Y denoting the ith question.

    Output

    • Line i: a single integer, the answer to the ith question.

    Example

    Input:
    9
    4 -2 -2 3 -1 -4 2 2 -6
    3
    1 2
    1 5
    4 9
    
    Output:
    4
    5
    3
    
    
    Warning: large input/output data,be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-05-16
    Time limit:1s-5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Description, standard program and test data by Yang Zhe









    SPOJ Problem Set (classical)

    1644. Trees

    Problem code: TREEOI14

    Byteasar has a cottage. Lately, he has bought n trees and had them planted all in one row. Byteasar does not, however, like the order which the trees have been planted in. It particularly annoys him that tall and short ones have been mixed up, and the composition does not meet his aesthetic criteria.

    Byteasar has invented a disorder coefficient so as to allow the gardener to comprehend his intentions: the lower the value of the coefficient the prettier the row of trees. It is defined in the following way: |h1−h2|+ |h2−h3|+...+|hn−1−hn|, where h1,h2, . . . ,hn are the heights of consecutive trees in a row.

    Replanting is a very toilsome and cumbersome task, therefore Byteasar has ordered the gardener to replant two trees at the most (i.e. interchange their positions). The task of the gardener is to choose the pair to replant in a way that makes the disorder coefficient the smallest.

    The gardener is not sure if he has chosen the correct pair of trees and he fears he may lose his job if he is mistaken. Help him: for each tree calculate the minimal disorder coefficient that may be attained by switching places with any other tree.

    Task

    Write a program which:

    • reads the height of the consecutive trees in a row from the standard input,
    • for each tree calculates the minimal disorder coefficient that may be attained should it switch places with some other tree (or should there be no change at all),
    • writes the outcome to the standard output.

    Input

    The first line of the standard input contains one integer n (2 <= n <= 50000). The other contains n integers hi (1 <= hi <= 100000000) separated by single spaces, denoting the height of the consecutive trees in the row.

    Output

    The output should consist of precisely n lines. The i-th line should contain a single integer - the smallest disorder coefficient attainable when considering replanting of the i-th tree.

    Example

    Input:
    5
    7 4 5 2 5
    
    Output:
    7
    7
    8
    7
    7
    
    * Added some unofficial tests
    Added by:Thanh-Vy Hua
    Date:2007-06-09
    Time limit:1s-6s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Polish Olympiad 14









    SPOJ Problem Set ()

    1671. Another Mathematical Problem

    Problem code: AMATH

    Given two numbers n (1<=n<10100) and k (1<=k<=100), you are to determine whether there exists a positive integer T which satisfies that for every positive integer a, na+T-na is divisible by 10k.

    Input

    Multiple test cases. Each test case contains two space-separated integers n and k. Input terminate by EOF.

    The number of test cases will not more than 20.

    Output

    For each test case, you should output the smallest positive integer number T which satisfies the condition above, or -1 if it doesn't exist.

    Example

    Input:
    32 2
    
    Output:
    4
    

    Added by:[Trichromatic] XilinX
    Date:2007-07-01
    Time limit:3s
    Source limit:2048B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:Folklore, description and standard program by Blue Mary









    SPOJ Problem Set (classical)

    1672. The Great Indian Wedding

    Problem code: GIWED

    A wedding is to be organized in a rectangular park of dimensions M by N. Some parts of the park are covered by K rectangular carpets. These carpets, produced by ItSucks Corporation are revolutionary self cleaning carpets - they suck any liquid they come in contact with! The organizer wants to water the park to keep the grass fresh. If there were no carpets, the organizer could have used a single pipe to water the whole park but unforunately, the water doesn't seep through the carpets. The organizer has at his diposal L pipes. The pipes would be placed at fixed locations chosen by the organizer and can't be moved. Water spreads from a pipe in all directions unless obstructed by the park boundary or a carpet. What is the maximum area that can be watered using these L pipes?

    Input

    The first line of the input contains a single integer T, the number of test cases (1<=T<=30) . Each test case starts with a single line containg the values M,N,K and L ( 1<=M<=10000, 1<=N<=10000, 0<=K<=50, 1<=L<=10). It is followed by K lines, each line containing 4 integers separated by single spaces, x1,y1,x2,y2 where (x1,y1) and (x2,y2) are the zero based coordinates of lower left and upper right vertex of the carpet. Assume that x1<x2 and y1<y2. The carpets may cover each other. Water would not be able to seep through even if two carpets touch in a corner.

    Output

    For each test case, print the maximum area that can be watered on a single line

    Example

    Input:
    2
    10 10 0 1
    10 10 1 1
    3 3 4 4
    
    Output:
    100
    99
    
    

    Added by:Rahul Garg
    Date:2007-07-04
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:C-maphore, Tryst 2007









    SPOJ Problem Set (classical)

    1673. Ambitious Manager

    Problem code: AMBM

    The Bogus Corporation distributes salary to its employees in a weird manner. The salary is distributed every K days,  and instead of same salary for each day, the salary for the ith day is ai. An ambitious young manager, fresh from Institute of Mismanagement, observes that people usually prefer to take leave towards the end of this period of K days, when the workload is higher. Instead of revising each of the ai's, the manager comes up with a quick fix solution - he redefines the new salary on the ith day as bi=ai+2ai-1+22ai-2+23ai-3+........+2i-1a1 . Baba, one of the employees, is in a dire financial crisis, and must accumulate at least N rupees at the end of the forthcoming period. Being a lazy worker that he is, he is interested in finding out if attending particular days would guarantee him exactly  N rupees at the end of the period. Can you help Baba?

    Input

    First line contains a single integer integer T, the number of test cases ( 1<=T<=100). Each test case is described on two lines. First line contains two integers, N and K ( 1<=N<=263-1, 1<=K<=50) , the second line contains a space separated list of K integers, the ai's ( 1<=ai<=1000).

    Output

    For each test case, output on a single line 1-based indices of the days (separated by a single space) he should attend to ensure a salary of exactly N rupees at the end of the period. The indices should be printed in the sorted order. In case of multiple answers, output any one of them. If there is no answer, print -1.

    Example

    Input:
    2
    9 3
    1 1 2
    10 2
    2 3
    Output:
    1 3
    -1
    

    Added by:Rahul Garg
    Date:2007-07-04
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:C-maphore, Tryst 2007









    SPOJ Problem Set (classical)

    1674. The Explosion

    Problem code: EXPLOSN

    The day of 6.XII.2003 in Megabyteland began calm and quietly as any other day. Some people went to work, some - to school, some - to store to buy food. Drivers were traditionally stucked in traffic jams, drinking coffee and reading morning newspaper. Suddenly the regularity of this day was disturbed by huge explosion."They blew up the embassy of Bajtocja!!!" - somebody cried. Everybody began to run away in panic.

    Police works pretty good in Megabyteland and first radiocars appeared near the embassy only few seconds after the explosion. All the people near the embassy were detained. Some of these people are the organizers of the explosion, but the others could by just occasional witnesses. During the testification each person named exactly one perpetrator. It is known, that if a man is not a perpetrator, than he always says the truth (he haven't a reason to lie, have he?). However, perpetrators want to make the work of the police more difficult, so a perpetrator can name any person during the testification (even himself).

    The policemen are in the very hard situation. They should arrest some group of potential perpetrators, but it is difficult to determine who is guilty and who is not from the data they have. There exists many groups of potential perpetrators, that don't contradict to any of the testimonies. The policemen want to arrest as small innocent people as possible. So they would like to choose the group with minimal number of people.

    Write a program that, given the number of detained people and their testimonies, will determine the number of people in the smallest group of potential perpetrators, that don't contradict to the testimonies.

    Input

    The first line of the input contains a single integer T, the number of testcases (1<=T<=10).

    First line of each testcase contains integer number N (2 <= N <= 100000), equal to the number of detained people (the people are numbered from 1 to N). The i-th of the following N lines contain one integer number Pi (1 <= Pi <= N). Here Pi is the man whom i-th man testified to be guilty.

    Output

    The output should consist of T lines, containing one integer number for each testcase - the number of people in the smallest group of potential perpetrators, that don't contradict to the testimonies.

    Example

    Input:
    1
    3
    2
    3
    1
    
    Output:
    2
    
    

    Added by:Bin Jin
    Date:2007-07-04
    Time limit:1s-2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:First Minsk Training Camp for NEERC teams, day 2 – MWPZ' 2003









    SPOJ Problem Set (classical)

    1675. Fusion Cube

    Problem code: FUSION

    The Bogus Corporation claims to have solved the energy crisis by devising a method to perform controlled fusion reaction! The set up consists of a cube of side length N meters, which contain K point sources of electrons. Each of the sources can be configured to emanate an electron along any of the six possible directions corresponding to +X axis, -X axis, +Y axis, -Y axis, +Z axis, -Z axis. The cube is filled with a medium in which the electrons travel with a velocity of 1m/s. At time t=0, all the sources are switched on simultaneously, emanating a single electron along the configured direction. An electron travels in a straight line until it strikes the boundary of the cube or collides with another electron. A collision between two electrons can occur in two possible ways - a head-on collision, and a side-on collision. In a head-on collision, both the electrons rebound in opposite directions with the same speed. A side-on collision occurs when the colliding electrons are travelling in mutually perpendicular directions. After a side-on collision, the colliding electrons are deflected by 90 degrees, rebounding in mutually perpendicular directions with the same speed, the plane of motion remaining the same. Note that throughout the experiment, the direction of motion of an electron remains oriented along one of the coordinate axes. If more than two electrons collide simultaneously, resolve the collision pairwise, where any two of the colliding electrons can be paired. To maximize the chances of initiating the fusion reaction, we would like to maximize the time before an electron hits a boundary wall of the cube. Given the location of the K sources, determine the orientation of the sources such that this time is maximized. Output this maximum value.

    Input

    First line contains a single integer T, the number of test cases ( 1<=T<=50),  followed by the description of the test cases. The first line of each test case contains two integers, K and N respectively ( 1<=K<=100, 1<=N<=1000). It is followed by K lines, where each line contains space separated three integers representing the X, Y and Z coordinates of the particular source. The coordinates of the diagonally opposite corners of the cube are (0,0,0) and (N,N,N). All the sources will lie strictly inside the cube.

    Output

    For each test case, output the maximum value of the time before the first electron hits the boundary of the cube on a single line.

    Example

    Input:
    2
    1 10
    5 5 5
    2 10
    1 1 1
    1 1 2
    Output:
    5
    9
    

    Added by:Rahul Garg
    Date:2007-07-04
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:C-maphore, Tryst 2007









    SPOJ Problem Set (classical)

    1676. Text Generator

    Problem code: GEN

    LoadingTime has been given a task these days. He is required to write a tool called Text Generator. This software is widely used among the kids who are under seven. It generates an article with the size of a given number L for users. If an article contains at least one word which the users know, we consider it readable. Now, LoadingTime wants to know, how many readable articles can it generates, and he can improve his Text Generator. Could you help him??

    Input

    The input contains multiple test cases.

    The first line of each test case contains two integer N (1 <= N <= 10), L (1 <= L <= 1000000). The following N lines contain N words representing the words knew by the users. All the words and the generated article only contain uppercase letters, and the length of each word is not greater than 6.

    Output

    For each test case, your program should output a integer as LoadingTime required. As the number could be quite large, you only need to print the answer modulo 10007.

    Example

    Input:
    2 2
    A
    B
    2 10000
    ABC
    B
    
    Output:
    100
    5960
    
    

    Added by:Bin Jin
    Date:2007-07-05
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:









    SPOJ Problem Set (classical)

    1677. Halloween treats

    Problem code: HALLOW

    Every year there is the same problem at Halloween: Each neighbor is only willing to give a certain total number of sweets on that day, no matter how many children call on him, so it may happen that a child will get nothing if it is too late. To avoid conflicts, the children have decided they will put all sweets together and then divide them evenly among themselves. From last year's experience of Halloween they know how many sweets they get from each neighbour. Since they care more about justice than about the number of sweets they get, they want to select a subset of the neighbours to visit, so that in sharing every child receives the same number of sweets. They will not be satisfied if they have any sweets left which cannot be divided.

    Your job is to help the children and present a solution.

    Input

    The input contains several test cases.
    The first line of each test case contains two integers c and n (1 ≤ c ≤ n ≤ 100000), the number of children and the number of neighbours, respectively. The next line contains n space separated integers a1 , ... , an (1 ≤ ai ≤ 100000 ), where ai represents the number of sweets the children get if they visit neighbour i.

    The last test case is followed by two zeros.

    Output

    For each test case output one line with the indices of the neighbours the children should select (here, index i corresponds to neighbour i who gives a total number of ai sweets). If there is no solution where each child gets at least one sweet, print "no sweets" instead. Note that if there are several solutions where each child gets at least one sweet, you may print any of them.

    Example

    Input:
    4 5
    1 2 3 7 5
    3 6
    7 11 2 5 13 17
    0 0
    
    
    Output:
    3 5
    2 3 4
    

    Added by:Simon Gog
    Date:2007-07-05
    Time limit:15s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:University of Ulm Local Contest 2007/2008









    SPOJ Problem Set (classical)

    1678. Royal Treasury

    Problem code: TREASURY

    Once upon a time in a kingdom far far away, the royal treasury started getting emptier and emptier. The king decided to change the situation and he invented a new system of cooperation with in the office of the royal treasurer. The clerks of the office are supposed to form pairs (in order to avoid being bribed) in such away that each pair is formed by a clerk and his/her direct subordinate. Your task is to compute, given the structure of the office of the treasurer, the maximum number of pairs that can be formed this way and in how many different ways this is possible.

    The office of the treasurer is led by George Skinflint. Each clerk has zero, one or more subordinates and is a subordinate of a single clerk (except for George Skinflint who is responsible only to the king himself). The number of clerks does not exceed 1000. Your task is to compute the maximum number of pairs that can be formed by clerks in such a way that every pair is formed by a clerk and his/her direct subordinate. In addition, you should also compute the number of ways such pairs can be formed. Note that some clerks need not be contained in a pair.

    Input

    The input contains multiple testcases.

    The first line of each testcase contains a single number N that represents the number of clerks 1 <= N <= 1000. The clerks are assigned unique ID numbers from the range between 1 and N. The ID number of the treasurer (Skinflint) is 1. Each of the following N lines corresponds to one of the clerks: it contains his/her ID number, the number K of his/her subordinates, 0 <= K <= 999, and the ID numbers of his/her K subordinates separated by single spaces. You can assume that the line corresponding to a clerk never appears before the line corresponding to his/her supervisor.

    Output

    The output for each testcase should consist of two lines. The first line of the output should contain a single number that represents the maximum number M of pairs that the clerks can form. The second line should contain the number of different ways in which the clerks can form M pairs obeying the rules given by the king.

    Example

    Input:
    7
    1 3 2 4 7
    2 1 3
    4 1 6
    3 0
    7 1 5
    5 0
    6 0
    
    Output:
    3
    4
    

    Added by:Bin Jin
    Date:2007-07-06
    Time limit:0.5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:CEOI 2007, day 2









    SPOJ Problem Set (classical)

    1681. Cylinder

    Problem code: CYLINDER

    Using a sheet of paper and scissors, you can cut out two faces to form a cylinder in the following way:

    1. Cut the paper horizontally (parallel to the shorter side) to get two rectangular parts.
    2. From the first part, cut out a circle of maximum radius. The circle will form the bottom of the cylinder.
    3. Roll the second part up in such a way that it has a perimeter of equal length with the circle's circumference, and attach one end of the roll to the circle. Note that the roll may have some overlapping parts in order to get the required length of the perimeter.

    Given the dimensions of the sheet of paper, can you calculate the biggest possible volume of a cylinder which can be constructed using the procedure described above?

    Input Specification

    The input consists of several test cases. Each test case consists of two numbers w and h (1 ≤ w ≤ h ≤ 100), which indicate the width and height of the sheet of paper.

    The last test case is followed by a line containing two zeros.

    Output Specification

    For each test case, print one line with the biggest possible volume of the cylinder. Round this number to 3 places after the decimal point.

    Sample Input

    10 10
    10 50
    10 30
    0 0
    

    Sample Output

    54.247
    785.398
    412.095
    

    In the first case, the optimal cylinder has a radius of about 1.591549, in the second case, the optimal cylinder has a radius of 5, and in the third case, the optimal cylinder has a radius of about 3.621795.
    Added by:Adrian Kuegel
    Date:2007-07-06
    Time limit:4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:own problem, used in University of Ulm Local Contest 2007









    SPOJ Problem Set (classical)

    1683. Expressions

    Problem code: EXPRESS

    Arithmetic expressions are usually written with the operators in between the two operands (which is called infix notation). For example, (x+y)*(z-w) is an arithmetic expression in infix notation. However, it is easier to write a program to evaluate an expression if the expression is written in postfix notation (also known as reverse polish notation). In postfix notation, an operator is written behind its two operands, which may be expressions themselves. For example, x y + z w - * is a postfix notation of the arithmetic expression given above. Note that in this case parentheses are not required.

    To evaluate an expression written in postfix notation, an algorithm operating on a stack can be used. A stack is a data structure which supports two operations:

    1. push: a number is inserted at the top of the stack.
    2. pop: the number from the top of the stack is taken out.

    During the evaluation, we process the expression from left to right. If we encounter a number, we push it onto the stack. If we encounter an operator, we pop the first two numbers from the stack, apply the operator on them, and push the result back onto the stack. More specifically, the following pseudocode shows how to handle the case when we encounter an operator O:

    a := pop();
    b := pop();
    push(b O a);

    The result of the expression will be left as the only number on the stack.

    Now imagine that we use a queue instead of the stack. A queue also has a push and pop operation, but their meaning is different:

    1. push: a number is inserted at the end of the queue.
    2. pop: the number from the front of the queue is taken out of the queue.

    Can you rewrite the given expression such that the result of the algorithm using the queue is the same as the result of the original expression evaluated using the algorithm with the stack?

    Input Specification

    The first line of the input contains a number T (T ≤ 200). The following T lines each contain one expression in postfix notation. Arithmetic operators are represented by uppercase letters, numbers are represented by lowercase letters. You may assume that the length of each expression is less than 10000 characters.

    Output Specification

    For each given expression, print the expression with the equivalent result when using the algorithm with the queue instead of the stack. To make the solution unique, you are not allowed to assume that the operators are associative or commutative.

    Sample Input

    2
    xyPzwIM
    abcABdefgCDEF
    

    Sample Output

    wzyxIPM
    gfCecbDdAaEBF
    

    Added by:Adrian Kuegel
    Date:2007-07-06
    Time limit:4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:own problem, used in University of Ulm Local Contest 2007









    SPOJ Problem Set (classical)

    1684. Frequent values

    Problem code: FREQUENT

    You are given a sequence of n integers a1 , a2 , ... , an in non-decreasing order. In addition to that, you are given several queries consisting of indices i and j (1 ≤ i ≤ j ≤ n). For each query, determine the most frequent value among the integers ai , ... , aj.

    Input Specification

    The input consists of several test cases. Each test case starts with a line containing two integers n and q (1 ≤ n, q ≤ 100000). The next line contains n integers a1 , ... , an (-100000 ≤ ai ≤ 100000, for each i ∈ {1, ..., n}) separated by spaces. You can assume that for each i ∈ {1, ..., n-1}: ai ≤ ai+1. The following q lines contain one query each, consisting of two integers i and j (1 ≤ i ≤ j ≤ n), which indicate the boundary indices for the query.

    The last test case is followed by a line containing a single 0.

    Output Specification

    For each query, print one line with one integer: The number of occurrences of the most frequent value within the given range.

    Sample Input

    10 3
    -1 -1 1 1 1 1 3 10 10 10
    2 3
    1 10
    5 10
    0
    

    Sample Output

    1
    4
    3
    

    A naive algorithm may not run in time!
    Added by:Adrian Kuegel
    Date:2007-07-06
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:University of Ulm Local Contest 2007









    SPOJ Problem Set (classical)

    1685. Grocery store

    Problem code: GROCERY


    A cashier in a grocery store seems to have difficulty in distinguishing the multiplication symbol and the addition symbol. To make things easier for him, you want to buy goods in such a way that the product of their prices is the same as the sum of their prices.

    Of course, if you buy only one item, this is always true. With two items and three items, it still seems quite a boring task to you, so now you are interested in finding possible prices of four items such that the sum of the four prices is equal to the product of the four prices. You should consider the prices are in € with two digits after the decimal point. Obviously, each product costs at least one cent.

    Input Specification

    This problem has no input.

    Output Specification

    Print all solutions which have a sum of the four items of at most 20.00 €. For each solution, print one line with the prices of the four items in non-decreasing order, with one space character between them. You may print the solutions in any order, but make sure to print each solution only once.

    Sample Output

    0.50 1.00 2.50 16.00
    1.25 1.60 1.75 1.84
    1.25 1.40 1.86 2.00
    ...
    

    Added by:Adrian Kuegel
    Date:2007-07-06
    Time limit:1.600s
    Source limit:600B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:University of Ulm Local Contest 2007









    SPOJ Problem Set (classical)

    1687. Logic II

    Problem code: LOGIC2

    Some day in 2003 in Byteland began calm and quietly as any other day. Some people went to work, some to school, some to store to buy food. Drivers were traditionally stucked in traffic jams, drinking coffee and reading morning newspaper. Suddenly the regularity of this day was disturbed by huge explosion."They blew up the embassy of Bajtocja!!!" somebody cried. Everybody began to run away in panic.

    Police works pretty good in Byteland and first radiocars appeared near the embassy only few seconds after the explosion. All the people near the embassy were detained. Only one of the people is the organizer of the explosion, the others could by just occasional witnesses. It is known, among these M(1<=M<=11) people, N(1<=N<=M) people always lie because they want to make the work of police more difficult, the others always tell the truth.

    All these people say P(1<=P<=30) sentences in total.All the useful sentences are in one of the 4 forms below, all the other sentences are useless and you can ignore them.

    • I am guilty.
    • I am not guilty.
    • Somebody is guilty.
    • Somebody is not guilty.
    • Today is Someday.

    Among these sentences, Somebody is a name of one of these M people, and Someday is Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday.

    Your task is to help the police to find out the only one organizer of the explosion.

    Input

    Multiple test cases. For each test case:

    The first line contains three integers M, N and P. M lines follow, each contains a name of one of the people.All names contain only capital Latin letters and no whitespaces.P lines come next, each contains no more than 250 characters, the speaker and his/her speech. See the example.

    You can assume that there's no whitespace at the start and the end of a line, and there are no two consecutive spaces in the input.

    Input terminate by EOF.

    Output

    The name of the organizer if you can determine, or Cannot Determine if you find more than one, or Impossible if you find no one.

    Example

    Input:
    3 1 5
    MIKE
    CHARLES
    KATE
    MIKE: I am guilty.
    MIKE: Today is Sunday.
    CHARLES: MIKE is guilty.
    KATE: I am guilty.
    KATE: How are you??
    
    Output:
    MIKE
    

    Added by:[Trichromatic] XilinX
    Date:2007-07-13
    Time limit:13s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Description by Blue Mary









    SPOJ Problem Set (classical)

    1688. A Very Easy Problem!

    Problem code: EASYPROB

    Input

    There's no input.

    Output

    Output some form of these numbers: 137, 1315, 73, 136, 255, 1384, 16385, one per line in the listed order.

    Example

    The first two lines of the CORRECT output file are:

    137=2(2(2)+2+2(0))+2(2+2(0))+2(0)
    1315=2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
    

    The correct output file should contain 7 lines.


    Added by:[Trichromatic] XilinX
    Date:2007-07-13
    Time limit:1s
    Source limit:500B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:TEXT
    Resource:You can imagine it.









    SPOJ Problem Set (classical)

    1689. Hard Problem

    Problem code: HARDP


    [This space is intentionally left blank.]

    Input

    Multiple test cases. Each contains a single integer N(1<=N<=50). Input terminates by EOF.

    Output

    For each test case, output one line contains the answer. See the example.

    Example

    Input:

    8 9 10

    Output:

    8=90*(0+0+0+0+45-3+20-42+60+10) 9=20*(0-3+10-14+15+2+0+0+0+0+10) 10=66*(0+0+0+0+0+33+5-33+66-66+55+6)

    Added by:[Trichromatic] XilinX
    Date:2007-07-14
    Time limit:11s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Based on a problem from an ACM/ICPC Regional Contest









    SPOJ Problem Set (classical)

    1693. Coconuts

    Problem code: COCONUTS

    A group of n castle guards are voting to determine whether African swallows can carry coconuts. While each guard has his own personal opinion on the matter, a guard will often vote contrary to his beliefs in order to avoid disagreeing with the votes of his friends.
    You are given a list of guards who either do or do not believe in the coconut-carrying capacity of African swallows, and a list of all pairs of guards who are friends. Your task is to determine how each guard must vote in order to minimize the sum of the total number of disagreements between friends and the total number of guards who must vote against their own beliefs.

    Input

    The input to this problem will contain multiple test cases. Each test case begins with a single line containing an integer n (where 2 <= n <= 300), the number of guards, and an integer m (where 1 <= m <= n(n-1)/2), the number of pairs of guards who are friends. The second line of the test case contains n integers, where the ith integer is 1 if the ith guard believes in the ability of African swallows to carry coconuts, and 0 otherwise. Finally, the next m lines of the test case each contain two distinct integers i and j (where 1 <= i, j <= n), indicating that guards i and j are friends. Guards within each pair of friends may be listed in any order, but no pair of guards will be repeated. The input is terminated by an invalid test case with n = m = 0, which should not be processed.

    Output

    For each input test case, print a single line containing the minimum possible sum of the total number of disagreements between all friends plus the total number of guards who must vote against their own beliefs.

    Example

    Input:
    3 3
    1 0 0
    1 2
    1 3
    3 2
    6 6
    1 1 1 0 0 0
    1 2
    2 3
    4 2
    3 5
    4 5
    5 6
    0 0
    
    Output:
    1
    2
    

    Added by:Bin Jin
    Date:2007-07-22
    Time limit:1s
    Source limit:5000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:Pacific NW 2006









    SPOJ Problem Set (classical)

    1695. Grandpa’s Rubik Cube

    Problem code: GRC

    Documento sin título

    A very well-known toy/pastime, called Rubik's cube, consists of a cube as shown in Figure 1a, where letters stand for colors (e.g. B for blue, R for red,...). The goal of the game is to rotate the faces of the cube in such a way that at the end each face has a different color, as shown in Figure 1b. Notice that,

    when a face is rotated, the configuration of colors in all the adjacent faces changes. Figure 2 illustrates a rotation of one of the faces. Given a scrambled configuration, reaching the final position can be quite challenging, as you may know.

    But your grandpa has many years of experience, and claims that, given any configuration of the Rubik cube, he can come up with a sequence of rotations leading to a winning configuration. In order to show all faces of the cube we shall represent the cube as in Figure 3a. The six colors are Yellow, Red, Blue, Green, White and Magenta (represented by their first letters).
    You will be given an initial configuration and a list of rotations. A rotation will be represented by an integer number, indicating the face to be rotated and the direction of the rotation (a positive value means clockwise rotation, negative value means counter-clockwise rotation). Faces of the cube are numbered as shown in Figure 3b. You must write a program that checks whether the list of rotations will lead to a winning configuration.

    Input
    The input contains several test cases. The first line of the input is an integer which indicates the number of tests. Each test description consists of ten lines of input. The first nine lines of a test will describe an initial configuration, in the format shown in Figure 3a. The next line will contain a list of rotations, ending with the value 0.

    Output
    For each test case your program should print one line. If your grandpa is correct, print “Yes, grandpa!”, otherwise print “No, you are wrong!”. (See example.)


    Added by:Andrés Leonardo Rojas Duarte
    Date:2007-07-24
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:ACM International Collegiate Programming Contest 2002 – South America









    SPOJ Problem Set (classical)

    1696. Will Indiana Jones Get There

    Problem code: WIJGT


    Documento sin título

    Indiana Jones is in a deserted city, annihilated during a war. Roofs of all houses have been destroyed and only portions of walls are still standing. The ground is so full of mines that the only safe way to move around the city is walking over the remaining walls. The mission of our hero is to save a person who is trapped in the city. In order to move between two walls which are not connected Indiana Jones thought of taking with him a wooden board which he could place between the two walls and then cross from one to the other.

    Initial positions of Indiana Jones and the trapped person are both on some section of the walls. Besides, walls are either in the direction South-North or West-East. You will be given a map of the city remains. Your mission is to determine the minimum length of the wooden board Indiana Jones needs to carry in order to get to the trapped person.

    Input
    Your program should process several test cases. Each test case starts with an integer N indicating the number of wall sections remaining in the city (2 <= N <= 1000). Each of the next N lines describes a wall section. The first wall section to appear is the section where Indiana Jones stands at the beginning. The second section to appear is the section where the trapped person stands. Each wall section description consists of three integers X , Y and L (–10000 <= X , Y , L <= 10000), where X an Y define either the southernmost point of a wall section (for South-North sections) or the westernmost point
    (for West-East wall sections). The value of L determines the length and direction of the wall: if L > 0, the section is West-East, with length L ; if L< 0, the section is North-South, with length | L | . The end of input is indicated by N = 0.

    Output
    For each test case in the input your program should produce one line of output, containing a real value representing the length of the wooden board Indiana Jones must carry. The length must be printed as a real number with two-digit precision, and the last decimal digit must be rounded. The input will not contain test cases where differences in rounding are significant.

    Sample input
    14
    1 1 5
    6 8 2
    7 2 -2
    5 3 3
    2 5 2
    2 3 2
    2 3 -2
    4 3 -2
    0 7 1
    1 8 2
    3 6 -2
    4 7 2
    6 6 1
    6 6 -2
    3
    -10 0 20
    -5 1 10
    50 50 100
    0

    Output for the sample input
    1.41
    1.00


    Added by:Andrés Leonardo Rojas Duarte
    Date:2007-07-25
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:ACM International Collegiate Programming Contest 2002 – South America









    SPOJ Problem Set ()

    1697. Ohgas' Fortune

    Problem code: OFORTUNE

    The Ohgas are a prestigious family based on Hachioji. The head of the family, Mr. Nemochi Ohga, a famous wealthy man, wishes to increase his fortune by depositing his money to an operation company. You are asked to help Mr. Ohga maximize his profit by operating the given money during a specified period.

    From a given list of possible operations, you choose an operation to deposit the given fund to. You commit on the single operation throughout the period and deposit all the fund to it. Each operation specifies an annual interest rate, whether the interest is simple or compound, and an annual operation charge. An annual operation charge is a constant not depending on the balance of the fund. The amount of interest is calculated at the end of every year, by multiplying the balance of the fund under operation by the annual interest rate, and then rounding off its fractional part. For compound interest, it is added to the balance of the fund under operation, and thus becomes a subject of interest for the following years. For simple interest, on the other hand, it is saved somewhere else and does not enter the balance of the fund under operation (i.e. it is not a subject of interest in the following years). An operation charge is then subtracted from the balance of the fund under operation. You may assume here that you can always pay the operation charge (i.e. the balance of the fund under operation is never less than the operation charge). The amount of money you obtain after the specified years of operation is called ``the final amount of fund.'' For simple interest, it is the sum of the balance of the fund under operation at the end of the final year, plus the amount of interest accumulated throughout the period. For compound interest, it is simply the balance of the fund under operation at the end of the final year.

    Operation companies use C, C++, Java, etc., to perform their calculations, so they pay a special attention to their interest rates. That is, in these companies, an interest rate is always an integral multiple of 0.0001220703125 and between 0.0001220703125 and 0.125 (inclusive). 0.0001220703125 is a decimal representation of 1/8192. Thus, interest rates' being its multiples means that they can be represented with no errors under the double-precision binary representation of floating-point numbers.

    For example, if you operate 1000000 JPY for five years with an annual, compound interest rate of 0.03125 (3.125 %) and an annual operation charge of 3000 JPY, the balance changes as follows.
    The balance of the fund under operation(at the beginning of year)InterestThe balance of the fund under operation (at the end of year)
    AB = A × 0.03125 (and rounding off fractions)A + B - 3000
    1000000312501028250
    1028250321321057382
    1057382330431087425
    1087425339821118407
    1118407349501150357

    After the five years of operation, the final amount of fund is 1150357 JPY.

    If the interest is simple with all other parameters being equal, it looks like:
    The balance of the fund under operation (at the beginning of year)InterestThe balance of the fund under operation (at the end of year)Cumulative interest
    AB = A × 0.03125 (and rounding off fractions)A - 3000
    10000003125099700031250
    9970003115699400062406
    9940003106299100093468
    99100030968988000124436
    98800030875985000155311

    In this case the final amount of fund is the total of the fund under operation, 985000 JPY, and the cumulative interests, 155311 JPY, which is 1140311 JPY.

    Input

    The input consists of datasets. The entire input looks like:

      the number of datasets (=m)
      1st dataset
      2nd dataset
      ...
      m-th dataset

    The number of datasets, m, is no more than 100. Each dataset is formatted as follows.
      the initial amount of the fund for operation
      the number of years of operation
      the number of available operations (=n)
      operation 1
      operation 2
      ...
      operation n


    The initial amount of the fund for operation, the number of years of operation, and the number of available operations are all positive integers. The first is no more than 100000000, the second no more than 10, and the third no more than 100.

      Each ``operation'' is formatted as follows.

    simple-or-compound annual-interest-rate annual-operation-charge
    where simple-or-compound is a single character of either '0' or '1', with '0' indicating simple interest and '1' compound. annual-interest-rate is represented by a decimal fraction and is an integral multiple of 1/8192. annual-operation-charge is an integer not exceeding 100000.


    Output

    For each dataset, print a line having a decimal integer indicating the final amount of fund for the best operation. The best operation is the one that yields the maximum final amount among the available operations. Each line should not have any character other than this number.

    You may assume the final balance never exceeds 1000000000. You may also assume that at least one operation has the final amount of the fund no less than the initial amount of the fund.

    Example

    Input:
    4
    1000000
    5
    2
    0 0.03125 3000
    1 0.03125 3000
    6620000
    7
    2
    0 0.0732421875 42307
    1 0.0740966796875 40942
    39677000
    4
    4
    0 0.0709228515625 30754
    1 0.00634765625 26165
    0 0.03662109375 79468
    0 0.0679931640625 10932
    10585000
    6
    4
    1 0.0054931640625 59759
    1 0.12353515625 56464
    0 0.0496826171875 98193
    0 0.0887451171875 78966
    
    Output:
    1150357
    10559683
    50796918
    20829397
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
    Resource:Japan Domestic, 2005









    SPOJ Problem Set ()

    1698. Polygonal Line Search

    Problem code: PLSEARCH

    Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.

    A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.

    Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.

    Write a program that answers polygonal lines which have the same shape as the template.

    subir imagenes
    Figure 1: Polygonal lines

    Input

    The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.

    A dataset is given as follows.

    n
    Polygonal line0
    Polygonal line1
    Polygonal line2
    ...
    Polygonal linen

    n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.

    A polygonal line is given as follows.

    m
    x1 y1
    x2 y2
    ...
    xm ym

    m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000

    Output

    For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.

    Five continuous "+"s must be placed in a line at the end of each dataset.

    Example

    Input:
    5
    5
    0 0
    2 0
    2 1
    4 1
    4 0
    5
    0 0
    0 2
    -1 2
    -1 4
    0 4
    5
    0 0
    0 1
    -2 1
    -2 2
    0 2
    5
    0 0
    0 -1
    2 -1
    2 0
    4 0
    5
    0 0
    2 0
    2 -1
    4 -1
    4 0
    5
    0 0
    2 0
    2 1
    4 1
    4 0
    4
    4
    -60 -75
    -60 -78
    -42 -78
    -42 -6
    4
    10 3
    10 7
    -4 7
    -4 40
    4
    -74 66
    -74 63
    -92 63
    -92 135
    4
    -12 22
    -12 25
    -30 25
    -30 -47
    4
    12 -22
    12 -25
    30 -25
    30 47
    3
    5
    -8 5
    -8 2
    0 2
    0 4
    8 4
    5
    -3 -1
    0 -1
    0 7
    -2 7
    -2 16
    5
    -1 6
    -1 3
    7 3
    7 5
    16 5
    5
    0 1
    0 -2
    8 -2
    8 0
    17 0
    0
    
    Output:
    1
    3
    5
    +++++
    3
    4
    +++++
    +++++
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Japan Domestic, 2005









    SPOJ Problem Set (classical)

    1699. Numeral System

    Problem code: NSYSTEM

    Prof. Hachioji has devised a new numeral system of integral numbers with four lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5", "6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.

    The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1, respectively, and the digits "2", ...,"9" correspond to 2, ..., 9, respectively. This system has nothing to do with the Roman numeral system.

    For example, character strings

    "5m2c3x4i", "m2c4i" and "5m2c3x"

    correspond to the integral numbers 5234 (=5*1000+2*100+3*10+4*1), 1204 (=1000+2*100+4*1), and 5230 (=5*1000+2*100+3*10), respectively. The parts of strings in the above example, "5m", "2c", "3x" and "4i" represent 5000 (=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1), respectively.

    Each of the letters "m", "c", "x" and "i" may be prefixed by one of the digits "2", "3", ..., "9". In that case, the prefix digit and the letter are regarded as a pair. A pair that consists of a prefix digit and a letter corresponds to an integer that is equal to the original value of the letter multiplied by the value of the prefix digit.

    For each letter "m", "c", "x" and "i", the number of its occurrence in a string is at most one. When it has a prefix digit, it should appear together with the prefix digit. The letters "m", "c", "x" and "i" must appear in this order, from left to right. Moreover, when a digit exists in a string, it should appear as the prefix digit of the following letter. Each letter may be omitted in a string, but the whole string must not be empty. A string made in this manner is called an MCXI-string.

    An MCXI-string corresponds to a positive integer that is the sum of the values of the letters and those of the pairs contained in it as mentioned above. The positive integer corresponding to an MCXI-string is called its MCXI-value. Moreover, given an integer from 1 to 9999, there is a unique MCXI-string whose MCXI-value is equal to the given integer. For example, the MCXI-value of an MCXI-string "m2c4i" is 1204 that is equal to 1000 + 2*100 + 4*1. There are no MCXI-strings but "m2c4i" that correspond to 1204. Note that strings "1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are not valid MCXI-strings. The reasons are use of "1", multiple occurrences of "c", use of "0", and the wrong order of "c" and "m", respectively.

    Your job is to write a program for Prof. Hachioji that reads two MCXI-strings, computes the sum of their MCXI-values, and prints the MCXI-string corresponding to the result.

    Input

    The input is as follows. The first line contains a positive integer n (<= 500) that indicates the number of the following lines. The k+1 th line is the specification of the k th computation (k=1, ..., n).

    n
    specification1
    specification2
    ...
    specificationn

    Each specification is described in a line:

    MCXI-string1 MCXI-string2

    The two MCXI-strings are separated by a space.

    You may assume that the sum of the two MCXI-values of the two MCXI-strings in each specification is less than or equal to 9999.

    Output

    For each specification, your program should print an MCXI-string in a line. Its MCXI-value should be the sum of the two MCXI-values of the MCXI-strings in the specification. No other characters should appear in the output.

    Example

    Input:
    10
    xi x9i
    i 9i
    c2x2i 4c8x8i
    m2ci 4m7c9x8i
    9c9x9i i
    i 9m9c9x8i
    m i
    i m
    m9i i
    9m8c7xi c2x8i
    
    Output:
    3x
    x
    6cx
    5m9c9x9i
    m
    9m9c9x9i
    mi
    mi
    mx
    9m9c9x9i
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Japan Domestic, 2005









    SPOJ Problem Set (classical)

    1700. Traveling by Stagecoach

    Problem code: TRSTAGE

    Once upon a time, there was a traveler.

    He plans to travel using stagecoaches (horse wagons). His starting point and destination are fixed, but he cannot determine his route. Your job in this problem is to write a program which determines the route for him.

    There are several cities in the country, and a road network connecting them. If there is a road between two cities, one can travel by a stagecoach from one of them to the other. A coach ticket is needed for a coach ride. The number of horses is specified in each of the tickets. Of course, with more horses, the coach runs faster.

    At the starting point, the traveler has a number of coach tickets. By considering these tickets and the information on the road network, you should find the best possible route that takes him to the destination in the shortest time. The usage of coach tickets should be taken into account.

    The following conditions are assumed.

    • A coach ride takes the traveler from one city to another directly connected by a road. In other words, on each arrival to a city, he must change the coach.
    • Only one ticket can be used for a coach ride between two cities directly connected by a road.
    • Each ticket can be used only once.
    • The time needed for a coach ride is the distance between two cities divided by the number of horses.
    • The time needed for the coach change should be ignored.


    Input

    The input consists of multiple datasets, each in the following format. The last dataset is followed by a line containing five zeros (separated by a space).

    n m p a b
    t1 t2 ... tn
    x1 y1 z1
    x2 y2 z2
    ...
    xp yp zp


    Every input item in a dataset is a non-negative integer. If a line contains two or more input items, they are separated by a space.

    n is the number of coach tickets. You can assume that the number of tickets is between 1 and 8. m is the number of cities in the network. You can assume that the number of cities is between 2 and 30. p is the number of roads between cities, which may be zero.

    a is the city index of the starting city. b is the city index of the destination city. a is not equal to b. You can assume that all city indices in a dataset (including the above two) are between 1 and m.

    The second line of a dataset gives the details of coach tickets. ti is the number of horses specified in the i-th coach ticket (1<=i<=n). You can assume that the number of horses is between 1 and 10.

    The following p lines give the details of roads between cities. The i-th road connects two cities with city indices xi and yi, and has a distance zi (1<=i<=p). You can assume that the distance is between 1 and 100.

    No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions.

    Output

    For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces.

    If the traveler can reach the destination, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied.

    If the traveler cannot reach the destination, the string "Impossible" should be printed. One cannot reach the destination either when there are no routes leading to the destination, or when the number of tickets is not sufficient. Note that the first letter of "Impossible" is in uppercase, while the other letters are in lowercase.

    Example

    Input:
    3 4 3 1 4
    3 1 2
    1 2 10
    2 3 30
    3 4 20
    2 4 4 2 1
    3 1
    2 3 3
    1 3 3
    4 1 2
    4 2 5
    2 4 3 4 1
    5 5
    1 2 10
    2 3 10
    3 4 10
    1 2 0 1 2
    1
    8 5 10 1 5
    2 7 1 8 4 5 6 3
    1 2 5
    2 3 4
    3 4 7
    4 5 3
    1 3 25
    2 4 23
    3 5 22
    1 4 45
    2 5 51
    1 5 99
    0 0 0 0 0
    
    Output:
    30.000
    3.667
    Impossible
    Impossible
    2.856
    
    Since the number of digits after the decimal point is
    not specified, the above result is not the only
    solution. For example, the following result is also acceptable.
    
    30.0
    3.66667
    Impossible
    Impossible
    2.85595
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Japan Domestic, 2005









    SPOJ Problem Set ()

    1701. Earth Observation with a Mobile Robot Team

    Problem code: EOWAMRT

    A new type of mobile robot has been developed for environmental earth observation. It moves around on the ground, acquiring and recording various sorts of observational data using high precision sensors. Robots of this type have short range wireless communication devices and can exchange observational data with ones nearby. They also have large capacity memory units, on which they record data observed by themselves and those received from others.

    Figure 1 illustrates the current positions of three robots A, B, and C and the geographic coverage of their wireless devices. Each circle represents the wireless coverage of a robot, with its center representing the position of the robot. In this figure, two robots A and B are in the positions where A can transmit data to B, and vice versa. In contrast, C cannot communicate with A or B, since it is too remote from them. Still, however, once B moves towards C as in Figure 2, B and C can start communicating with each other. In this manner, B can relay observational data from A to C. Figure 3 shows another example, in which data propagate among several robots instantaneously.

    subir imagenes
    Figure 1: The initial configuration of three robots

    subir imagenes
    Figure 2: Mobile relaying

    subir imagenes
    Figure 3: Instantaneous relaying among multiple robots

    As you may notice from these examples, if a team of robots move properly, observational data quickly spread over a large number of them. Your mission is to write a program that simulates how information spreads among robots. Suppose that, regardless of data size, the time necessary for communication is negligible.

    Input

    The input consists of multiple datasets, each in the following format.

    N T R
    nickname and travel route of the first robot
    nickname and travel route of the second robot
    ...
    nickname and travel route of the N-th robot


    The first line contains three integers N, T, and R that are the number of robots, the length of the simulation period, and the maximum distance wireless signals can reach, respectively, and satisfy that 1 <= N <= 100, 1 <= T <= 1000, and 1 <= R <= 10.

    The nickname and travel route of each robot are given in the following format.

    nickname
    t0 x0 y0
    t1 vx1 vy1
    t2 vx2 vy2
    ...
    tk vxk vyk

    Nickname is a character string of length between one and eight that only contains lowercase letters. No two robots in a dataset may have the same nickname. Each of the lines following nickname contains three integers, satisfying the following conditions.

    0 = t0 < t1 < ... < tk = T
    -10 <= vx1, vy1, ..., vxk, vyk<= 10

    A robot moves around on a two dimensional plane. (x0, y0) is the location of the robot at time 0. From time ti-1 to ti (0 < i <= k), the velocities in the x and y directions are vxi and vyi, respectively. Therefore, the travel route of a robot is piecewise linear. Note that it may self-overlap or self-intersect.

    You may assume that each dataset satisfies the following conditions.

    • The distance between any two robots at time 0 is not exactly R.
    • The x- and y-coordinates of each robot are always between -500 and 500, inclusive.
    • Once any robot approaches within R + 10-6. of any other, the distance between them will become smaller than R - 10-6. while maintaining the velocities.
    • Once any robot moves away up to R - 10-6. of any other, the distance between them will become larger than R + 10-6. while maintaining the velocities.
    • If any pair of robots mutually enter the wireless area of the opposite ones at time t and any pair, which may share one or two members with the aforementioned pair, mutually leave the wireless area of the opposite ones at time t', the difference between t and t' is no smaller than 10-6. time unit, that is, |t - t' | >= 10-6.

    A dataset may include two or more robots that share the same location at the same time. However, you should still consider that they can move with the designated velocities.

    The end of the input is indicated by a line containing three zeros.

    Output

    For each dataset in the input, your program should print the nickname of each robot that have got until time T the observational data originally acquired by the first robot at time 0. Each nickname should be written in a separate line in dictionary order without any superfluous characters such as leading or trailing spaces.

    Example

    Input:
    3 5 10
    red
    0 0 0
    5 0 0
    green
    0 5 5
    5 6 1
    blue
    0 40 5
    5 0 0
    3 10 5
    atom
    0 47 32
    5 -10 -7
    10 1 0
    pluto
    0 0 0
    7 0 0
    10 3 3
    gesicht
    0 25 7
    5 -7 -2
    10 -1 10
    4 100 7
    impulse
    0 -500 0
    100 10 1
    freedom
    0 -491 0
    100 9 2
    destiny
    0 -472 0
    100 7 4
    strike
    0 -482 0
    100 8 3
    0 0 0
    
    Output:
    blue
    green
    red
    atom
    gesicht
    pluto
    freedom
    impulse
    strike
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:Japan Domestic, 2005









    SPOJ Problem Set (classical)

    1702. Cleaning Robot

    Problem code: CLEANRBT


    Here, we want to solve path planning for a mobile robot cleaning a rectangular room floor with furniture.

    Consider the room floor paved with square tiles whose size fits the cleaning robot (1 × 1). There are 'clean tiles' and 'dirty tiles', and the robot can change a 'dirty tile' to a 'clean tile' by visiting the tile. Also there may be some obstacles (furniture) whose size fits a tile in the room. If there is an obstacle on a tile, the robot cannot visit it. The robot moves to an adjacent tile with one move. The tile onto which the robot moves must be one of four tiles (i.e., east, west, north or south) adjacent to the tile where the robot is present. The robot may visit a tile twice or more.

    Your task is to write a program which computes the minimum number of moves for the robot to change all 'dirty tiles' to 'clean tiles', if ever possible.

    Input

    IThe input consists of multiple maps, each representing the size and arrangement of the room. A map is given in the following format.

    w h
    c11 c12 c13 ... c1w
    c21 c22 c23 ... c2w
    ...
    ch1 ch2 ch3 ... chw

    The integers w and h are the lengths of the two sides of the floor of the room in terms of widths of floor tiles. w and h are less than or equal to 20. The character cyx represents what is initially on the tile with coordinates (x, y) as follows.

    '.' : a clean tile
    '*' : a dirty tile
    'x' : a piece of furniture (obstacle)
    'o' : the robot (initial position)

    In the map the number of 'dirty tiles' does not exceed 10. There is only one 'robot'.

    The end of the input is indicated by a line containing two zeros.

    Output

    For each map, your program should output a line containing the minimum number of moves. If the map includes 'dirty tiles' which the robot cannot reach, your program should output -1.

    Example

    Input:
    7 5
    .......
    .o...*.
    .......
    .*...*.
    .......
    15 13
    .......x.......
    ...o...x....*..
    .......x.......
    .......x.......
    .......x.......
    ...............
    xxxxx.....xxxxx
    ...............
    .......x.......
    .......x.......
    .......x.......
    ..*....x....*..
    .......x.......
    10 10
    ..........
    ..o.......
    ..........
    ..........
    ..........
    .....xxxxx
    .....x....
    .....x.*..
    .....x....
    .....x....
    0 0
    
    Output:
    8
    49
    -1
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Japan Domestic, 2005









    SPOJ Problem Set (classical)

    1703. ACM (ACronymMaker)

    Problem code: ACMAKER

    The sadists who design problems for ACM programming contests often like to include the abbre- viation “ACM” somewhere in their problem descriptions. Thus, in years past, the World Finals has had problems involving “Apartment Construction Management,” the “Atheneum of Culture and Movies,” the “Association of Cover Manufacturers,” “ACM Airlines,” the “Association for Computa- tional Marinelife,” and even an insect named “Amelia Cheese Mite.” However, the number of word combinations beginning with A, C, and M that make sense is finite and the problem writers are starting to run out of ideas (it’s hard to think of problems about “Antidisestablishmentarianistic Chthonian Metalinguistics”). Fortunately, modern culture allows more flexibility in designing abbreviations — consider, for example:

    GDB — Gnu DeBugger
    LINUX — either “LINus’s UniX” or “LINUs’s miniX” or “Linux Is Not UniX”
    SNOBOL — StriNg Oriented symBOlic Language
    SPITBOL — SPeedy ImplemenTation of snoBOL
    

    The rules used in these examples seem to be:

    • Insignificant words (such as “of”, “a”, “the”, etc.) are ignored.
    • The letters of the abbreviation must appear, in the correct order, as an ordered sublist of the letters in the significant words of the phrase to be abbreviated.
    • At least one letter of the abbreviation must come from every significant word (multiple occurrences of a letter are, of course, treated as distinct).

    Of course these rules are often broken in real life. For instance, RADAR is an abbreviation for “RAdio Detecting And Ranging”. Under our rules (assuming that “and” is an insignificant word), this would not be a valid abbreviation (however, RADR or RADRAN or DODGING would be valid). You have been asked to take a list of insignificant words and a list of abbreviations and phrases and to determine in how many ways each abbreviation can be formed from the corresponding phrase according to the rules above.

    Input

    The input file consists of multiple scenarios. Each scenario begins with an integer 100 >= n >= 1 followed by n insignificant words, all in lower case, one per line with no extra white space. (A line containing 0 indicates end of input.) Following this are one or more test cases for this scenario, one per line, followed by a line containing the phrase “LAST CASE”. Each line containing a test case begins with an abbreviation (uppercase letters only) followed by a phrase (lowercase letters and spaces only). The abbreviation has length at least 1 and the phrase contains at least one significant word. No input line (including abbreviation, phrase, and spaces) will contain more than 150 characters. Within these limits, however, abbreviations and phrase words may be any length.

    Output

    For each test case, output the abbreviation followed by either

    is not a valid abbreviation

    or

    can be formed in i ways

    where i is the number of different ways in which the letters of the abbreviation may be assigned to the letters in the phrase according to the rules above. The value of i will not exceed the range of a 32-bit signed integer.

    Example

    Input:
    2
    and
    of
    ACM academy of computer makers
    RADAR radio detection and ranging
    LAST CASE
    2
    a
    an
    APPLY an apple a day
    LAST CASE
    0
    
    Output:
    ACM can be formed in 2 ways
    RADAR is not a valid abbreviation
    APPLY can be formed in 1 ways
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:East Central North America 2005









    SPOJ Problem Set (classical)

    1704. Countdown

    Problem code: CDOWN

    Ann Sister owns a genealogical database service, which maintains family tree history for her clients. When clients login to the system, they are presented with a variety of services: searching, printing, querying, etc. One recent question that came up which the system was not quite prepared for was the following: “Which member of my family had the most grandchildren?” The client who posed this question eventually had to answer it by manually searching the family tree database herself. Ann decided to have software written in case this question (or ones similar to it asking for great-grandchildren, or great-great-grandchildren, etc.) is asked in the future.

    Input

    Input will consist of multiple test cases. The first line of the input will contain a single integer indicating the number of test cases. Each test case starts with a single line containing two positive integers n and d, where n indicates the number of lines to follow containing information about the family tree, and d indicates the specific question being asked about the tree: if d = 1, then we are interested in persons with the most children (1 generation away); if d = 2, then we are interested in persons with the most grandchildren (2 generations away), and so on. The next n lines are of the form

    name m dname1 dname2 ... dnamem

    where name is one of the family members’ names, m is the number of his/her children, and dname1 through dnamem are the names of the children. These lines will be given in no particular order. You may assume that all n lines describe one single, connected tree. There will be no more than 1000 people in any one tree, and all names will be at most 10 characters long.

    Output

    For each test case, output the three names with the largest number of specified descendants in order of number of descendants. If there are ties, output the names within the tie in alphabetical order. Print fewer than three names if there are fewer than three people who match the problem criteria (you should not print anyone’s name who has 0 of the specified descendants), and print more than three if there is a tie near the bottom of the list. Print each name one per line, followed by a single space and then the number of specified descendants. The output for each test case should start with the line

    Tree i:

    where i is the test case number (starting at 1). Separate the output for each problem with a blank line.

    Example

    Input:
    3
    8 2
    Barney 2 Fred Ginger
    Ingrid 1 Nolan
    Cindy 1 Hal
    Jeff 2 Oliva Peter
    Don 2 Ingrid Jeff
    Fred 1 Kathy
    Andrea 4 Barney Cindy Don Eloise
    Hal 2 Lionel Mary
    6 1
    Phillip 5 Jim Phil Jane Joe Paul
    Jim 1 Jimmy
    Phil 1 Philly
    Jane 1 Janey
    Joe 1 Joey
    Paul 1 Pauly
    6 2
    Phillip 5 Jim Phil Jane Joe Paul
    Jim 1 Jimmy
    Phil 1 Philly
    Jane 1 Janey
    Joe 1 Joey
    Paul 1 Pauly
    
    Output:
    Tree 1:
    Andrea 5
    Don 3
    Cindy 2
    Tree 2:
    Phillip 5
    Jane 1
    Jim 1
    Joe 1
    Paul 1
    Phil 1
    Tree 3:
    Phillip 5
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:East Central North America 2005









    SPOJ Problem Set ()

    1705. The Game of Efil

    Problem code: GAMEFIL

    Almost anyone who has ever taken a class in computer science is familiar with the “Game of Life,” John Conway’s cellular automata with extremely simple rules of birth, survival, and death that can give rise to astonishing complexity.

    The game is played on a rectangular field of cells, each of which has eight neighbors (adjacent cells). A cell is either occupied or not. The rules for deriving a generation from the previous one are:

    • If an occupied cell has 0, 1, 4, 5, 6, 7, or 8 occupied neighbors, the organism dies (0, 1: of loneliness; 4 thru 8: of overcrowding).
    • If an occupied cell has two or three occupied neighbors, the organism survives to the next gener- ation.
    • If an unoccupied cell has three occupied neighbors, it becomes occupied (a birth occurs).

    One of the major problems researchers have looked at over the years is the existence of so-called “Garden of Eden” configurations in the Game of Life — configurations that could not have arisen as the result of the application of the rules to some previous configuration. We’re going to extend this question, which we’ll call the “Game of Efil”: Given a starting configuration, how many possible parent configurations could it have? To make matters easier, we assume a finite grid in which edge and corner cells “wrap around” (i.e., a toroidal surface). For instance, the 2 by 3 configuration:

    subir imagenes

    has exactly three possible parent configurations; they are:

    subir imagenes subir imagenes subir imagenes

    You should note that when counting neighbors of a cell, another cell may be counted as a neighbor more than once, if it touches the given cell on more than one side due to the wrap around. This is the case for the configurations above.

    Input

    There will be multiple test cases. Each case will start with a line containing a pair of positive integers m and n, indicating the number of rows and columns of the configuration, respectively. The next line will contain a nonnegative integer k indicating the number of “live” cells in the configuration. The following k lines each contain the row and column number of one live cell, where row and column numbering both start at zero. The final test case is followed by a line where m = n = 0 — this line should not be processed. You may assume that the product of m and n is no more than 16.

    Output

    For each test case you should print one line of output containing the case number and the number of possible ancestors. Imitate the sample output below. Note that if there are 0 ancestors, you should print out

    Garden of Eden.

    Example

    Input:
    2 3
    2
    0 0
    0 1
    3 3
    4
    0 0
    0 1
    0 2
    1 1
    3 3
    5
    0 0
    1 0
    1 2
    2 1
    2 2
    0 0
    
    Output:
    Case 1: 3 possible ancestors.
    Case 2: 1 possible ancestors.
    Case 3: Garden of Eden.
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:60s-65s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:East Central North America 2005









    SPOJ Problem Set (classical)

    1706. Queens, Knights and Pawns

    Problem code: QKP

    You all are familiar with the famous 8-queens problem which asks you to place 8 queens on a chess board so no two attack each other. In this problem, you will be given locations of queens and knights and pawns and asked to find how many of the unoccupied squares on the board are not under attack from either a queen or a knight (or both). We’ll call such squares “safe” squares. Here, pawns will only serve as blockers and have no capturing ability. The board below has 6 safe squares. (The shaded squares are safe.)

    subir imagenes

    Recall that a knight moves to any unoccupied square that is on the opposite corner of a 2x3 rectangle from its current position; a queen moves to any square that is visible in any of the eight horizontal, vertical, and diagonal directions from the current position. Note that the movement of a queen can be blocked by another piece, while a knight’s movement can not.

    Input

    There will be multiple test cases. Each test case will consist of 4 lines. The first line will contain two integers n and m, indicating the dimensions of the board, giving rows and columns, respectively. Neither integer will exceed 1000. The next three lines will each be of the form

    k r1 c1 r2 c2 · · · rk ck

    indicating the location of the queens, knights and pawns, respectively. The numbering of the rows and columns will start at one. There will be no more than 100 of any one piece. Values of n = m = 0 indicate end of input.

    Output

    Each test case should generate one line of the form

    Board b has s safe squares.

    where b is the number of the board (starting at one) and you supply the correct value for s.

    Example

    4 4
    2 1 4 2 4
    1 1 2
    1 2 3
    2 3
    1 1 2
    1 1 1
    0
    1000 1000
    1 3 3
    0
    0
    0 0
    
    Output:
    Board 1 has 6 safe squares.
    Board 2 has 0 safe squares.
    Board 3 has 996998 safe squares.
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:East Central North America 2005









    SPOJ Problem Set (classical)

    1707. Reliable Nets

    Problem code: RELINETS

    You’re in charge of designing a campus network between buildings and are very worried about its reliability and its cost. So, you’ve decided to build some redundancy into your network while keeping it as inexpensive as possible. Specifically, you want to build the cheapest network so that if any one line is broken, all buildings can still communicate. We’ll call this a minimal reliable net.

    Input

    There will be multiple test cases for this problem. Each test case will start with a pair of integers n (<=15) and m (<= 20) on a line indicating the number of buildings (numbered 1 through n) and the number of potential inter-building connections, respectively. (Values of n = m = 0 indicate the end of the problem.) The following m lines are of the form b1 b2 c (all positive integers) indicating that it costs c to connect building b1 and b2. All connections are bidirectional.

    Output

    For each test case you should print one line giving the cost of a minimal reliable net. If there is a minimal reliable net, the output line should be of the form:

    The minimal cost for test case p is c.

    where p is the number of the test case (starting at 1) and c is the cost. If there is no reliable net possible, output a line of the form:

    There is no reliable net possible for test case p.

    Example

    Input:
    4 5
    1 2 1
    1 3 2
    2 4 2
    3 4 1
    2 3 1
    2 1
    1 2 5
    0 0
    
    Output:
    The minimal cost for test case 1 is 6.
    There is no reliable net possible for test case 2.
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:East Central North America 2005









    SPOJ Problem Set (classical)

    1708. Square Count

    Problem code: SQCOUNT

    Little Bobby Roberts, age 8, has been dragged to yet another museum by his parents. While they while away the hours studying Etruscan pottery and Warhol soup cans, Bobby must depend on himself for entertainment. Having a mathematical bent, he recently started counting all the square tiles on the floors of the museum. He soon realized that the tiles could be grouped into larger squares that needed to be added to the count. The problem became a bit more complicated when he started counting squares contained in multiple rooms, since some squares overlapped both rooms. For example, the two rooms shown below contain a total of 86 squares: 45 1 × 1 squares, 28 2 × 2 squares and 13 3 × 3 squares. (Note the opening between the two rooms is only 3 squares wide.)

    subir imagenes

    While this helped kill several days’ worth of museum visits, it soon became rather tedious, so Bobby is now looking for a program to automate the counting process for him.

    Input

    Input will consist of multiple test cases. The first line of each case will be a positive integer n <= 1000 which will indicate the number of rooms in the museum. After this will be n lines, each containing a description of one room. Each room will be rectangular in shape and will be described by a line of the form

    x1 y1 x2 y2

    where (x1, y1) and (x2, y2) are opposing corner coordinates (integers) of the room. No two rooms will overlap, though they may share a side. If the shared side is of length m > 2, then a door of length m−2 exists between the two rooms, centered along the shared length. No square of any size will overlap more than two rooms. All x and y values will be <= 1, 000, 000. An input line of n = 0 terminates input and should not be processed.

    Output

    For each test case, output the total number of squares on a single line in the format shown below. All answers will fit within a 32-bit integer and cases are enumerated starting at 1.

    Example

    Input:
    2
    0 0 9 3
    10 6 4 3
    3
    11 20 15 24
    11 17 15 20
    15 16 20 24
    0
    
    Output:
    Case 1: 86
    Case 2: 152
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:East Central North America 2005









    SPOJ Problem Set (classical)

    1709. Swamp Things

    Problem code: SWTHIN

    Hugh F. Oh, in his never-ending quest to prove the existence of extraterrestrials, has gotten hold of a number of nighttime photographs taken by a research group that is examining glowing swamp gas. Hugh wants to see if any of the photos show, not swamp gas, but Little Grey Men in glowing suits. The photographs consist of bright dots appearing against a black background. Unfortunately, at the time the photos were taken, trains were travelling through the area (there is a train trestle over the swamp), and occasional lights from the train windows also appear in the photographs. Hugh, being a fastidious researcher, wants to eliminate these spots from the images. He can’t tell from the photos exactly where the tracks are, or from what direction the photos were taken, but he knows that the tracks in that area are perfectly straight, so he’s decided on the following approach: he will find the line with the maximum number of spots lying on it and, if there are four or more spots on the line, he will eliminate those points from his calculations, assuming that those are windows on the train. If two or more lines have the maximum number of points, Hugh will just randomly select one such set and delete it from the photo (he’s not all that fastidious – after all, he believes in Little Grey Men). If there are fewer than four points lying along a common line, Hugh will assume that there is no train in the photograph and won’t delete any points. Please write a program for him to process a set of photographs.

    Input

    There will be a series of test cases. Each test case is one photograph described by a line containing a positive integer n (<= 1000) the number of distinct spots in the photograph, followed by n lines containing the integer coordinates of the spots, one (x, y) pair per line. All coordinates are between 0 and 10000. The last photo description is followed by a line containing a zero, marking the end of the input. This line should not be processed.

    Output

    For each test case, output the photo number followed by the number of points eliminated from the photograph. Imitate the sample output below.

    Example

    Input:
    6
    0 1
    0 2
    1 2
    2 2
    4 5
    5 6
    4
    3 5
    4 4
    6 5
    7 4
    0
    
    Output:
    Photo 1: 4 points eliminated
    Photo 2: 0 points eliminated
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:25s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:East Central North America 2005









    SPOJ Problem Set (classical)

    1710. Two Ends

    Problem code: TWENDS

    In the two-player game “Two Ends”, an even number of cards is laid out in a row. On each card, face up, is written a positive integer. Players take turns removing a card from either end of the row and placing the card in their pile. The player whose cards add up to the highest number wins the game. Now one strategy is to simply pick the card at the end that is the largest — we’ll call this the greedy strategy. However, this is not always optimal, as the following example shows: (The first player would win if she would first pick the 3 instead of the 4.)

    3 2 10 4

    You are to determine exactly how bad the greedy strategy is for different games when the second player uses it but the first player is free to use any strategy she wishes.

    Input

    There will be multiple test cases. Each test case will be contained on one line. Each line will start with an even integer n followed by n positive integers. A value of n = 0 indicates end of input. You may assume that n is no more than 1000. Furthermore, you may assume that the sum of the numbers in the list does not exceed 1,000,000.

    Output

    For each test case you should print one line of output of the form:

    In game m, the greedy strategy might lose by as many as p points.

    where m is the number of the game (starting at game 1) and p is the maximum possible difference between the first player’s score and second player’s score when the second player uses the greedy strategy. When employing the greedy strategy, always take the larger end. If there is a tie, remove the left end.

    Example

    Input:
    4 3 2 10 4
    8 1 2 3 4 5 6 7 8
    8 2 2 1 5 3 8 7 3
    0
    
    Output:
    In game 1, the greedy strategy might lose by as many as 7 points.
    In game 2, the greedy strategy might lose by as many as 4 points.
    In game 3, the greedy strategy might lose by as many as 5 points.
    

    Added by:Camilo Andrés Varela León
    Date:2007-07-26
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:East Central North America 2005









    SPOJ Problem Set (classical)

    1712. Permalex

    Problem code: PRMLX


    Given a string of characters, we can permute the individual characters to make new strings. If we can impose an ordering on the characters (say alphabetic sequence), then the strings themselves can be ordered and any given permutation can be given a unique number designating its position in that ordering. For example the string `acab' gives rise to the following 12 distinct permutations:

    aabc 1 acab 5 bcaa 9
    aacb 2 acba 6 caab 10
    abac 3 baac 7 caba 11
    abca 4 baca 8 cbaa 12

    Thus the string `acab' can be characterised in this sequence as 5.

    Write a program that will read in a string and determine its position in the ordered sequence of permutations of its constituent characters. Note that numbers of permutations can get very large; however we guarantee that no string will be given whose position is more than 2^31 = 2.147.483.647

    Input and Output

    Input will consist of a series of lines, each line containing one string. Each string will consist of up to 30 lower case letters, not necessarily distinct. Test cases a separated by empty lines. The file will be terminated by a line consisting of a single #.

    Output will consist of a series of lines, one for each line of the input. Each line will consist of the position of the string in its sequence, right justified in a field of width 10.

    Sample Input

    bacaa
    abc
    cba
    
    bacaa
    abc
    cba
    #

    Sample Output

            15
             1
             6
    
            15
             1
             6
    

    Added by:Andrés Leonardo Rojas Duarte
    Date:2007-07-27
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC 1992 Northwestern European Regionals









    SPOJ Problem Set (classical)

    1713. Funny scales

    Problem code: SCALE

    Kinh_Can has a set of precious weights P1, P2, ..., PN in which the mass of the ith weight is Pi = 3i-1, and a balance with 2 scales. On a nice day, Kinh_Can decided to show off his set of precious weights to his friends, and said that he can put them in equilibrium with any weight as long as its mass is not more than the mass of the sum of his weights. At first, his friends didn't believe, but after many trials they realized that Kinh_Can was right. In addition, while putting a thing whose mass is X on a scale, Kinh_Can could put right away the weights added on the 2 scales to keep their blance without any trial. With a random weight X (X is a natural number, X ≠ 0). Your task is to put weights on scales in order to keep the 2 scales' balance like Kinh_Can. The first scale initially weights X, and the second one weights 0.

    Input

    Input has exactly one line consisting 2 numbers, the first is N and the second is X.

    Output

    • If there is no solution, you should write -1
    • If there is at least one solution for the problem, you should write exactly 2 lines:
      • The first line contains some numbers descripting the indices of the weights in the first disc
      • The second line contains some numbers description the indices of the weights in the second disc
      • Note: One of 2 lines can be blank

    Constraints

    • 1 ≤ N ≤ 20
    • 1 ≤ X ≤ 2000000000

    Example

    Input 1:
    10 2
    
    Output 1:
    1
    2
    
    Input 2:
    10 5
    
    Output 2:
    1 2
    3
    
    

    Added by:Unknown
    Date:2007-07-29
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Classical









    SPOJ Problem Set (classical)

    1715. Another Necklace Problem

    Problem code: NCKLCE

    T Corporation is a company which produces colorful necklaces. The necklaces designed by them are unique and fashionable, and because of the price, they are popular with the youth. Now, T Corporation intends to design a self-help Producing System.

    This system includes hardware and software. The software is interactive and controls the hardware. Now the hardware has been completed, but the software is to develop. The workers find you, who is taking NOI. Could you please write a software system to simulate?

    A necklace includes N beads. The color of each bead is one of 1..c. The necklace is fixed in a plain. One position of the plain is marked as Position 1, and the other positions are marked as 2..n in clockwise.
    Your system should supply the orders as follow:

    +------------+-------------------------------+--------------------------------------------------+
    |Order       |Parameters restrictions        |Content                                           |
    +------------+-------------------------------+--------------------------------------------------+
    |R  k        |0 < k < N                      |It means Rotate K. Rotate the necklace by k       |
    |            |                               |positions in clockwise. i.e. The bead in former 1 |
    |            |                               |position will be transfer to position k+1, the    |
    |            |                               |bead in former 2 position will be transfer to     |
    |            |                               |position k+2, and so on.                          |
    +------------+-------------------------------+--------------------------------------------------+
    |F           |                               |It means Flip. Flip the plain by the given axis.  |
    |            |                               |The bead in position 1 doesn't move.The bead in   |
    |            |                               |position 2 will swap with the bead in position    |
    |            |                               |N,the bead in position 3 will swap with the bead  |
    |            |                               |in position n-1, and so on.                       |
    +------------+-------------------------------+--------------------------------------------------+
    |S i j       |1 <= i,j <= n                  |Swap the bead in position i and j.                |
    +------------+-------------------------------+--------------------------------------------------+
    |P i j x     |1 <= i,j <= n , x<= c          |It means Paint. Paint color x from position i to  |
    |            |                               |position j in clockwise.                          |
    +------------+-------------------------------+--------------------------------------------------+
    |C           |                               |It means Count. Ask how many parts are there in   |
    |            |                               |the necklace. We define some consecutive beads    |
    |            |                               |in same color as a "part". Pay attention that C is|
    |            |                               |different from CS 1,n.                            |
    +------------+-------------------------------+--------------------------------------------------+
    |CS i j      |1 <= i,j <= n                  |It means CountSegment i,j. Ask how many parts are |
    |            |                               |there from position i to position j in clockwise, |
    |            |                               |i and j included.                                 |
    +------------+-------------------------------+--------------------------------------------------+
    

    Input

    The first line in input includes two integers N,C, representing the beads in the necklace and the number of colors. The second line contains N integers x1,x2...xn, representing the colors of beads from position 1 to position n,1<=xi<=c. The third line includes a integer q, as the number of orders. There is an order in the next q lines, as mentioned above.

    For 60% test cases, n <= 1000, Q <= 1000;
    For 100% test cases, n <= 500000, Q <= 500000.

    Output

    For every order starts with C and CS, print a integer as the answer.

    Example

    Input:
    5 3
    1 2 3 2 1
    4
    C
    R 2
    P 5 5 2
    CS 4 1
    
    Output:
    4
    1
    
    Test data is unofficial. If you have any questions, please contact me.
    Added by:Bin Jin
    Date:2007-08-03
    Time limit:0.100s-5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:Chinese National Olympiad in Informatics 2007,Day 2









    SPOJ Problem Set (classical)

    1716. Can you answer these queries III

    Problem code: GSS3

    You are given a sequence A of N (N <= 50000) integers between -10000 and 10000. On this sequence you have to apply M (M <= 50000) operations:
    modify the i-th element in the sequence or for given x y print max{Ai + Ai+1 + .. + Aj | x<=i<=j<=y }.

    Input

    The first line of input contains an integer N. The following line contains N integers, representing the sequence A1..AN.
    The third line contains an integer M. The next M lines contain the operations in following form:
    0 x y: modify Ax into y (|y|<=10000).
    1 x y: print max{Ai + Ai+1 + .. + Aj | x<=i<=j<=y }.

    Output

    For each query, print an integer as the problem required.

    Example

    Input:
    4
    1 2 3 4
    4
    1 1 3
    0 3 -3
    1 2 4
    1 3 3
    
    Output:
    6
    4
    -3
    

    Added by:Bin Jin
    Date:2007-08-03
    Time limit:2s
    Source limit:5000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:own problem









    SPOJ Problem Set (classical)

    1722. Life, the Universe, and Everything II

    Problem code: RP

    This problem tests your mathematic knowledge and your programming ability very much. Your task is to calculate the number of different Minimum Spanning Trees (MSTs) of a special undirected unweighted graph. The graph has n nodes numbered from 1 to n, and there is an edge between node i (1<=i<=n) and node j (1<=j<=n) if and only if 0<|i-j|<=k.

    Input

    Multiple test cases, the number of them(<=8) is given in the very first line.

    Each test case contains one line with two space-separated numbers k(1<=k<=5) and n(1<=n<=1015).

    Output

    For each test case you should output one line, the number of different MSTs of the corresponding graph modulo 65521.

    Example

    Input:
    1
    3 5
    
    Output:
    75
    

    Added by:[Trichromatic] XilinX
    Date:2007-08-04
    Time limit:1s-4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2007,Day 2; Translated by Blue Mary









    SPOJ Problem Set (classical)

    1723. Bee Maja

    Problem code: BMJ


    Documento sin título

    Maja is a bee. She lives in a bee hive with thousands of other bees. This bee hive consists of many hexagonal honey combs where the honey is stored in.
    But bee Maja has a problem. Willi told her where she can meet him, but because Willi is a male drone and Maja is a female worker they have different coordinate systems.

    Maja's Coordinate System
    Willi's Coordinate System

    Maja who often flies directly to a special honey comb has laid an advanced two dimensional grid over the whole hive.

    Maja

    Willi who is more lazy and often walks around just numbered the cells clockwise starting from 1 in the middle of the hive.

    Willi

    Help Maja to convert Willi's system to hers. Write a program which for a given honey comb number gives the coordinates in Maja's system.

    Input

    The input contains one or more integers which represent Willi's numbers. Each number stands on its own in a separate line, directly followed by a newline. The honey comb numbers are all less than 100 000.

    Output

    You should output the corresponding Maja coordinates to Willi's numbers, each coordinate pair on a separate line.

    Sample Input

    1
    2
    3
    4
    5


    Sample Output

    0 0
    0 1
    -1 1
    -1 0
    0 -1


    Added by:Andrés Leonardo Rojas Duarte
    Date:2007-08-04
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Ulm Local 1999









    SPOJ Problem Set (classical)

    1724. Counting Triangles

    Problem code: TRICOUNT

    We define the LEVEL of a triangle as in the following illustrative image:

    Task: Your task is very easy. All you have to do is to count all triangles in the biggest one (Level N).

    Input

    The first line of the input contains an integer T (T ≤ 10000) - the number of test cases and T lines follow. Each line contains an integer N (1 ≤ N ≤ 106) which is the level of the triangle in that test case.

    Output

    For each test case, you should write a seperate line: the number of triangles in the biggest one (Level N). (All answers will fit within the range of a 64-bit integer)

    Example

    Input:
    3
    1
    2
    3

    Output:
    1
    5
    13

    Added by:Unknown
    Date:2007-08-05
    Time limit:1s
    Source limit:500B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Trần Huy Hưng









    SPOJ Problem Set (classical)

    1725. The Importance

    Problem code: IMPORT1


    Given an undirected weighted graph {V,E}. Your task to calculate the importance of each node.

    The importance of a node v (I(v)) can be defined as follow:

    Cs,t is the number of different shortest paths from s to t, Cs,t(v) is the number of different shortest paths from s to t through v.

    Input

    Multiple test cases, the number of them is given in the very first line.

    For each test case:

    The first line contains two space-separated integers n(n<=100) and m(m<=4500), the number of nodes in the graph and the number of edges in the graph. The nodes are numbered from 1 to n. m lines follow, each contains 3 integers a, b, c, 1<=a, b<=n, 1<=c<=1000, a!=b, which denotes that there is an undirected edge between node a and node b weighted c. You may assume that there is at most one edge between any pair of nodes, and the number of shortest paths between any pair of nodes is at least 1 and at most 1010.

    Output

    For each test case:

    Your Output should contains n lines, each contains one single real number, with 3 decimal places after radix point. The number in the ith line denotes the importance of the ith node.

    Example

    Input:
    1
    4 4
    1 2 1
    2 3 1
    3 4 1
    4 1 1
    
    Output:
    1.000
    1.000
    1.000
    1.000
    

    Added by:[Trichromatic] XilinX
    Date:2007-08-05
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2007,Day 1; Translated by Blue Mary









    SPOJ Problem Set (classical)

    1726. Exchange

    Problem code: EXCHANGE

    There are 3 kinds of money in a planet far away from the earth: Mone, Luck, and Rpin. There's a money exchange company in this planet. You must go to this company if you want to do some money exchange, and, more autocratically, this company regulate the exchange rate of each pair of these 3 kinds of money.

    The money exchange will be done in the following two ways:

    (A)

    You give the company a real number x in the range (0,100], the company will exchange x% of your Mone and x% of your Luck to equal Rpin according to the exchange rate of that day.

    (B)

    You give the company a real number x, the company will exchange your x Rpin to some Mone and Luck, whose value is equal to x Rpin according to the exchange rate of that day, and, the value of Mone is Rate times of the value of Luck.

    You can do many exchange operations in the same day.

    Now, as the excellant spy in this planet, you know the exchange rate between Mone and Rpin of each of the next n days(ai Mone per Rpin), and the exchange rate between Luck and Rpin of each of the next n days(bi Luck per Rpin), and, each Rate of the next n days( Ratei). you have S Rpin in the start, and you want to get most Rpin in the nth day later.

    Input

    Multiple test cases, the number of them( <=5 ) is given in the very first line.

    For each test case:

    The first line contains a integer number n(1<=n<=100000) and a real number S.n lines follow, each contains 3 real numbers: ai(between 0 and 10), bi(between 0 and 10), Ratei(between 0 and 100).

    Output

    For each test case, output one line contains a real number with 3 digits after decimal point, which denotes to the answer. You can assume it is less than 1000000000.

    Example

    Input:
    1
    3 100
    1 1 1
    1 2 2
    2 2 3
    
    Output:
    225.000
    
    Warning: large input/output data, be careful with certain languages; the time limit is somewhat strict for this problem
    Added by:[Trichromatic] XilinX
    Date:2007-08-05
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese National Olympiad in Informatics 2007,Day 1; Translated by Blue Mary









    SPOJ Problem Set (classical)

    1728. Common Permutation

    Problem code: CPRMT

    Given two strings of lowercase letters, a and b, print the longest string x of lowercase letters such that there is a permutation of x that is a subsequence of a and there is a permutation of x that is a subsequence of b.

    Input

    Input file contains several lines of input. Consecutive two lines make a set of input. That means in the input file line 1 and 2 is a set of input, line 3 and 4 is a set of input and so on. The first line of a pair contains a and the second contains b. Each string is on a separate line and consists of at most 1000 lowercase letters.

    Output

    For each set of input, output a line containing x. If several x satisfy the criteria above, choose the first one in alphabetical order.

    Example

    Sample input:
    pretty
    women
    walking
    down
    the
    street
     
    Sample output:
    e
    nw
    et 
    

    Added by:Andrés Leonardo Rojas Duarte
    Date:2007-08-05
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:University of Alberta Local Contest 1999









    SPOJ Problem Set ()

    1730. Counting Triangles II

    Problem code: TCOUNT2

    We define the LEVEL of a triangle as in the following illustrative image:


    And we continue defining the LEVEL of a hexagon. It's called level N hexagon if it’s joined by 6 triangles, each one is a level N triangle.


    Task: All you have to do is to count all triangles in the “level N” hexagon.

    Input

    The first line of the input contains an integer T - the number of test cases and T lines follow. Each line contains an integer N which is the level of the hexagon in that test case.

    Output

    For each test case, you should write a seperate line: the number of triangles in the “level N” hexagon. (All answers will fit within the range of a 64-bit positive integer)

    Example

    Input:
    1
    1
    
    Output:
    6
    
    Be careful with certain languages

    Added by:Unknown
    Date:2007-08-06
    Time limit:1s
    Source limit:300B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:ASM C C++ 4.0.0-8 C99 strict D PAS fpc PAS gpc
    Resource:Trần Huy Hưng









    SPOJ Problem Set (classical)

    1731. Counting Triangles III

    Problem code: TCOUNT3


    Have you felt bored when counting triangles?

    Like TRICOUNT and TCOUNT2, we define the LEVEL of a triangle as in the following illustrative image:


    And now we will continue defining the LEVEL of a hexagram. It's called level N hexagram if it’s joined by 12 triangles, each one is a level N triangle.


    Task: All you have to do is to count all triangles in the level N hexagram.

    Input

    The first line of the input contains an integer T - the number of test cases and T lines follow. Each line contains an integer N which is the level of the hexagram in that test case.

    Output

    For each test case, you should write a seperate line: the number of triangles in the level N hexagram. (All answers will fit within the range of a 64-bit positive integer)

    Example

    Input:
    1
    1
    
    Output:
    20
    
    The author allows only few languages

    Added by:Unknown
    Date:2007-08-07
    Time limit:1s
    Source limit:128B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:ASM C C++ 4.0.0-8 C99 strict D PAS fpc PAS gpc PERL PYTH 2.7 RUBY
    Resource:Trần Huy Hưng









    SPOJ Problem Set (classical)

    1739. Yet Another Equation

    Problem code: EQU2

    Consider the equation

    x2 - ny2 = 1

    where n is some integer.

    Find the smallest strictly positive integer solutions (x, y) for a given n.

    Input

    The number of test cases t (around 30), followed by a list of t values of n (2 ≤ n ≤ 1000). You can assume that the equation can be solved for all values of n in the input set.

    Output

    For every test case, the values of x and y separated by a space character, on separate lines.

    Example

    Input:
    3
    2
    6
    61
    
    Output:
    3 2
    5 2
    1766319049 226153980
    

    Added by:Mauro Persano
    Date:2007-08-18
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Brahmagupta, circa 628 AD









    SPOJ Problem Set (classical)

    1741. Tetris 3D

    Problem code: TETRIS3D

    The authors of the game "Tetris" have decided to make a new, three-dimensional version, in which cuboids would fall down on a rectangular platform. The blocks fall down separately in a certain order, just like in the two-dimensional game. A block falls down until it reaches an obstacle: the platform or another block, that has already stopped - then it stops and remains in this exact position till the game is over.
    However, the authors wanted to change the spirit of the game, turning it from a simple arcade-game into a play far more puzzling. Knowing the order of the falling blocks and their flight path the player's task is to tell the height of the highest point of the arrangement after all blocks have fallen down (and stopped). All the blocks are falling down vertically and do not rotate while falling. For convenience we'll introduce a cartesian coordinate system on the platform, with the center in one of the platform's corners and the axes parallel to the platform's edges.
    Write a program that:
    • reads the descriptions of subsequent falling blocks from the standard input,
    • determines the height of the highest point of the arrangement of blocks after all have fallen down and stopped,
    • writes the result to the standard output.

    Input

    In the first line of the input there are three integers D, S and N ( 1<=N<=20 000, 1<=D, S<=1 000), separated by single spaces and denoting respectively: the length and the depth of the platform and the number of blocks that are going to fall down on it. In the following N lines the descriptions of subsequent blocks are given, one in each line.
    Each description of a block consists of five integers: d, s, w, x and y (1<=d, 0<=x,d+x<=D, 1<=s,0<=y,s+y<=S, 1<=w<=100 000), representing a block of length d depth s and height w This very block will be falling down on the platform with its d×s face as the bottom, where the length and depth of the block are parallel to those of the platform. The coordinates of the vertices of the projection of the block on the platform are: (x, y), (x + d, y), (x, y + s) and (x + d, y + s).

    Output

    The first and only line of the standard output should contain exactly one integer, the height of the highest point of the arrangement of blocks after all have fallen down ad stopped.

    Example

    Input:
    7 5 4
    4 3 2 0 0
    3 3 1 3 0
    7 1 2 0 3
    2 3 3 2 2
    
    Output:
    6
    

    Added by:Bin Jin
    Date:2007-08-19
    Time limit:2s-4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:POI XIII - Stage I









    SPOJ Problem Set (classical)

    1744. Evaluate the polynomial

    Problem code: POLEVAL

    Your task consists of evaluate a polynomial of degree n (0 <= n <= 999) represented by its n+1 coefficients of the form:

    pn(x) = cnxn + cn-1xn-1 + … + c2x2 + c1x + c0

    in each one of the k (1 <= k <= 100) points x1, x2, …, xk. The coefficients of the polynomial and the values where they will be evaluated are integers in the interval [-100, 100] that guarantees that the polynomial's evaluation is at the most 263 – 1.

    Input

    There will be multiple test cases, each one with 4 lines that are described below
    n: degree of polynomial.
    cn cn-1 … c2 c1 c0: coefficients of the polynomial separated by a single space.
    k: number of points to evaluate the polynomial.
    x1 x2 xk-1 xk: points to evaluate the polynomial separated by a single space.

    The final test case is a single line where n = -1 and this case should not be processed.

    Output

    For each test case you should print k + 1 lines of output, the very first line containing the case number and the following k lines with the result of the polynomial's evaluation in each one of the k given points. See the sample.

    Example

    Input:
    2
    1 -2 -1
    5
    0 1 -1 2 -2
    3
    2 1 -2 -1
    4
    0 -1 2 -2
    -1
    Output: Case 1:
    -1
    -2
    2
    -1
    7
    Case 2:
    -1
    0
    15
    -9

    Added by:Ivan Alfonso Olamendy
    Date:2007-08-25
    Time limit:2.5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:My own resource









    SPOJ Problem Set (classical)

    1748. Sequence Partitioning II

    Problem code: SEQPAR2

    Given a sequence of N ordered pairs of positive integers (Ai, Bi), you have to partition it into several contiguous parts. Let p be the number of these parts, whose boundaries are (l1, r1), (l2, r2), ... ,(lp, rp), which satisfy li = ri-1 + 1, li <= ri, l1 = 1, rp = n. The parts themselves also satisfy the following restrictions:

    1. For any two pairs (Ap, Bp), (Aq, Bq), where (Ap, Bp) is belongs to the Tpth part and (Aq, Bq) the Tqth part. If Tp < Tq, then Bp > Aq.

    2. Let Mi be the maximum A-component of elements in the ith part, say

      Mi = max {Ali, Ali+1, ..., Ari}, 1 <= i <= p

      it is provided that


      where Limit is a given integer.

    Let Si be the sum of B-components of elements in the ith part.

    Now I want to minimize the value

    max{Si:1 <= i <= p}

    Could you tell me the minimum?

    Input

    The input contains exactly one test case. The first line of input contains two positive integers N (N <= 50000), Limit (Limit <= 231-1). Then follow N lines each contains a positive integers pair (A, B). It's always guaranteed that

    max{A1, A2, ..., An} <= Limit

    Output

    Output the minimum target value.

    Example

    Input:
    4 6
    4 3
    3 5
    2 5
    2 4
    
    Output:
    9
    
    

    Explanation

    An available assignment is the first two pairs are assigned into the first part and the last two pairs are assigned into the second part. Then B1 > A3, B1 > A4, B2 > A3, B2 > A4, max{A1, A2}+max{A3, A4} <= 6, and minimum max {B1+B2, B3+B4}=9.


    Added by:Bin Jin
    Date:2007-08-28
    Time limit:1s-15s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:POJ Monthly--2007.07.08









    SPOJ Problem Set (classical)

    1754. Divisor Summation (Hard)

    Problem code: DIVSUM2

    Given a natural number n (1 <= n <= 1e16), please output the summation of all its proper divisors.

    Definition: A proper divisor of a natural number is the divisor that is strictly less than the number.

    e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22.

    Input

    An integer stating the number of test cases (equal to 500), and that many lines follow, each containing one integer between 1 and 1e16 inclusive.

    Output

    One integer each line: the divisor summation of the integer given respectively.

    Example

    Input:
    3
    2
    10
    20
    
    Output:
    1
    8
    22
    
    warning: a naive algorithm may not run in time.
    Added by:Bin Jin
    Date:2007-08-29
    Time limit:60s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:own problem









    SPOJ Problem Set (classical)

    1771. Yet Another N-Queen Problem

    Problem code: NQUEEN

    After solving Solution to the n Queens Puzzle by constructing, LoadingTime wants to solve a harder version of the N-Queen Problem. Some queens have been set on particular locations on the board in this problem. Can you help him??

    Input

    The input contains multiple test cases. Every line begins with an integer N (N<=50), then N integers followed, representing the column number of the queen in each rows. If the number is 0, it means no queen has been set on this row. You can assume there is at least one solution.

    Output

    For each test case, print a line consists of N numbers separated by spaces, representing the column number of the queen in each row. If there are more than one answer, print any one of them.

    Example

    Input:
    4 0 0 0 0
    8 2 0 0 0 4 0 0 0
    
    Output:
    2 4 1 3
    2 6 1 7 4 8 3 5
    

    Added by:Bin Jin
    Date:2007-09-06
    Time limit:5s
    Source limit:10000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:own problem









    SPOJ Problem Set ()

    1772. Find The Determinant II

    Problem code: DETER2

    In this problem you have to calculate the determinant of an N x N matrix whose entries are given by m[i][j] = gcd(i,j)k, 1 ≤ i,j ≤ N.

    Here gcd(i,j) denotes the greatest common divisor of i and j.

    As the determinant D can grow very large, you have to print D%1000003.

    Input

    First line of input consists of a single integer containing the number of test cases T ( equal to around 20), each of the following T lines contain two integers N and k where N is the size of the matrix and k is the exponent.
    1 ≤ N ≤ 1000000
    1 ≤ k ≤ 109

    Output

    One line corresponding to each test case containing the determinant modulo 1000003 for the corresponding test case.

    Example

    Input:
    3
    4 2
    2 4
    4 3
    
    
    Output:
    288
    15
    10192
    
    Note: You may want to solve DETER first, in case you havent already solved it.
    Added by:Ajay Somani
    Date:2007-09-07
    Time limit:1s
    Source limit:2048B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:"The Art of Computer Programming"









    SPOJ Problem Set (classical)

    1774. All Discs Considered

    Problem code: ALL

    Operating systems are large software artefacts composed of many packages, usually distributed on several media, e.g., discs. You probably remember the time when your favourite operating system was delivered on 21 floppy discs, or, a few years later, on 6 CDs. Nowadays, it will be shipped on several DVDs, each containing tens of thousands of packages.

    The installation of certain packages may require that other packages have been installed previously. Therefore, if the packages are distributed on the media in an unsuitable way, the installation of the complete system requires you to perform many media changes, provided that there is only one reading device available, e.g., one DVD-ROM drive. Since you have to start the installation somehow, there will of course be one or more packages that can be installed independently of all other packages.

    Given a distribution of packages on media and a list of dependences between packages, you have to calculate the minimal number of media changes required to install all packages. For your convenience, you may assume that the operating system comes on exactly 2 DVDs.

    Input

    The input contains several test cases. Every test case starts with three integers N1, N2, D. You may assume that 1<=N1,N2<=50000 and 0<=D<=100000. The first DVD contains N1 packages, identified by the numbers 1, 2, ..., N1. The second DVD contains N2 packages, identified by the numbers N1+1, N1+2, ..., N1+N2. Then follow D dependence specifications, each consisting of two integers xi, yi. You may assume that 1<=xi,yi<=N1+N2 for 1<=i<=D. The dependence specification means that the installation of package xi requires the previous installation of package yi. You may assume that there are no circular dependences. The last test case is followed by three zeros.

    Output

    For each test case output on a line the minimal number of DVD changes required to install all packages. By convention, the DVD drive is empty before the installation and the initial insertion of a disc counts as one change. Likewise, the final removal of a disc counts as one change, leaving the DVD drive empty after the installation.

    Example

    Input:
    3 2 1
    1 2
    2 2 2
    1 3
    4 2
    2 1 1
    1 3
    0 0 0
    
    Output:
    3
    4
    3
    

    Added by:Wanderley Guimarães
    Date:2007-09-14
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2004









    SPOJ Problem Set (classical)

    1775. Boolean Logic

    Problem code: BOOLE


    Propositions are logical formulas consisting of proposition symbols and connecting operators. They are recursively defined by the following rules:

    1. All proposition symbols (in this problem, lower-case alphabetic characters, e.g., a and z) are propositions.
    2. If P is a proposition, (!P) is a proposition, and P is a direct subformula of it.
    3. If P and Q are propositions, (P&Q), (P|Q), (P-->Q), and (P<->Q) are propositions, and P and Q are direct subformulas of them.
    4. Nothing else is a proposition.
    The operations !, &, |, -->, and <-> denote logical negation, conjunction, disjunction, implication, and equivalence, respectively. A proposition P is a subformula of a proposition R if P=R or P is a direct subformula of a proposition Q and Q is a subformula of R.

    Let P be a proposition and assign boolean values (i.e., 0 or 1) to all proposition symbols that occur in P. This induces a boolean value to all subformulas of P according to the standard semantics of the logical operators:

    negation conjunction disjunction implication equivalence
    !0=1 0&0=0 0|0=0 0-->0=1 0<->0=1
    !1=0 0&1=0 0|1=1 0-->1=1 0<->1=0
    1&0=0 1|0=1 1-->0=0 1<->0=0
    1&1=1 1|1=1 1-->1=1 1<->1=1

    This way, a value for P can be calculated. This value depends on the choice of the assignment of boolean values to the proposition symbols. If P contains n different proposition symbols, there are 2n different assignments. To evaluate all possible assignments we may use truth tables.

    A truth table contains one line per assignment (i.e., 2n lines in total). Every line contains the values of all subformulas under the chosen assignment. The value of a subformula is aligned with the proposition symbol, if the subformula is a proposition symbol, and with the center of the operator otherwise.

    Input Specification

    The input contains several test cases, each on a separate line. Every test case denotes a proposition and may contain arbitrary amounts of spaces in between. The input file terminates immediately after the newline symbol following the last test case.

    Output Specification

    For each test case generate a truth table for the denoted proposition. Start the truth table by repeating the input line. Evaluate the proposition (and its subformulas) for all assignments to its variables, and output one line for each assignment. The line must have the same length as the corresponding input line and must consist only of spaces and the characters 0 and 1. Output an empty line after each test case.

    Let s1,...,sn be the proposition symbols in the denoted proposition sorted in alphabetic order. Then, all assignments of 0 to s1 must precede the assignments of 1 to s1. Within each of these blocks of assignments, all assignments of 0 to s2 must precede the assignments of 1 to s2, and so on.

    Sample Input

    ((b --> a) <-> ((! a) --> (! b)))
      ((y &  a)   -  ->(c |c))
    

    Sample Output

    ((b --> a) <-> ((! a) --> (! b)))
      0  1  0   1    1 0   1   1 0   
      1  0  0   1    1 0   0   0 1   
      0  1  1   1    0 1   1   1 0   
      1  1  1   1    0 1   1   0 1   
    
      ((y &  a)   -  ->(c |c))
        0 0  0       1  0 00  
        1 0  0       1  0 00  
        0 0  0       1  1 11  
        1 0  0       1  1 11  
        0 0  1       1  0 00  
        1 1  1       0  0 00  
        0 0  1       1  1 11  
        1 1  1       1  1 11  
    
    

    Added by:Wanderley Guimarães
    Date:2007-09-14
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2004









    SPOJ Problem Set (classical)

    1776. DNA Laboratory

    Problem code: DNALAB

    Having started to build his own DNA lab just recently, the evil doctor Frankenstein is not quite up to date yet. He wants to extract his DNA, enhance it somewhat and clone himself. He has already figured out how to extract DNA from some of his blood cells, but unfortunately reading off the DNA sequence means breaking the DNA into a number of short pieces and analyzing those first. Frankenstein has not quite understood how to put the pieces together to recover the original
    sequence.

    His pragmatic approach to the problem is to sneak into university and to kidnap a number of smart looking students. Not surprisingly, you are one of them, so you would better come up with a solution pretty fast.

    You are given a list of strings over the alphabet A (for adenine), C (cytosine), G (guanine), and T (thymine), and your task is to find the shortest string (which is typically not listed) that contains all given strings as substrings. If there are several such strings of shortest length, find the smallest in alphabetical/lexicographical order.

    Input
    The fist line contains the number of scenarios. For each scenario, the first line contains the number n of strings with 1<=n<=15. Then these strings with 1 <= length <= 100 follow, one on each line, and they consist of the letters ‘A’, ‘C’, ‘G’, and ‘T’ only.

    Output
    The output for every scenario begins with a line containing “Scenario #i:”, where i is the number of the scenario starting at 1. Then print a single line containing the shortest (and smallest) string as described above. Terminate the output for the scenario with a blank line.

    Sample Input
    1
    2
    TGCACA
    CAT

    Sample Output

    Scenario #1:
    TGCACAT


    Added by:Andrés Leonardo Rojas Duarte
    Date:2007-09-15
    Time limit:12s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:TUD Programming Contest 2004









    SPOJ Problem Set (classical)

    1784. IOICamp Sequence

    Problem code: ICAMPSEQ

    Let's say we have 4 N-elements sequences of real numbers: A[], B[], C[], D[] .
    Funtion F(i, j) is defined: F(i, j) = |Ai - Aj| + |Bi - Bj| + |Ci - Cj| + |Di - Dj| (1 ≤ i, j ≤ N).
    Your task is very easy: you have to find the maximum of F(i, j).

    Input

    The first line: N (N ≤ 100000).
    Following are N lines: the i-th line contains four real numbers Ai, Bi, Ci, Di. (-109 ≤ Ai, Bi, Ci, Di ≤ 109)

    Output

    Only one line is the maximum of F(i, j).
    (The result takes exactly 3 decimal places)

    Example

    Input:
    2
    1.0 1.0 2.0 0.5
    1.0 1.0 0.5 2.0
    
    
    Output:
    3.000
    
    

    Added by:Nghia Nguyen Hoang
    Date:2007-09-18
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:IOICamp and Ms. Thanh Vy Hua Le









    SPOJ Problem Set (classical)

    1785. Code

    Problem code: CODE

    KEY Inc., the leading company in security hardware, has developed a new kind of safe. To unlock it, you don't need a key but you are required to enter the correct n-digit code on a keypad (as if this were something new!). There are several models available, from toy safes for children (with a 2-digit code) to the military version (with a 6-digit code).

    The safe will open as soon as the last digit of the correct code is entered. There is no "enter" key. When you enter more than n digits, only the last n digits are significant. For example (in the 4-digit version), if the correct code is 4567, and you plan to enter the digit sequence 1234567890, the door will open as soon as you press the 7 key.

    The software to create this effect is rather simple. In the n-digit version the safe is always in one of 10n-1 internal states. The current state of the safe simply represents the last n-1 digits that have been entered. One of these states (in the example above, state 456) is marked as the unlocked state. If the safe is in the unlocked state and then the right key (in the example above, 7) is pressed, the door opens. Otherwise the safe shifts to the corresponding new state. For example, if the safe is in state 456 and then you press 8, the safe goes into state 568.

    A trivial strategy to open the safe is to enter all possible codes one after the other. In the worst case, however, this will require n * 10n keystrokes. By choosing a good digit sequence it is possible to open the safe in at most 10n + n - 1 keystrokes. All you have to do is to find a digit sequence that contains all n-digit sequences exactly once. KEY Inc. claims that for the military version (n=6) the fastest computers available today would need billions of years to find such a sequence - but apparently they don't know what some programmers are capable of...

    Input Specification

    The input contains several test cases. Every test case is specified by an integer n. You may assume that 1<=n<=6. The last test case is followed by a zero.

    Output Specification

    For each test case specified by n output a line containing a sequence of 10n + n - 1 digits that contains each n-digit sequence exactly once.

    Sample Input

    1
    2
    0
    

    Sample Output

    0123456789
    00102030405060708091121314151617181922324252627282933435363738394454647484955657585966768697787988990
    

    Added by:Wanderley Guimarães
    Date:2007-09-19
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2004









    SPOJ Problem Set (classical)

    1786. In Danger

    Problem code: DANGER

    Flavius Josephus and 40 fellow rebels were trapped by the Romans. His companions preferred suicide to surrender, so they decided to form a circle and to kill every third person and to proceed around the circle until no one was left. Josephus was not excited by the idea of killing himself, so he calculated the position to be the last man standing (and then he did not commit suicide since nobody could watch).

    We will consider a variant of this "game" where every second person leaves. And of course there will be more than 41 persons, for we now have computers. You have to calculate the safe position. Be careful because we might apply your program to calculate the winner of this contest!

    Input Specification

    The input contains several test cases. Each specifies a number n, denoting the number of persons participating in the game. To make things more difficult, it always has the format "xyez" with the following semantics: when n is written down in decimal notation, its first digit is x, its second digit is y, and then follow z zeros. Whereas 0<=x,y<=9, the number of zeros is 0<=z<=6. You may assume that n>0. The last test case is followed by the string 00e0.

    Output Specification

    For each test case generate a line containing the position of the person who survives. Assume that the participants have serial numbers from 1 to n and that the counting starts with person 1, i.e., the first person leaving is the one with number 2. For example, if there are 5 persons in the circle, counting proceeds as 2, 4, 1, 5 and person 3 is staying alive.

    Sample Input

    05e0
    01e1
    42e0
    66e6
    00e0
    

    Sample Output

    3
    5
    21
    64891137
    

    Added by:Wanderley Guimarães
    Date:2007-09-19
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2004









    SPOJ Problem Set (classical)

    1787. Run Length Encoding

    Problem code: ENCONDIN

    Your task is to write a program that performs a simple form of run-length encoding, as described by the rules below.

    Any sequence of between 2 to 9 identical characters is encoded by two characters. The first character is the length of the sequence, represented by one of the characters 2 through 9. The second character is the value of the repeated character. A sequence of more than 9 identical characters is dealt with by first encoding 9 characters, then the remaining ones.

    Any sequence of characters that does not contain consecutive repetitions of any characters is represented by a 1 character followed by the sequence of characters, terminated with another 1. If a 1 appears as part of the sequence, it is escaped with a 1, thus two 1 characters are output.

    Input Specification

    The input consists of letters (both upper- and lower-case), digits, spaces, and punctuation. Every line is terminated with a newline character and no other characters appear in the input.

    Output Specification

    Each line in the input is encoded separately as described above. The newline at the end of each line is not encoded, but is passed directly to the output.

    Sample Input

    AAAAAABCCCC
    12344
    

    Sample Output

    6A1B14C
    11123124
    

    Added by:Wanderley Guimarães
    Date:2007-09-19
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2004









    SPOJ Problem Set ()

    1788. Fractan

    Problem code: FRACTAN

    To play the "fraction game" corresponding to a given list f1, f2, ..., fk of fractions and starting integer N, you repeatedly multiply the integer you have at any stage (initially N) by the earliest fi in the list for which the answer is integral. Whenever there is no such fi, the game stops.

    Formally, we define a sequence by S0=N, and Sj+1=fiSj, if for 1<=i<=k, the number fiSj is an integer but the numbers f1Sj, ..., fi-1Sj are not.

    For example, if we have the list of eight fractions f1=170/39, f2=19/13, f3=13/17, f4=69/95, f5=19/23, f6=1/19, f7=13/7, f8=1/3, and start with N=21, we produce the (finite) sequence (21,39,170,130,190,138,114,6,2). In general, the sequence may be infinite.

    Given a fraction list and a starting integer calculate a part of the defined sequence. Actually, we are interested only in the powers of 2 that appear in the sequence.

    Input Specification

    The input contains several test cases. Every test case starts with three integers m, N, k. You may assume that 1<=m<=40, 1<=N<=1000, and 1<=k<=100. Then follow k fractions f1, ..., fk. For each fraction, first its numerator is given, followed by its denominator. You may assume that both are positive integers less than 1000 and their greatest common divisor is 1. The last test case is followed by a zero.

    Output Specification

    For each test case output on a line m numbers e1, ..., em, separated by one space character, such that 2e1, ..., 2ek are the first m numbers in the defined sequence that are powers of 2. You may assume that there are at least m powers of 2 among the first 7654321 elements of the sequence.

    Sample Input

    1 21 8 170 39 19 13 13 17 69 95 19 23 1 19 13 7 1 3
    20 2 14 17 91 78 85 19 51 23 38 29 33 77 29 95 23 77 19 1 17 11 13 13 11 15 2 1 7 55 1
    0
    

    Sample Output

    1
    1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67
    

    Added by:Wanderley Guimarães
    Date:2007-09-19
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:University of Ulm Local Contest 2004









    SPOJ Problem Set (classical)

    1789. Huffman´s Greed

    Problem code: GREEDULM

    In the following we define the basic terminology of trees. A tree is defined inductively: It has a root which is either an external node (a leaf), or an internal node having a sequence of trees as its children. An internal node is also called the parent of the roots of its child trees. The level of a node in a tree is defined inductively: The root has level 0, and the level of a node is 1 more than the level of its parent node.

    Every internal node of a binary tree has precisely two children, its left sub-tree and its right sub-tree. Every internal node of a labelled binary tree is additionally marked with a string, its label. A binary search tree is a labelled binary tree where every internal node t satisfies the following condition: All labels of nodes in the left sub-tree of t are less than the label of t which is, in turn, less than all labels of nodes in the right sub-tree of t. For this condition, we assume lexicographic, i.e., alphabetic order on the strings.

    An inorder traversal of a tree is defined recursively: A leaf is just visited, and for an internal node first its left sub-tree is traversed inorder, then the node itself is visited, finally its right sub-tree is traversed inorder. It follows that an inorder traversal of a binary search tree yields the labels in lexicographic order. Note that binary search trees whose shapes differ may nevertheless yield the same sequence of strings while being traversed inorder.

    When a given string s is looked for in a binary search tree, we compare s to the label l of the root. We are done if s=l, otherwise if s<l we continue to search in the left sub-tree, and if s>l in the right sub-tree. If a leaf is reached, we know that s is not in the tree.

    The number of comparisons performed in such a search procedure depends on s and the actual shape of the search tree. Therefore, there is an interest in constructing binary search trees that store a given sequence of strings but provide as efficient access as possible. Of course, we don't know in advance which strings will be looked up in the tree, so we need to make some assumptions.

    Let n be the number of strings that are to be stored in the binary search tree. Let K1,...,Kn be these strings in lexicographic order. Let p1,...,pn and q0,...,qn be 2n+1 non-negative real numbers such that i=1..n pi + ∑i=0..n qi = 1. The interpretation of these numbers is:

    • pi = probability that the search argument s is Ki.
    • qi = probability that s lies (lexicographically) strictly between Ki and Ki+1.

    By convention, q0 is the probability that s is less than K1, and qn is the probability that s is greater than Kn. We want to find a binary search tree containing nodes with labels K1,...,Kn that minimises the expected number of comparisons in the search, namely

    cost = ∑i=1..n pi*(1 + level of internal node Ki) + ∑i=0..n qi*(level of leaf between Ki and Ki+1).

    The leaf between Ki and Ki+1 is that leaf reached in the search for a string s that lies (lexicographically) strictly between Ki and Ki+1. Adhere to the convention stated above for the border cases.

    The following figure illustrates the first test case of the sample input. It shows the two possible binary search trees, the probabilities and the associated costs.

    Input Specification

    The input contains several test cases. Every test case starts with an integer n. You may assume that 1<=n<=200. Then follow 2n+1 non-negative integers denoting frequencies. Let s be the sum of all frequencies. You may assume that 1<=s<=1000000. The probabilities p1,...,pn and q0,...,qn are calculated in this order by dividing the frequencies by s. The last test case is followed by a zero.

    Output Specification

    For each test case devise a binary search tree whose cost is minimal for the specified probabilities. Output the integer cost*s for such a tree.

    Sample Input

    2
    20 15 15 25 25
    35
    142 35 58 5 20 5 10 9 15 23 129 4 52 5 38 18 9 7 2 4 266 93 5 18 18 27 5 10 11 180 4 32 21 3 21
    0 55 27 36 85 31 58 3 334 0 98 27 113 89 180 0 62 12 0 37 0 3 64 70 0 277 0 0 0 170 0 18 76 27 3 29
    0
    

    Sample Output

    160
    13637
    
    

    Added by:Wanderley Guimarães
    Date:2007-09-19
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2004









    SPOJ Problem Set ()

    1790. Binary Search Heap Construction

    Problem code: HEAPULM

    Read the statement of problem G for the definitions concerning trees. In the following we define the basic terminology of heaps. A heap is a tree whose internal nodes have each assigned a priority (a number) such that the priority of each internal node is less than the priority of its parent. As a consequence, the root has the greatest priority in the tree, which is one of the reasons why heaps can be used for the implementation of priority queues and for sorting.

    A binary tree in which each internal node has both a label and a priority, and which is both a binary search tree with respect to the labels and a heap with respect to the priorities, is called a treap. Your task is, given a set of label-priority-pairs, with unique labels and unique priorities, to construct a treap containing this data.

    Input Specification

    The input contains several test cases. Every test case starts with an integer n. You may assume that 1<=n<=50000. Then follow n pairs of strings and numbers l1/p1,...,ln/pn denoting the label and priority of each node. The strings are non-empty and composed of lower-case letters, and the numbers are non-negative integers. The last test case is followed by a zero.

    Output Specification

    For each test case output on a single line a treap that contains the specified nodes. A treap is printed as (<left sub-treap><label>/<priority><right sub-treap>). The sub-treaps are printed recursively, and omitted if leafs.

    Sample Input

    7 a/7 b/6 c/5 d/4 e/3 f/2 g/1
    7 a/1 b/2 c/3 d/4 e/5 f/6 g/7
    7 a/3 b/6 c/4 d/7 e/2 f/5 g/1
    0
    

    Sample Output

    (a/7(b/6(c/5(d/4(e/3(f/2(g/1)))))))
    (((((((a/1)b/2)c/3)d/4)e/5)f/6)g/7)
    (((a/3)b/6(c/4))d/7((e/2)f/5(g/1)))
    

    Added by:Wanderley Guimarães
    Date:2007-09-19
    Time limit:4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:University of Ulm Local Contest 2004









    SPOJ Problem Set (classical)

    1793. Text Generater II

    Problem code: GEN2


    HL, HJ and FGD set problem for ZMY everyday. The title of each problem bores them very much. The title is a string which consists only lower case letters. It's length is L, and, of course, the title must contain their names(hl, hj, fgd) as consecutive substrings.More apparently, N evil consecutive substrings should not appear in the title. Any string satisfying the two conditions above is OK.

    The task ZMY is to do today is: if they give ZMY 8 problems every week, and the title of each problem should not be repeated, how many (complete) weeks can they set problems?

    Input

    Multiple test cases.Input terminates by EOF.

    For each test case:

    The first line contains two space-seperated integers L(0<=L<=109) and N(0<=N<=20). N lines follow, each contains a string (contains only lowercase letters), which is evil.You can assume the total length of the N evil strings is no more than 20.

    Output

    For each test case output one line contains the answer modudo 1000.

    Example

    Input:
    10 1
    zmy
    
    Output:
    245
    

    Added by:[Trichromatic] XilinX
    Date:2007-09-20
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:description by Blue Mary; standard program and test data by g201513









    SPOJ Problem Set (classical)

    1794. Greedy Hydra II

    Problem code: DRAGON2

    The problem description is the same as the problem DRAGON.

    Input

    The first line contains 3 integers N(1<=N<=3000),M(2<=M<=N),K(1<=K<=N), separated by single spaces. The N fruits are numbered 1..N, and the biggest fruit is always numbered 1. N-1 lines follow, each contains 3 integers i,j,k separated by spaces denoted that there is a branch between fruit i(1<=i<=N) and fruit j(1<=j<=N) and the weight of illness of this branch is k(0<=k<=100000).

    Output

    Output one line contains a single integer denoted the minimum weight of illness of the hydra. If we can't divide the fruit into M groups, output "-1"(without quotes).

    Example

    Input:
    8 2 4
    1 2 20
    1 3 4 
    1 4 13
    2 5 10
    2 6 12
    3 7 15
    3 8 5
    
    Output:
    4
    

    Blue Mary's Note: some new test cases were added on Dec.7, 2007.


    Added by:[Trichromatic] XilinX
    Date:2007-09-20
    Time limit:0.5s-1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:description by Blue Mary; standard program and test data by lcosvse









    SPOJ Problem Set (classical)

    1797. Cardsharper

    Problem code: CARD

    Zenek is a well known (at least in Byteotia) card-sharper. He spent most of his best years practicing one card shuffle with his deck of n cards, which for simplicity we will call 1,2,...,n. Unfortunately, it turns out that knowing this one card shuffle a is not enough to earn a good living. To become rich and famous Zenek needs to know k shuffles c1,...,ck. As he doesn't have enough time to learn all of them, he decided to learn only one shuffle b so that using both a and b he will be able to perform as many of ci as it is possible.

    Each shuffle is described by n numbers t1,t2,...,tn. Such description means that after performing shuffle, card that was originally at position i will be at position ti.

    Task

    Find shuffle b maximizing number of shuffles that can be performed.

    Input

    First line contains n (2≤n≤52). Second line contains n numbers a1,a2,...,an describing shuffle that Zenek already knows.Third line contains k (2≤k≤6). i-th of the next k lines contains description of ci.

    Output

    First line contains description of the shuffle b that Zenek shoud learn. i-th of the next k lines contains:

    • -1 when it is not possible to perform ci using only a and b
    • m,r1,r2,...,rm (0≤m≤500000, 0≤ri≤106) meaning that applying a r1 times, then b r2 times, then a r3 times and so on is the same as applying shuffle ci once.

    Examples

    Input
    5
    2 3 4 5 1
    3
    1 3 2 4 5
    1 2 3 4 5
    5 4 3 2 1
    
    Output
    2 1 3 4 5
    3 4 1 1
    0
    9 1 1 3 1 4 1 1 1 1
    
    Input
    5
    1 2 3 4 5
    3
    1 3 2 4 5
    5 4 3 2 1
    1 2 5 4 3
    
    Output
    1 3 2 4 5
    2 0 1
    -1
    -1
    

    Added by:Pawel Gawrychowski
    Date:2007-09-20
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Fajne Zawody Informatyczne









    SPOJ Problem Set (classical)

    1798. Assistance Required

    Problem code: ASSIST


    After the 1997/1998 Southwestern European Regional Contest (which was held in Ulm) a large contest party took place. The organization team invented a special mode of choosing those participants that were to assist with washing the dirty dishes. The contestants would line up in a queue, one behind the other. Each contestant got a number starting with 2 for the first one, 3 for the second one, 4 for the third one, and so on, consecutively.

    The first contestant in the queue was asked for his number (which was 2). He was freed from the washing up and could party on, but every second contestant behind him had to go to the kitchen (those with numbers 4, 6, 8, etc). Then the next contestant in the remaining queue had to tell his number. He answered 3 and was freed from assisting, but every third contestant behind him was to help (those with numbers 9, 15, 21, etc). The next in the remaining queue had number 5 and was free, but every fifth contestant behind him was selected (those with numbers 19, 35, 49, etc). The next had number 7 and was free, but every seventh behind him had to assist, and so on.

    Let us call the number of a contestant who does not need to assist with washing up a lucky number. Continuing the selection scheme, the lucky numbers are the ordered sequence 2, 3, 5, 7, 11, 13, 17, etc. Find out the lucky numbers to be prepared for the next contest party.

    Input Specification

    The input contains several test cases. Each test case consists of an integer n. You may assume that 1<=n<=3000. A zero follows the input for the last test case.

    Output Specification

    For each test case specified by n output on a single line the n-th lucky number.

    Sample Input

    1
    2
    10
    20
    0
    

    Sample Output

    2
    3
    29
    83
    

    Added by:Wanderley Guimarães
    Date:2007-09-21
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2003









    SPOJ Problem Set (classical)

    1799. The Bottom of a Graph

    Problem code: BOTTOM

    We will use the following (standard) definitions from graph theory. Let V be a nonempty and finite set, its elements being called vertices (or nodes). Let E be a subset of the Cartesian product V×V, its elements being called edges. Then G=(V,E) is called a directed graph.

    Let n be a positive integer, and let p=(e1,...,en) be a sequence of length n of edges ei∈ E such that ei=(vi,vi+1) for a sequence of vertices (v1,...,vn+1). Then p is called a path from vertex v1 to vertex vn+1 in G and we say that vn+1 is reachable from v1, writing (v1→vn+1).

    Here are some new definitions. A node v in a graph G=(V,E) is called a sink, if for every node w in G that is reachable from v, v is also reachable from w. The bottom of a graph is the subset of all nodes that are sinks, i.e., bottom(G)={v∈V|∀w∈V:(v→w)⇒(w→v)}. You have to calculate the bottom of certain graphs.

    Input Specification

    The input contains several test cases, each of which corresponds to a directed graph G. Each test case starts with an integer number v, denoting the number of vertices of G=(V,E), where the vertices will be identified by the integer numbers in the set V={1,...,v}. You may assume that 1<=v<=5000. That is followed by a non-negative integer e and, thereafter, e pairs of vertex identifiers v1,w1,...,ve,we with the meaning that (vi,wi)∈E. There are no edges other than specified by these pairs. The last test case is followed by a zero.

    Output Specification

    For each test case output the bottom of the specified graph on a single line. To this end, print the numbers of all nodes that are sinks in sorted order separated by a single space character. If the bottom is empty, print an empty line.

    Sample Input

    3 3
    1 3 2 3 3 1
    2 1
    1 2
    0
    

    Sample Output

    1 3
    2
    

    Added by:Wanderley Guimarães
    Date:2007-09-21
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2003









    SPOJ Problem Set (classical)

    1800. Fixed Partition Contest Management

    Problem code: CONTEST

    A technique used in early programming contest strategies involved partitioning the available intellectual capacity of a team into a number of members with each member having a fixed amount of intelligence, different members potentially having different amounts. The sum of the brightness of all members equals the total intellectual capacity of the team.

    Given a set of problems, it was the task of the team to assign the problems to different team members, so that they could be solved concurrently. This was made difficult due to the fact that the solution time of a problem might depend on the amount of intelligence available to it. Every problem has a minimum intelligence requirement, but if assigned to a brighter member its solution time might increase or decrease.

    In this task, you have to determine optimal assignments of problems to team members. Your program is given the intellectual capacities of the team members available for the solution of problems, and for each problem a description of how its solution time depends on the amount of intelligence available to it. Your program has to find the solution schedule of the problems that minimizes the average solution time for the problems. A solution schedule is an assignment of problems to team members and times, such that no two problems use the same member at the same time, and no problem is assigned to a team member with less brightness than its minimum requirement. The solution time of the problem is the difference between the time when the problem was submitted to be solved (which is the start of the contest at time zero for all problems in this task), and the time that the problem is solved.

    Input Specification

    The input data will contain multiple test cases. Each test case begins with a line containing a pair of integers m and n. The number m specifies the number of team members (1 <= m <= 3), and n specifies the number of problems to be solved (1 <= n <= 10).

    The next line contains m positive integers giving the intelligence amounts of the m team members. Following this are n lines, describing the time-brightness tradeoffs for each of the n problems. Each line starts with a positive integer k (k <= 10), followed by k pairs of positive integers s1,t1,s2,t2,...,sk,tk that satisfy si < si+1 for 1 <= i < k. The minimum intelligence requirement of the problem is s1, i.e. it cannot be solved by a member with less intellectual capacity than this number. If the problem is solved by a team member with brightness s, where si <= s < si+1 for some i, then its solution time will be ti. Finally, if the problem is solved by a team member with intellectual capacity sk or more, then its execution time will be tk.

    A pair of zeroes will follow the input for the last test case.

    You may assume that each problem will be solved in exactly the time specified for the given brightness, regardless of the number of other problems being solved by other team members at the same time. No problem will have an intelligence requirement larger than that of the brightest team member.

    Output Specification

    For each test case, first display the case number (starting with 1 and increasing sequentially). Then print the minimum average solution time for the set of problems with two digits to the right of the decimal point. Follow this by the description of a solution schedule that achieves this average solution time. Display one line for each problem, in the order they were given in the input, that identifies the problem number, the member used to solve it (numbered in the order given in the input), the time when the member started to solve the problem, and the time when the problem was solved. Follow the format shown in the sample output, and print a blank line after each test case.

    Sample Input

    2 4
    40 60
    1 35 4
    1 20 3
    1 40 10
    1 60 7
    3 5
    10 20 30
    2 10 50 12 30
    2 10 100 20 25
    1 25 19
    1 19 41
    2 10 18 30 42
    0 0
    

    Sample Output

    Case 1
    Average solution time = 7.75
    Problem 1 is solved by member 2 from 0 to 4
    Problem 2 is solved by member 1 from 0 to 3
    Problem 3 is solved by member 1 from 3 to 13
    Problem 4 is solved by member 2 from 4 to 11
    
    Case 2
    Average solution time = 35.40
    Problem 1 is solved by member 3 from 19 to 49
    Problem 2 is solved by member 2 from 0 to 25
    Problem 3 is solved by member 3 from 0 to 19
    Problem 4 is solved by member 2 from 25 to 66
    Problem 5 is solved by member 1 from 0 to 18
    
    

    Added by:Wanderley Guimarães
    Date:2007-09-21
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2003









    SPOJ Problem Set (classical)

    1801. Drink, on Ice

    Problem code: DRINK

    A good drink is always served on ice. That said, the amount of ice is what makes the difference. If it is too much, the drink will be well cooled, however, this is a bit of fraud as there could be less ice (and more Vodka for example). On the other hand, if there is too little ice the drink is warm which is unacceptable. You are to help the bartender, of course neither with mixing nor drinking, but with calculating the expected outcome of such mixtures.

    To make things easier, we assume that pure water is mixed with ice in a closed system, i.e., there is no problem with the outside temperature or the warming of the bottle, etc. Therefore, after a some time has passed, the system may be regarded as balanced (there is no further change in temperature and no more melting or freezing). Your job is to calculate the final temperature of this balanced system and the amount of ice and water in this equilibrium state.

    As you know from physics, it takes 4.19 Joule to heat one gram of water one Kelvin, whereas it takes 2.09 Joule if it is ice. We define the capacities cw = 4.19 J/(g*K) and ci = 2.09 J/(g*K). Melting one gram of ice takes 335 Joule, where the temperature remains constant at zero. We define the constant em = 335 J/g. The total thermal energy of the ice and the water before the experiment is equal to the thermal energy of the final mixture.

    The figure below shows the energy of one gram of ice, ice-water-mixture, or water, where the temperature is measured relative to -30 degrees Celsius. The jump at 0 degrees represents the melting of ice to water. The amount of energy gained is proportional to the amount of ice already melted.

    Input Specification

    The input contains several test cases. Each test case consists of four real numbers mw, mi, tw, ti. The mass of water mw and the mass of ice mi are both non-negative, given in grams, and mw + mi > 0. The water temperature tw and the ice temperature ti follow, both given in degrees Celsius, and you may assume that -30 < ti <= 0 <= tw < 100. The last test case is followed by four zeroes.

    Output Specification

    For each test case output the amount of ice and water in grams and the final temperature of the mixture in degrees Celsius. All numbers must be rounded to one digit. Adhere to the sample output for the exact format to use.

    Sample Input

    100 20 50 -10
    100 22 0  0
    100 35 25 -10.5
    10  90 25 -28
    0 0 0 0
    

    Sample Output

    0.0 g of ice and 120.0 g of water at 27.5 C
    22.0 g of ice and 100.0 g of water at 0.0 C
    6.0 g of ice and 129.0 g of water at 0.0 C
    100.0 g of ice and 0.0 g of water at -4.2 C
    


    Added by:Wanderley Guimarães
    Date:2007-09-21
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2003









    SPOJ Problem Set (classical)

    1802. Edge

    Problem code: EDGE

    For products that are wrapped in small packings it is necessary that the sheet of paper containing the directions for use is folded until its size becomes small enough. We assume that a sheet of paper is rectangular and only folded along lines parallel to its initially shorter edge. The act of folding along such a line, however, can be performed in two directions: either the surface on the top of the sheet is brought together, or the surface on its bottom. In both cases the two parts of the rectangle that are separated by the folding line are laid together neatly and we ignore any differences in thickness of the resulting folded sheet.

    After several such folding steps have been performed we may unfold the sheet again and take a look at its longer edge holding the sheet so that it appears as a one-dimensional curve, actually a concatenation of line segments. If we move along this curve in a fixed direction we can classify every place where the sheet was folded as either type A meaning a clockwise turn or type V meaning a counter-clockwise turn. Given such a sequence of classifications, produce a drawing of the longer edge of the sheet assuming 90 degree turns at equidistant places.

    Input Specification

    The input contains several test cases, each on a separate line. Each line contains a nonempty string of characters A and V describing the longer edge of the sheet. You may assume that the length of the string is less than 200. The input file terminates immediately after the last test case.

    Output Specification

    For each test case generate a PostScript drawing of the edge with commands placed on separate lines. Start every drawing at the coordinates (300,420) with the command "300 420 moveto". The first turn occurs at (310,420) using the command "310 420 lineto". Continue with clockwise or counter-clockwise turns according to the input string, using a sequence of "x y lineto" commands with the appropriate coordinates. The turning points are separated at a distance of 10 units. Do not forget the end point of the edge and finish each test case by the commands stroke and showpage.

    You may display such drawings with the gv PostScript interpreter, optionally after a conversion using the ps2ps utility.

    Sample Input

    V
    AVV
    

    Sample Output

    300 420 moveto
    310 420 lineto
    310 430 lineto
    stroke
    showpage
    300 420 moveto
    310 420 lineto
    310 410 lineto
    320 410 lineto
    320 420 lineto
    stroke
    showpage
    


    Added by:Wanderley Guimarães
    Date:2007-09-21
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2003









    SPOJ Problem Set (classical)

    1803. Fold

    Problem code: FOLD


    Read the statement of problem E: Edge to understand how to fold a sheet of paper and how to interpret the input. We define a "stripe" to be a maximally large part of the sheet that has no folding line going through. Since the turns occur at equidistant places, all stripes are congruent.

    In this problem you are given the description of the result of performing several folding steps as in problem E: Edge, i.e., in the unfolded state. Additionally, you know that the length of the sheet in its folded state is exactly the length of 1 stripe (again, we ignore thickness).

    Find the minimum number of folding steps necessary to generate the described sheet from an initially flat sheet of paper. Note that performing a folding step may create more than one turn in the result because parts of the sheet already overlay due to previous folding steps. When a step is carried out, however, all overlaying parts of the sheet are affected, i.e., it is not allowed to fold, say, only the top three layers.

    Finally, note that every result can be obtained by iterating through the turns in a fixed direction and performing a folding step at each turn, thereby accumulating a 1 stripe long stack of all stripes. If n is the number of turns in the input description, this procedure in fact requires n folding steps, which is not necessarily minimal as can be observed in the sample output.

    Input Specification

    The input contains several test cases, each on a separate line. Each line contains a nonempty string of characters A and V describing the longer edge of the sheet. You may assume that the length of the string is less than 200. The input file terminates immediately after the last test case.

    Output Specification

    For each test case print on a line the minimum number of folding steps required to produce the described sheet of paper.

    Sample Input

    V
    AVV
    AAVAAVVVAAV
    

    Sample Output

    1
    2
    4
    

    Added by:Wanderley Guimarães
    Date:2007-09-21
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2003









    SPOJ Problem Set ()

    1804. Genetic Code

    Problem code: GENETIC


    The connections between mathematics and biology are complicated. Most of the time they do not run along nice-looking links that merrily join at first glance, but they are abstract and not always easily established.

    Lake Vostok - about 14000 square kilometers large, up to 650 meters deep, and covered by 3743 meters of ice - was recently discovered on the Antarctic continent. The lake remained under conditions of high pressure and no sunlight for several millions of years. It is believed that ordinary life has evolved to a more efficient form using a genetic code composed of only three bases (the current state of ignorance proclaims the four bases adenine, cytosine, guanine, and thymine). Until reasonable names are found, the three bases will be abbreviated as N, O, and P.

    Moreover, the genome is single-stranded and directed, i.e., we may see it as a sequence over the alphabet {N,O,P}. Unless risking instability, it is necessary that the genome is a Thue-sequence, due to the Norwegian mathematician A. Thue (1863-1922). Define a subsegment of a sequence to be a connected subsequence, and call two subsegments adjacent if one follows immediately after the other in the sequence. A Thue-sequence is a sequence where no adjacent subsegments are equal. For example, NOPNO is and NOPNPNO is not a Thue-sequence, so that the first may be a genome whereas the second may not.

    To be able to simulate experiments with the new genomes, you are asked to generate genomes of certain lengths.

    Input Specification

    The input contains several test cases. Each test case consists of an integer n. You may assume that 1<=n<=5000. The last test case is followed by a zero.

    Output Specification

    For each test case specified by n output on a single line any genome of length n. If no genome of length n exists, output a blank line instead.

    Sample Input

    1
    2
    10
    20
    0
    

    Sample Output

    N
    NO
    NONPNOPNPO
    NONPNOPNPONOPNONPNOP
    

    Added by:Wanderley Guimarães
    Date:2007-09-21
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:University of Ulm Local Contest 2003









    SPOJ Problem Set (classical)

    1805. Largest Rectangle in a Histogram

    Problem code: HISTOGRA

    A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles:

    Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.

    Input Specification

    The input contains several test cases. Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of. You may assume that 1<=n<=100000. Then follow n integers h1,...,hn, where 0<=hi<=1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. A zero follows the input for the last test case.

    Output Specification

    For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.

    Sample Input

    7 2 1 4 5 1 3 3
    4 1000 1000 1000 1000
    0
    

    Sample Output

    8
    4000
    

    Added by:Wanderley Guimarães
    Date:2007-09-21
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:University of Ulm Local Contest 2003









    SPOJ Problem Set (classical)

    1810. Nuclear Plants

    Problem code: ORZ

    The Great Plain of Algorithmia plays an extremely important role in the agriculture of the Bandulu Kingdom: this is the only place where barley (Hordeum vulgare), an essential ingredient of beer, can be produced. Unfortunately, it is not possible to grow barley on the full area of the plain, as several nuclear plants have recently been built, and you cannot grow barley near a nuclear plant (since you do not want to produce giant-size, aggressive, man-eating barley-mutants). Your task is to write a program that determines the size of the area that can be used for growing barley.

    The Great Plain of Algorithmia is an n * m km2 rectangle, the coordinates of the four corners being (0, 0),(0, m),(n, 0) and (n, m). There are two types of nuclear plants: small and large. You are not allowed to grow barley within 0.58km of a small nuclear plant or within 1.31km of a large nuclear plant.

    Input

    The input contains several blocks of test cases. Each block begins with a line containing four integers: 1 <= n, m <= 10000 describe the size of the plain, ks <= 100 is the number of small nuclear plants, and kl <= 100 is the number of large nuclear plants. The next ks lines describe the coordinates of the small nuclear plants, each line contains two integers 0 <= x <= n and 0 <= y <= m . The next kl lines describe the large nuclear plants in a similar fashion.

    The input is terminated by a block with n = m = ks = kl = 0 .

    Output

    For each test case, you have to output a single line containing the area that can be used for growing barley. This number should be a real value with two digits of precision. To avoid rounding problems, we accept solutions with a maximum of 0.01(positive or negative) error.

    Example

    Input:
    10 10 2 2
    2 2
    4 4
    5 6
    1 8
    10 10 1 0
    5 5
    0 0 0 0
    
    Output:
    87.46
    98.94
    
    Time limit has been changed from 2 seconds to 5 seconds.
    Added by:[Trichromatic] XilinX
    Date:2007-09-23
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set (classical)

    1811. Longest Common Substring

    Problem code: LCS

    A string is finite sequence of characters over a non-empty finite set Σ.

    In this problem, Σ is the set of lowercase letters.

    Substring, also called factor, is a consecutive sequence of characters occurrences at least once in a string.

    Now your task is simple, for two given strings, find the length of the longest common substring of them.

    Here common substring means a substring of two or more strings.

    Input

    The input contains exactly two lines, each line consists of no more than 250000 lowercase letters, representing a string.

    Output

    The length of the longest common substring. If such string doesn't exist, print "0" instead.

    Example

    Input:
    alsdfkjfjkdsal
    fdjskalajfkdsla
    
    Output:
    3
    

    Notice: new testcases added


    Added by:Bin Jin
    Date:2007-09-24
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8









    SPOJ Problem Set (classical)

    1812. Longest Common Substring II

    Problem code: LCS2

    A string is finite sequence of characters over a non-empty finite set Σ.

    In this problem, Σ is the set of lowercase letters.

    Substring, also called factor, is a consecutive sequence of characters occurrences at least once in a string.

    Now your task is a bit harder, for some given strings, find the length of the longest common substring of them.

    Here common substring means a substring of two or more strings.

    Input

    The input contains at most 10 lines, each line consists of no more than 100000 lowercase letters, representing a string.

    Output

    The length of the longest common substring. If such string doesn't exist, print "0" instead.

    Example

    Input:
    alsdfkjfjkdsal
    fdjskalajfkdsla
    aaaajfaaaa
    
    Output:
    2
    

    Notice: new testcases added


    Added by:Bin Jin
    Date:2007-09-24
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8









    SPOJ Problem Set (classical)

    1815. Problems Collection (Volume X)

    Problem code: WA

    These ten problems come from Chinese National Olympiad in Mathematics - Province Contest.

    Problem 1 Polynomial P(x)=x5+a1x4+a2x3+a3x2+a4x+a5, and we know when k=1, 2, 3, 4, P(k)=2007*k. Calculate P(10)-P(-5).

    Problem 2 The sum of 100 positive integers a1, a2, ..., a100 is 2007. Calculate the maximum possible value of .

    Problem 3 Calculate 100101102103104......498499500 modulo 126.

    Problem 4 We define the sum of the first n numbers of geometric progression {an} Sn. Now we know S7=7, S14=2014. Calculate S7*(S21-S14).

    Problem 5 Calculate the sum of this kind of positive integers n(n>=4): n satisfies that n! can be written as the product of n-3 consecutive positive integers.

    Problem 6 Two vertices of a square are on the line y=2x-17, while the other two are on the parabola y=x2. Calculate the sum of two different possible values of the area of this square.

    Problem 7 A, B, C, D are four fixed points in the space and they are not on the same plane. Calculate the number of different parallelepipeds, which satisfies that 4 vertices of the parallelepiped are A, B, C and D.

    Problem 8 Polynomial x2-x-1 exactly divides Polynomial a1x17+a2x16+1. Calculate a1*a2.

    Problem 9 Suppose x is an acute angle, calculate the minimum possible value of (sin x +cos x)/(sin x +tan x) + (tan x +cot x)/(cos x +tan x) + (sin x +cos x)/(cos x +cot x) + (tan x +cot x)/(sin x +cot x).

    Problem 10 Suppose x4+y4+z4=m/n, x, y, z are all real numbers, satisfying x*y+y*z+z*x=1 and 5*(x+1/x)=12*(y+1/y)=13*(z+1/z); m, n are positive integers and their greatest common divisor is 1. Calculate m+n.

    Input

    There is no input.

    Output

    Ten lines, each contains a single integer denoted the answer to the correspoding problem.

    Example

    There is no example.

    Links

    If there is any problem, please contact me.


    Added by:[Trichromatic] XilinX
    Date:2007-09-27
    Time limit:1s
    Source limit:60B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:TEXT
    Resource:CMOP :)









    SPOJ Problem Set (classical)

    1825. Free tour II

    Problem code: FTOUR2

    After the success of 2nd anniversary (take a look at problem FTOUR for more details), this 3rd year, Travel Agent SPOJ goes on with another discount tour.

    The tour will be held on ICPC island, a miraculous one on the Pacific Ocean. We list N places (indexed from 1 to N) where the visitors can have a trip. Each road connecting them has an interest value, and this value can be negative (if there is nothing interesting to view there). Simply, these N places along with the roads connecting them form a tree structure. We will choose two places as the departure and destination of the tour.

    Since September is the festival season of local inhabitants, some places are extremely crowded (we call them crowded places). Therefore, the organizer of the excursion hopes the tour will visit at most K crowded places (too tiring to visit many of them) and of course, the total number of interesting value should be maximum.

    Briefly, you are given a map of N places, an integer K, and M id numbers of crowded place. Please help us to find the optimal tour. Note that we can visit each place only once (or our customers easily feel bored), also the departure and destination places don't need to be different.

    Input

    There is exactly one case. First one line, containing 3 integers N K M, with 1 <= N <= 200000, 0 <= K <= M, 0 <= M <= N.

    Next M lines, each line includes an id number of a crowded place.

    The last (N - 1) lines describe (N - 1) two-way roads connected N places, form a b i, with a, b is the id of 2 places, and i is its interest value (-10000 <= i <= 10000).

    Output

    Only one number, the maximum total interest value we can obtain.

    Example

    Input:
    8 2 3
    3
    5
    7
    1 3 1
    2 3 10
    3 4 -2
    4 5 -1
    5 7 6
    5 6 5
    4 8 3
    
    
    Output:
    12
    

    Explanation

    We choose 2 and 6 as the departure and destination place, so the tour will be 2 -> 3 -> 4 -> 5 -> 6, total interest value = 10 + (-2) + (-1) + 5 = 12

    * Added some unofficial cases

    Added by:Thanh-Vy Hua
    Date:2007-09-28
    Time limit:1s-5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Adapted from Preslav Le's problem, first used in Bulgarian OI 07









    SPOJ Problem Set (classical)

    1833. Sudoku

    Problem code: SUDOKU2


    Oh no! Bill just realized that the sudoku puzzle he had spent the last ten minutes trying to solve essentially was last week's puzzle, only rotated counterclockwise. How cheap! Couldn't the magazine afford to make a new one every week? Of course, he had no way of knowing about this before he started to solve it, as the holes to fill with digits were other than last week. Nevertheless, realizing that this week's puzzle was a simple derivative of last week's certainly took the fun out of solving the rest of it.

    The sudoku board consists of 9×9 cells. These can be grouped into 3×3 regions of 3×3 cells each. Some of the cells are filled with a digit 1 through 9 while the rest of them are left empty. The aim of the game is to fill each empty cell with a digit 1...9 so that every row, every column and every region contains each of the numbers 1...9 exactly once. A proper sudoku puzzle always has exactly one solution.

    Help Bill avoid unpleasant surprises by creating a program that checks whether an unsolved sudoku puzzle is in fact derived from an earlier puzzle by simple operations.

    The allowed operations are:

    • Rotating the entire puzzle clockwise or counterclockwise.
    • Swapping two columns within a 3×9 column segment.
    • Swapping two rows within a 9×3 row segment.
    • Swapping entire row or column segments.
    • Applying a permutation f of the digits 1...9 to every cell (i.e. replace x by f(x) in every cell).

    An operation is considered being performed on the sudoku solution (rather than on the unsolved puzzle) and always guarantees that if the board before the transformation was a solution to a sudoku puzzle, it still is afterwards.

    Input

    The input starts with the number of test cases 0 ≤ N ≤ 50 on a single line.

    Then for every test case follow nine lines describing last week's puzzle solution, from top to bottom. Each line corresponds to a row in the puzzle and consists of nine digits (1...9), describing the contents of the cell from left to right.

    Last week's solution is followed by nine lines describing this week's unsolved puzzle. Here, also, every line corresponds to a puzzle row and every digit (0...9) describes the contents of a cell. 0 indicates that the cell is empty. The rows are presented ordered from top to bottom, and within each row, the cells are ordered from left to right.

    After every test case except the last one follows a blank line. Every unsolved puzzle is guaranteed to be uniquely solvable and last week's solution is always a proper sudoku solution. /p>

    Output

    For every test case, output Yes if the sudoku puzzle can be derived from the given solved puzzle using the allowed operations, or No if this is not possible.

    Example

    Input:
    2
    963174258
    178325649
    254689731
    821437596
    496852317
    735961824
    589713462
    317246985
    642598173
    060104050
    200000001
    008305600
    800407006
    006000300
    700901004
    500000002
    040508070
    007206900
    
    534678912
    672195348
    198342567
    859761423
    426853791
    713924856
    961537284
    287419635
    345286179
    010900605
    025060070
    870000902
    702050043
    000204000
    490010508
    107000056
    040080210
    208001090
    
    Output:
    Yes
    No
    

    Added by:Robin Nittka
    Date:2007-10-02
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC NWERC 2006









    SPOJ Problem Set ()

    1835. The SetStack Computer

    Problem code: SETSTACK


    Background from Wikipedia: Set theory is a branch of mathematics created principally by the German mathematician Georg Cantor at the end of the 19th century. Initially controversial, set theory has come to play the role of a foundational theory in modern mathematics, in the sense of a theory invoked to justify assumptions made in mathematics concerning the existence of mathematical objects (such as numbers or functions) and their properties. Formal versions of set theory also have a foundational role to play as specifying a theoretical ideal of mathematical rigor in proofs.

    Given this importance of sets, being the basis of mathematics, a set of eccentric theorist set off to construct a supercomputer operating on sets instead of numbers. The initial SetStack Alpha is under construction, and they need you to simulate it in order to verify the operation of the prototype.

    The computer operates on a single stack of sets, which is initially empty. After each operation, the cardinality of the topmost set on the stack is output. The cardinality of a set S is denoted |S| and is the number of elements in S. The instruction set of the SetStack Alpha is PUSH, DUP, UNION, INTERSECT, and ADD}.

    • PUSH will push the empty set {} on the stack.
    • DUP will duplicate the topmost set (pop the stack, and then push that set on the stack twice).
    • UNION will pop the stack twice and then push the union of the two sets on the stack.
    • INTERSECT will pop the stack twice and then push the intersection of the two sets on the stack.
    • ADD will pop the stack twice, add the first set to the second one, and then push the resulting set on the stack.

    For illustration purposes, assume that the topmost element of the stack is

    A = { {}, {{}} },

    and that the next one is

    B = { {}, {{{}}} }.

    For these sets, we have |A| = 2 and |B| = 2. Then:

    • UNION would result in the set { {}, {{}}, {{{}}} }. The output is 3.
    • INTERSECT would result in the set { {} }. The output is 1.
    • ADD would result in the set { {}, {{{}}}, {{},{{}}} }. The output is 3.

    Input

    An integer 0 ≤ T ≤ 5 on the first line gives the cardinality of the set of test cases. The first line of each test case contains the number of operations 0 ≤ N ≤ 2000. Then follow N lines each containing one of the five commands. It is guaranteed that the SetStack computer can execute all the commands in the sequence without ever popping an empty stack.

    Output

    For each operation specified in the input, there will be one line of output consisting of a single integer. This integer is the cardinality of the topmost element of the stack after the corresponding command has executed. After each test case there will be a line with *** (three asterisks).

    Example

    Input:
    2
    9
    PUSH
    DUP
    ADD
    PUSH
    ADD
    DUP
    ADD
    DUP
    UNION
    5
    PUSH
    PUSH
    ADD
    PUSH
    INTERSECT
    
    Output:
    0
    0
    1
    0
    1
    1
    2
    2
    2
    ***
    0
    0
    1
    0
    0
    ***
    

    Added by:Robin Nittka
    Date:2007-10-02
    Time limit:12s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:ACM ICPC NWERC 2006









    SPOJ Problem Set (main)

    1837. Pie

    Problem code: PIE

    My birthday is coming up and traditionally I'm serving pie. Not just one pie, no, I have a number N of them, of various tastes and of various sizes. F of my friends are coming to my party and each of them gets a piece of pie. This should be one piece of one pie, not several small pieces since that looks messy. This piece can be one whole pie though.

    My friends are very annoying and if one of them gets a bigger piece than the others, they start complaining. Therefore all of them should get equally sized (but not necessarily equally shaped) pieces, even if this leads to some pie getting spoiled (which is better than spoiling the party). Of course, I want a piece of pie for myself too, and that piece should also be of the same size.

    What is the largest possible piece size all of us can get? All the pies are cylindrical in shape and they all have the same height 1, but the radii of the pies can be different.

    Input

    One line with a positive integer: the number of test cases. Then for each test case:

    • One line with two integers N and F with 1 ≤ N, F ≤ 10000: the number of pies and the number of friends.
    • One line with N integers ri with 1 ≤ ri ≤ 10000: the radii of the pies.

    Output

    For each test case, output one line with the largest possible volume V such that me and my friends can all get a pie piece of size V. The answer should be given as a floating point number with an absolute error of at most 10-3.

    Example

    Input:
    3
    3 3
    4 3 3
    1 24
    5
    10 5
    1 4 2 3 4 5 6 5 4 2
    
    Output:
    25.1327
    3.1416
    50.2655
    

    Added by:Robin Nittka
    Date:2007-10-02
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC NWERC 2006









    SPOJ Problem Set (classical)

    1838. Ticket to Ride

    Problem code: TICKET

    Ticket to Ride is a board game for up to 5 players. The goal of the game is to set up train lines (and to thwart the opponents' attempts at setting up their train lines). At the beginning of play, each player is assigned four train lines. A player may choose to discard as many of these four assignments as she likes. Each assignment has a score, corresponding to its difficulty (so, typically, a train line between e.g. Stockholm and Tokyo would be worth more than a train line between e.g. Stockholm and Utrecht). At the end of the game, each player gets points for the assignments that they have successfully completed, and penalty points for the assignments that they have failed to complete.

    An assignment consists of a pair of cities that are to be connected by a series of shorter railway routes. A route can be claimed (for a certain cost associated with the route), but things are complicated by the fact that there is only a limited number of routes, and once a player claims a route, none of the other players can claim it. A player has successfully set up a train line between two cities if there is a path between the two cities using only routes that have been claimed by this player. For simplicity, we will ignore all additional aspects of the game (including the actual process of claiming routes and additional ways to score points).

    For instance, if your assignment is to connect Stockholm and Amsterdam in the Figure above, you would probably want to claim the routes between Stockholm and Copenhagen, and between Copenhagen and Amsterdam. But if another player manages to claim the route between Copenhagen and Stockholm before you, your train line would have to use some other routes, e.g. by going to Copenhagen via Oslo.

    In this problem, we will consider the rather bold strategy of trying to complete all four assignments (typically, this will be quite hard). As a preliminary assessment of the difficulty of achieving this, we would like to calculate the minimum cost of setting up all four lines assuming that none of the other players interfere with our plans. Your job is to write a program to determine this minimum cost.

    Input

    The input consists of several (at most 20) games to be analyzed. Each game starts with two integers 1 ≤ n ≤ 30, 0 ≤ m ≤ 1000, giving the number of cities and railway routes in the map, respectively. Then follow n lines, giving the names of the n cities. City names are at most 20 characters long and consist solely of lower case letters ('a'-'z').

    After this follow m lines, each containing the names of two different cities and an integer 1 ≤ c ≤ 10000, indicating that there is a railway route with cost c between the two cities. Note that there may be several railway routes between the same pair of cities. You may assume that it is always possible to set up a train line from any city to any other city.

    Finally, there will be four lines, each containing the names of two cities, giving the four train line assignments.

    The input is terminated by a case where n = m = 0. This case should not be processed.

    Output

    For each game, output a single line containing a single integer, the minimum possible cost to set up all four train lines.

    Example

    Input:
    10 15
    stockholm
    amsterdam
    london
    berlin
    copenhagen
    oslo
    helsinki
    dublin
    reykjavik
    brussels
    oslo stockholm 415
    stockholm helsinki 396
    oslo london 1153
    oslo copenhagen 485
    stockholm copenhagen 522
    copenhagen berlin 354
    copenhagen amsterdam 622
    helsinki berlin 1107
    london amsterdam 356
    berlin amsterdam 575
    london dublin 463
    reykjavik dublin 1498
    reykjavik oslo 1748
    london brussels 318
    brussels amsterdam 173
    stockholm amsterdam
    oslo london
    reykjavik dublin
    brussels helsinki
    2 1
    first
    second
    first second 10
    first first
    first first
    second first
    first first
    0 0
    
    Output:
    3907
    10
    

    Added by:Robin Nittka
    Date:2007-10-02
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC NWERC 2006









    SPOJ Problem Set ()

    1839. The Bookcase

    Problem code: BOOKCASE

    No wonder the old bookcase caved under the massive piles of books Tom had stacked on it. He had better build a new one, this time large enough to hold all of his books. Tom finds it practical to have the books close at hand when he works at his desk. Therefore, he is imagining a compact solution with the bookcase standing on the back of the desk. Obviously, this would put some restrictions on the size of the bookcase, it should preferably be as small as possible. In addition, Tom would like the bookcase to have exactly three shelves for aesthetical reasons.

    Wondering how small his bookcase could be, he models the problem as follows. He measures the height hi and thickness ti of each book i and he seeks a partition of the books in three non-empty sets S1, S2, S3 such that

    is minimized, i.e. the area of the bookcase as seen when standing in front of it (the depth needed is obviously the largest width of all his books, regardless of the partition). Note that this formula does not give the exact area of the bookcase, since the actual shelves cause a small additional height, and the sides cause a small additional width. For simplicity, we will ignore this small discrepancy.

    Thinking a moment on the problem, Tom realizes he will need a computer program to do the job.

    Input

    The input begins with a positive number on a line of its own telling the number of test cases (at most 20). For each test case there is one line containing a single positive integer N, 3 ≤ N ≤ 70 giving the number of books. Then N lines follow each containing two positive integers hi, ti, satisfying 150 ≤ hi ≤ 300 and 5 ≤ ti ≤ 30, the height and thickness of book i respectively, in millimeters.

    Output

    For each test case, output one line containing the minimum area (height times width) of a three-shelf bookcase capable of holding all the books, expressed in square millimeters.

    Example

    Input:
    2
    4
    220 29
    195 20
    200 9
    180 30
    6
    256 20
    255 30
    254 15
    253 20
    252 15
    251 9
    
    Output:
    18000
    29796
    

    Added by:Robin Nittka
    Date:2007-10-02
    Time limit:40s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
    Resource:ACM ICPC NWERC 2006









    SPOJ Problem Set (classical)

    1840. Printer Queue

    Problem code: PQUEUE

    The only printer in the computer science students' union is experiencing an extremely heavy workload. Sometimes there are a hundred jobs in the printer queue and you may have to wait for hours to get a single page of output.

    Because some jobs are more important than others, the Hacker General has invented and implemented a simple priority system for the print job queue. Now, each job is assigned a priority between 1 and 9 (with 9 being the highest priority, and 1 being the lowest), and the printer operates as follows.

    • The first job J in queue is taken from the queue.
    • If there is some job in the queue with a higher priority than job J, then move J to the end of the queue without printing it.
    • Otherwise, print job J (and do not put it back in the queue).

    In this way, all those important muffin recipes that the Hacker General is printing get printed very quickly. Of course, those annoying term papers that others are printing may have to wait for quite some time to get printed, but that's life.

    Your problem with the new policy is that it has become quite tricky to determine when your print job will actually be completed. You decide to write a program to figure this out. The program will be given the current queue (as a list of priorities) as well as the position of your job in the queue, and must then calculate how long it will take until your job is printed, assuming that no additional jobs will be added to the queue. To simplify matters, we assume that printing a job always takes exactly one minute, and that adding and removing jobs from the queue is instantaneous.

    Input

    One line with a positive integer: the number of test cases (at most 100). Then for each test case:

    • One line with two integers n and m, where n is the number of jobs in the queue (1 ≤ n ≤ 100) and m is the position of your job (0 ≤ m ≤ n-1). The first position in the queue is number 0, the second is number 1, and so on.
    • One line with n integers in the range 1 to 9, giving the priorities of the jobs in the queue. The first integer gives the priority of the first job, the second integer the priority of the second job, and so on.

    Output

    For each test case, print one line with a single integer; the number of minutes until your job is completely printed, assuming that no additional print jobs will arrive.

    Example

    Input:
    3
    1 0
    5
    4 2
    1 2 3 4
    6 0
    1 1 9 1 1 1
    
    Output:
    1
    2
    5
    

    Added by:Robin Nittka
    Date:2007-10-02
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC NWERC 2006









    SPOJ Problem Set (classical)

    1841. Prime Path

    Problem code: PPATH

    The ministers of the cabinet were quite upset by the message from the Chief of Security stating that they would all have to change the four-digit room numbers on their offices.
    — It is a matter of security to change such things every now and then, to keep the enemy in the dark.
    — But look, I have chosen my number 1033 for good reasons. I am the Prime minister, you know!
    — I know, so therefore your new number 8179 is also a prime. You will just have to paste four new digits over the four old ones on your office door.
    — No, it's not that simple. Suppose that I change the first digit to an 8, then the number will read 8033 which is not a prime!
    — I see, being the prime minister you cannot stand having a non-prime number on your door even for a few seconds.
    — Correct! So I must invent a scheme for going from 1033 to 8179 by a path of prime numbers where only one digit is changed from one prime to the next prime.

    Now, the minister of finance, who had been eavesdropping, intervened.
    — No unnecessary expenditure, please! I happen to know that the price of a digit is one pound.
    — Hmm, in that case I need a computer program to minimize the cost. You don't know some very cheap software gurus, do you?
    — In fact, I do. You see, there is this programming contest going on...

    Help the prime minister to find the cheapest prime path between any two given four-digit primes! The first digit must be nonzero, of course. Here is a solution in the case above.

        1033
        1733     
        3733     
        3739     
        3779
        8779
        8179     
    
    The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.

    Input

    One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).

    Output

    One line for each case, either with a number stating the minimal cost or containing the word Impossible.

    Example

    Input:
    3
    1033 8179
    1373 8017
    1033 1033
    
    Output:
    6
    7
    0
    

    Added by:Robin Nittka
    Date:2007-10-02
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC NWERC 2006









    SPOJ Problem Set (classical)

    1842. Lineland Airport

    Problem code: LINELAND

    Lineland is a strange country. As the name suggests, it's shape (as seen from above) is just a straight line, rather than some two-dimensional shape. The landscape along this line is very mountainous, something which occasionally leads to some problems. One such problem now occurs: in this modern era the king wants to build an airport to stimulate the country's economy. Unfortunately, it's impossible for airplanes to land on steep airstrips, so a horizontal piece of land is needed. To accommodate for the larger airplanes, this strip needs to have length at least L.

    Over the years, the inhabitants of Lineland have become very proficient in flattening pieces of land. Given a piece a land, they can remove rock quickly. They don't want to add rock for that may lead to an unstable landing strip. To minimize the amount of effort, however, they want to remove the least amount of rock necessary to reach their goal: a flat piece of land of length L. What is this minimum amount? Because of the low-dimensional nature of Lineland, the amount of rock that needs to be removed is measured as the total area of land above the place where the landing strip is placed, rather than the volume (so in the Figure below, the amount of land removed is given by the lightly shaded area).

    Input

    One line with a positive number: the number of test cases (at most 25). Then for each test case:

    • One line with an integer N, 2 ≤ N ≤ 500, the number of points, and an integer L, 1 ≤ L ≤ 10000, the necessary length to flatten.
    • N lines with two integers xi and yi with 0 ≤ xi, yi ≤ 10000 describing the landscape of Lineland. The xi are in (strictly) ascending order. At position xi the height of the landscape is xi. Between two xi the landscape has constant slope. (So the landscape is piecewise linear). The difference between xN and x1 is greater than or equal to L.

    Output

    For each test case, output one line with the minimum amount of rock which must be removed in order to build the airport. The answer should be given as a floating point number with an absolute error of at most 10-3.

    Example

    Input:
    4
    3 5
    0 2
    4 2
    14 0
    4 3
    0 2
    2 0
    4 0
    5 3
    3 10
    10 2
    30 2
    35 7
    2 777
    222 333
    4444 5555
    
    Output:
    0.9000
    0.3750
    0.0000
    373362.4867
    

    Added by:Robin Nittka
    Date:2007-10-02
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC NWERC 2006









    SPOJ Problem Set (classical)

    1843. Leonardo Notebook

    Problem code: LEONARDO

    — I just bought Leonardo's secret notebook!
    Rare object collector Stan Ucker was really agitated but his friend, special investigator Sarah Keptic was unimpressed.
    — How do you know it is genuine?
    — Oh, it must be, at that price. And it is written in the da Vinci code.
    Sarah browsed a few of the pages. It was obvious to her that the code was a substitution cipher, where each letter of the alphabet had been substituted by another letter.
    — Leonardo would have written the plain-text and left it to his assistant to encrypt, she said. And he must have supplied the substitution alphabet to be used. If we are lucky, we can find it on the back cover!
    She turned up the last page and, lo and behold, there was a single line of all 26 letters of the alphabet:

    QWERTYUIOPASDFGHJKLZXCVBNM

    — This may be Leonardo's instructions meaning that each A in the plain-text was to be replaced by Q, each B with W, etcetera. Let us see...
    To their disappointment, they soon saw that this could not be the substitution that was used in the book. Suddenly, Stan brightened.
    — Maybe Leonardo really wrote the substitution alphabet on the last page, and by mistake his assistant coded that line as he had coded the rest of the book. So the line we have here is the result of applying some permutation TWICE to the ordinary alphabet!
    Sarah took out her laptop computer and coded fiercely for a few minutes. Then she turned to Stan with a sympathetic expression.
    — No, that couldn't be it. I am afraid that you have been duped again, my friend. In all probability, the book is a fake.
    Write a program that takes a permutation of the English alphabet as input and decides if it may be the result of performing some permutation twice.

    Input

    The input begins with a positive number on a line of its own telling the number of test cases (at most 500). Then for each test case there is one line containing a permutation of the 26 capital letters of the English alphabet.

    Output

    For each test case, output one line containing Yes if the given permutation can result from applying some permutation twice on the original alphabet string ABC...XYZ, otherwise output No.

    Example

    Input:
    2
    QWERTYUIOPASDFGHJKLZXCVBNM
    ABCDEFGHIJKLMNOPQRSTUVWXYZ
    
    Output:
    No
    Yes
    

    Added by:Robin Nittka
    Date:2007-10-02
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC NWERC 2006









    SPOJ Problem Set (classical)

    1845. Mice and Maze

    Problem code: MICEMAZE


    A set of laboratory mice is being trained to escape a maze. The maze is made up of cells, and each cell is connected to some other cells. However, there are obstacles in the passage between cells and therefore there is a time penalty to overcome the passage Also, some passages allow mice to go one-way, but not the other way round.

    Suppose that all mice are now trained and, when placed in an arbitrary cell in the maze, take a path that leads them to the exit cell in minimum time.

    We are going to conduct the following experiment: a mouse is placed in each cell of the maze and a count-down timer is started. When the timer stops we count the number of mice out of the maze.

    Problem

    Write a program that, given a description of the maze and the time limit, predicts the number of mice that will exit the maze. Assume that there are no bottlenecks is the maze, i.e. that all cells have room for an arbitrary number of mice.

    Input

    The maze cells are numbered $1,2,\ldots,N$, where $N$ is the total number of cells. You can assume that $N\leq 100$.

    The first three input lines contain $N$, the number of cells in the maze, $E$, the number of the exit cell, and the starting value $T$ for the count-down timer (in some arbitrary time unit).

    The fourth line contains the number $M$ of connections in the maze, and is followed by $M$ lines, each specifying a connection with three integer numbers: two cell numbers $a$ and $b$ (in the range $1,\ldots,N$) and the number of time units it takes to travel from $a$ to $b$.

    Notice that each connection is one-way, i.e., the mice can't travel from $b$ to $a$ unless there is another line specifying that passage. Notice also that the time required to travel in each direction might be different.

    Output

    The output consists of a single line with the number of mice that reached the exit cell $E$ in at most $T$ time units.

    Example

    Input:
    4 
    2 
    1
    8
    1 2 1
    1 3 1
    2 1 1
    2 4 1
    3 1 1
    3 4 1
    4 2 1
    4 3 1
    
    Output:
    3
    

    Added by:Robin Nittka
    Date:2007-10-04
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC -- SWERC 2001









    SPOJ Problem Set (classical)

    1846. Project File Dependencies

    Problem code: PFDEP

    Project managers, such as the UNIX utility make, are used to maintain large software projects made up from many components. Users write a project file specifying which components (called tasks) depend on others and the project manager can automatically update the components in the correct order.

    Problem

    Write a program that reads a project file and outputs the order in which the tasks should be performed.

    Input

    For simplicity we represent each task by an integer number from $1,2,\ldots,N$ (where $N$ is the total number of tasks). The first line of input specifies the number $N$ of tasks and the number $M$ of rules, such that $N \leq 100,\; M\leq 100$.

    The rest of the input consists of $M$ rules, one in each line, specifying dependencies using the following syntax:

    
    $T_0$    $k$    $T_1$    $T_2$    ...    $T_k$
    
    This rule means that task number $T_0$ depends on $k$ tasks $T_1, T_2, \ldots T_k$ (we say that task $T_0$ is the target and $T_1\ldots T_k$ are dependents).

    Note that tasks numbers are separated by single spaces and that rules end with a newline. Rules can appear in any order, but each task can appear as target only once.

    Your program can assume that there are no circular dependencies in the rules, i.e. no task depends directly or indirectly on itself.

    Output

    The output should be a single line with the permutation of the tasks $1\ldots N$ to be performed, ordered by dependencies (i.e. no task should appear before others that it depends on).

    To avoid ambiguity in the output, tasks that do not depend on each other should be ordered by their number (lower numbers first).

    Example

    Input:
    5 4
    3 2 1 5
    2 2 5 3
    4 1 3
    5 1 1
    
    Output:
    1 5 3 2 4
    

    Added by:Robin Nittka
    Date:2007-10-04
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC -- SWERC 2001









    SPOJ Problem Set (classical)

    1847. No Change

    Problem code: NOCHANGE

    Though it might be hard to imagine, the inhabitants of a small country Additivia do not know of such thing as change, which probably has to do with them not knowing subtraction either. When they buy something, they always need to have the exact amount of addollars, their currency. The only other option, but not a really attractive one, is over-paying.

    Professor Adem, one of the Additivian mathematicians came up with an algorithm for keeping a balanced portfolio. The idea is the following. Suppose you have more coins of value $v_1$ than coins of value $v_2$. In this case you should try to spend at least as many coins of value $v_1$ as those of value $v_2$ on any buy you make. Of course spending too many $v_1$ coins is not a good idea either, but to make the algorithm simpler professor Adem decided to ignore the problem. The algorithm became an instant hit and professor Adem is now designing a kind of ``electronic portfolio'' with built-in Adem's algorithm. All he needs now is a software for these machines, that will decide whether a given amount of addollars can be paid using a given set of coins according to the rules of Adem's algorithm. Needless to say, you are his chosen programmer for the task.

    Problem

    Write a program that reads the description of a set of coins and an amount of addollars to be paid, and determines whether you can pay that amount according to Professor Adem's rules.

    Input

    The input starts with the amount of addollars to be paid $x$, where $1\le x \le 100 000$. The number of different coin values $k$ follows, where $1 \le k \le 5$. The values of the coins $v_1,\ldots,v_k$ follow, where $1 \le v_i \le 10 000$.

    Notice that the order among coin values is significant: you need to spend at least as many coins of value $v_1$ as coins of value $v_2$, at least as many coins of value $v_2$ as those of value $v_3$, and so on. You may assume that you have a sufficiently large number of coins of each value.

    Output

    Your program should output for each test case either a single word ``YES'', if the given amount can be paid according to the rules, or a single word ``NO'' otherwise.

    Example

    Input:
    13 3 9 2 1
    Output:
    NO
    

    Added by:Robin Nittka
    Date:2007-10-04
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM ICPC -- SWERC 2001









    SPOJ Problem Set ()

    1865. Making Waves

    Problem code: MKWAVES

    Suppose we know a signal is generated by the function x sin (f1t) sin (f2t). F1 and f2 are two unique frequencies, each having an integral value in the range 400 to 600 Hz (Hz = cycles per second), and t represents time. In this problem, you will be given N samples of this function at equally-spaced time intervals corresponding to t = 1/N, t = 2/N, and so forth. From these samples, you are to determine f1 and f2.

    For example, suppose f1 = 400 Hz, f2 = 500 Hz, and N = 100. The first sample, at time t = 1/100 sec, is equal to sin(400 0.01) sin(500 0.01) sin(4) sin(5) 0.156912 . Similarly, the second sample, at time t = 2/100 sec, is equal to sin(400 0.02) sin(500 0.02) sin(8) sin(10) 0.312821.

    Input

    There will be multiple cases to consider. Each case begins with an integer N, no larger than 1000, that specifies the number of signal samples. The next N data items are real numbers representing the signal samples at time 1/N sec, 2/N sec, and so forth. A single integer 0 follows the last case.

    The number of samples for each case is guaranteed to be sufficient to allow the correct result to be obtained.

    Output

    For each input case, display a single line that is formatted like this:

    Case 1, f1 = 400, f2 = 500

    Example

    Input:
    100
    0.156912 0.312821 0.466731 0.617657 0.764638 0.906737 1.04305 1.17271
    1.29489 1.40883 1.51381 1.60917 1.69432 1.76873 1.83195 1.8836 1.92338
    1.95106 1.96649 1.96962 1.96045 1.93908 1.9057 1.86055 1.80396 1.73634
    1.65816 1.56997 1.47237 1.36603 1.25166 1.13003 1.00196 0.868307 0.729943
    0.587785 0.442764 0.295823 0.147918 1.68756e-010 -0.146981 -0.292088
    -0.434403 -0.573031 -0.707107 -0.835801 -0.958325 -1.07394 -1.18195
    -1.28171 -1.37266 -1.45428 -1.52611 -1.58779 -1.63898 -1.67947 -1.70907
    -1.7277 -1.73535 -1.73205 -1.71795 -1.69323 -1.65816 -1.61308 -1.55838
    -1.49452 -1.42201 -1.34141 -1.25334 -1.15846 -1.05745 -0.951057 -0.840028
    -0.725146 -0.607206 -0.487017 -0.365392 -0.243145 -0.121082 -2.75143e-010
    0.119322 0.236125 0.34968 0.459289 0.564288 0.664055 0.758014 0.845635
    0.926438 1 1.06595 1.12398 1.17384 1.21533 1.24833 1.27276 1.28862
    1.29596 1.29489 1.28558
    
    0
    
    Output:
    Case 1, f1 = 400, f2 = 500
    

    Added by:Camilo Andrés Varela León
    Date:2007-10-07
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:North Central North America Regional Programming Contest - 2003









    SPOJ Problem Set (classical)

    1866. Making Pals

    Problem code: MKPALS

    A palindrome is a sequence that is the same when read forward or backward. For example, “pop” is a palindrome, as are “Poor Dan is in a droop” (ignoring spaces and case), and “12321”.

    In this problem, you are to find the “cheapest” way to transform a sequence of decimal digits into a palindrome. There are only two types of modifications you may make to the sequence, but each of these may be repeated as many times as necessary. You may delete a digit from either end of the sequence, or you may add a digit to either end of the sequence. Each of these operations incurs a “cost” of 1. For each input sequence, determine the smallest cost of transforming the sequence into a palindrome, and the length of the resulting palindrome. If two palindromes can be produced with the same cost, the length of the longer palindrome (the one with more digits) is to be reported.

    For example, suppose the initial sequence was “911”. This can be transformed into a palindrome by deleting the leading “9” (yielding “11”) or by adding an additional “9” to the right end of the sequence (yielding “9119”). Since both of these transformations have a cost of 1, and the second transformation yields a longer palindrome, it is this one which would be reported as your result.

    Note that the particular palindrome produced by the cheapest sequence of transformations is not necessarily unique, but since you are not required to report the resulting palindrome, any of these will suffice.

    Input

    There will be multiple cases to consider. Each case has a single line of input that contains one or more decimal digits followed by the end of line. The maximum number of digits in a sequence will be 6. The last case is followed by an empty line (that is, only an end of line).

    Output

    For each input case, display the case number (1, 2, …), the input sequence, the cost of the cheapest transformation, and the length of the resulting palindrome. Your output should follow the format shown in the examples below.

    Example

    Input:
    911
    9118
    11234
    <-- This line is blank
    
    Output:
    Case 1, sequence = 911, cost = 1, length = 4
    Case 2, sequence = 9118, cost = 2, length = 4
    Case 3, sequence = 11234, cost = 3, length = 8
    

    Added by:Camilo Andrés Varela León
    Date:2007-10-07
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:North Central North America Regional Programming Contest - 2003









    SPOJ Problem Set ()

    1868. Making Money

    Problem code: MKMONEY

    A trick sometimes used by parents to teach their children the value of money is to give then a penny – just a penny! – and the promise that for each day they don’t spend it, the parent will double it. All students of computing know that long before a month has elapsed without spending a cent, the parents will not likely be able to make good on their promise.

    100-percent compound daily interest on an investment is, of course, unattainable in normal financial dealings, but we are all continually reminded of the power of compound interest, even with the relatively low interest rates available today.

    But exactly how much money can be made with compound interest? Assume, for example, an initial investment of $100.00 (US or Canadian ☺), an annual interest rate of 6.00 percent, and that interest is compounded monthly. That is, the interest earned during the preceding month is added to the principal at the end of the month. (For our purposes, we’ll assume a month is exactly 1/12th of a year.)

    At the end of the first month, the money will have earned 0.5 percent interest (1/12th of 6.00 percent), or $0.50. This is added to the $100.00 invested, so that during the next month, interest is paid on $100.50. During the next month another 0.5 percent interest is earned, which is exactly $0.5025. We will assume that the bank, being conservative, will not pay any interest less than $0.01, so our investment is credited with an additional $0.50 at the end of the second month, for a whopping total of $101.00. Continuing in the same manner, at the end of 12 months our investment will total $106.12, $0.12 more than simple 6.00 percent interest for a year with no compounding.

    Given an amount P to be invested for a year with I percent interest, compounded C times during the year at equal intervals, what is total return on the investment?

    Input

    There will be multiple cases to consider. The input for each case is a single line containing the initial investment amount, P, given in dollars and cents (but no fractional cents, and no larger than $100,000.00), the annual interest rate (I) given as a real number with two fractional digits representing a percentage, greater than zero but less than 100, and the number of compounding intervals per year (C), an integer between 1 and 365. The last case will be followed by a line containing “0.00 0.00 0”.

    Output

    For each input case, display the case number (1, 2, …), the initial investment (P), the annual interest rate (I), the number of compounding intervals per year(C), and the value of the investment at the end of a year. Your output should follow the format shown in the examples below.

    Example

    Input:
    100.00 6.00 1
    100.00 6.00 12
    1000.00 6.00 12
    0.00 0.00 0
    
    Output:
    Case 1. $100.00 at 6.00% APR compounded 1 times yields $106.00
    Case 2. $100.00 at 6.00% APR compounded 12 times yields $106.12
    Case 3. $1000.00 at 6.00% APR compounded 12 times yields $1061.63
    

    Added by:Camilo Andrés Varela León
    Date:2007-10-07
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:North Central North America Regional Programming Contest - 2003









    SPOJ Problem Set ()

    1869. Making Mountains Out Of Molehills

    Problem code: MKMOOM

    A macro processor is a symbol processing program. It takes a stream of characters as its input, and produces a stream of characters as its output. A “macro” is similar to ordinary function in that it has a definition, and when invoked, that definition is applied to the argument(s) to yield the result. In this problem, you will develop a simple macro processor.

    A “macro call” consists of a name and a list of arguments, separated by commas. The name is preceded by '[' (a left bracket) and the last argument is followed by ']' (a right bracket). For example, “[doit,to,it]” calls the macro named “doit” with two arguments, “to” and “it”. “[random]” calls the macro named “random” with no arguments.

    Before a macro can be called, it must be defined by associating its name with a symbol string. This definition string may contain the special constructions “$1” through “$9” to reference the first through the ninth macro parameters. “$0” references the macro’s name itself. When the macro is called, these constructions are literally replaced by the values of the parameters. For example, suppose the definition string for the macro named “321” was “$3-$2-$1”. The macro call “[321,This,is,fun]” would yield the output “fun-is-This”. A macro call can appear anywhere. For example, the macro call “[321,[321,A,B,C],D,E]” would yield the output “E-D-C-B-A”.

    Input enclosed in '<' and '>' prevents the evaluation of the text enclosed, allowing special characters like '[', ']', ',' and '$' to be used in other than their usual contexts. Thus the macro call “[321,<$>,<[>,<,>]” would yield “,-[-$”.

    Macros are defined using the predefined macro named “def”, which has two arguments. The first argument is the name of the macro being defined, and the second argument is the defining symbol string for the macro. The “321” macro definition is “[def,321,<$3-$2-$1>]”. Note that the definition is enclosed in '<' and '>' to prevent “$1”, “$2”, and “$3” from being interpreted as parameter references to def. The def macro produces no output. Naturally, the def macro isn’t defined using def, but is treated specially by the implementation.

    Processing

    The input stream is processed character by character and copied to the output until a macro call is encountered, or the input is exhausted (which terminates processing). A macro call is evaluated as described below, with the result (if any) copied to the output.

    1. The macro name and the parameters are evaluated in sequence from left to right. This may require evaluating additional macro calls, which must be processed recursively.
    2. When the argument list is complete (that is, when the closing ']' is encountered) the definition of the macro being called is scanned in the same manner as the original input stream except that occurrences of “$0”, “$1”, and so forth are replaced literally by the corresponding arguments. The result of the macro call is the symbol stream produced by this scan.
    3. When the macro call is completed, the macro name and the arguments are discarded, and processing resumes at the point where it was interrupted by the macro call.

    Limits and Caveats

    Macro names and arguments will contain no more than 32 characters each. The defining string for a macro will contain no more than 100 characters. Macros will never be defined more than once (that is, the same macro name will not be used more than once as the first argument to “def”). Macro calls will always provide the correct number of arguments. Character case is significant in comparisons. All input characters, including end of line characters, are to be processed through the macro processor. No output line will contain more than 80 characters, including the end of line character. The input is guaranteed to be correct.

    Input

    There will be multiple cases to consider. The input for each case begins with a line containing a single integer between 1 and 10, that specifies the number of lines of text immediately following that will be used as input to the macro processor. None of these lines will contain more than 80 characters, so the input to the macro processor will contain at most 810 characters. The last case will be followed by a line containing the integer 0.

    Output

    For each input case, display the case number (1, 2, …), a line containing 79 hyphens, the output from the macro processor, another line containing 79 hyphens, and a blank line.

    In the sample input shown below, assume that the last visible character on each line is immediately followed by the end of line character. Blank lines in the expected output are shown here as **BLANK** for clarity, but these should actually be totally blank in your output.

    Example

    Input:
    1
    This is just copied (including end of line).
    1
    [def,321,<$3-$2-$1>][321,This,is,fun]
    1
    [def,321,<$3-$2-$1>][321,[321,A,B,C],D,E]
    1
    [def,321,<$3-$2-$1>][321,This,is,fun][321,[321,A,B,C],D,E]
    3
    [def,321,<$3-$2-$1>]
    [321,This,is,fun]
    [321,[321,A,B,C],D,E]
    3
    [def,A,<$1[B]$2>]
    [def,B,*B*]
    [A,1,2]
    2
    [def,#,<[-]$1[-]$2[-]$3[-]>][def,-,<$0>][def,DEF,def][[DEF],X,THIS IS X]
    [X][#,DEF,#,X]
    0
    
    Output:
    Case 1
    -------------------------------------------------------------------------------
    This is just copied (including end of line).
    -------------------------------------------------------------------------------
    **BLANK**
    Case 2
    -------------------------------------------------------------------------------
    fun-is-This
    -------------------------------------------------------------------------------
    **BLANK**
    Case 3
    -------------------------------------------------------------------------------
    E-D-C-B-A
    -------------------------------------------------------------------------------
    **BLANK**
    Case 4
    -------------------------------------------------------------------------------
    fun-is-ThisE-D-C-B-A
    -------------------------------------------------------------------------------
    **BLANK**
    Case 5
    -------------------------------------------------------------------------------
    **BLANK**
    fun-is-This
    E-D-C-B-A
    -------------------------------------------------------------------------------
    **BLANK**
    Case 6
    -------------------------------------------------------------------------------
    **BLANK**
    **BLANK**
    1*B*2
    -------------------------------------------------------------------------------
    **BLANK**
    Case 7
    -------------------------------------------------------------------------------
    **BLANK**
    THIS IS X-DEF-#-X-
    -------------------------------------------------------------------------------
    **BLANK**
    

    Added by:Camilo Andrés Varela León
    Date:2007-10-07
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:North Central North America Regional Programming Contest - 2003









    SPOJ Problem Set (classical)

    1870. Making Labels

    Problem code: MKLABELS


    Trees comes in many varieties other than the popular binary tree. In general, a tree is a connected acyclic graph. That is, it consists of some number of vertices N (which we’ll assume is at least one in this problem), and N – 1 edges, each of which connects a pair of vertices.

    A “labeled tree” is a tree in which each vertex has been given a “label.” For simplicity, let us assume these labels are the integers 1 through N. In how many different ways may a tree with N vertices be labeled? By “different” we mean that no rearrangement of two trees with the same number of vertices with different labeling will be identical. (Note that although we commonly associate data with each vertex, and identify one vertex as the root of the tree, that’s not significant in this problem.)

    Let’s consider some examples. The figure below shows all possible arrangements of trees with N = 1, 2, 3, 4, or 5 vertices. The number shown below each tree is the number of different ways in which the vertices in each tree can be labeled.

    Illustration

    Clearly a tree with only one vertex can be labeled in only one way – by assigning the label “1” to the single vertex. A tree with two vertices can also be labeled in only one way. For example, although the two trees shown on the left below appear to be different, the first can be easily transformed into the second. (Imagine the edges are strings, so the vertices can be easily repositioned without losing their connectivity.)

    Illustration

    There are, however, three possible ways to label the vertices in a 3-vertex tree, as shown on the right above. No matter how you rearrange the labeled vertices in any of the three trees, you cannot produce any of the other labeled trees.

    In a similar manner, the various arrangements of four vertices in a tree yield a total of 16 possible labelings – 12 for the four vertices “in a row,” and 4 for the other configuration. There are three possible arrangements of the vertices in a tree with N = 5, with a total of 125 possible

    Input

    There will be multiple cases to consider. The input for each case is an integer N specifying the number of vertices in a tree, which will always be between 1 and 10. The last case will be followed by a zero.

    Output

    For each input case, display the case number (1, 2, …), the input value of N, and the number of different ways in which a tree with N vertices may be labeled. Use the format shown in the examples below.

    Example

    Input:
    2
    3
    4
    5
    0
    
    Output:
    Case 1, N = 2, # of different labelings = 1
    Case 2, N = 3, # of different labelings = 3
    Case 3, N = 4, # of different labelings = 16
    Case 4, N = 5, # of different labelings = 125
    

    Added by:Camilo Andrés Varela León
    Date:2007-10-07
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:North Central North America Regional Programming Contest - 2003









    SPOJ Problem Set (classical)

    1871. Making A Budget

    Problem code: MKBUDGET


    A company uses temporary employees (“temps”) to handle its varying workloads. By doing so, it avoids having to pay for benefits normally provided to its permanent employees. However, the company must pay an employment agency a fixed fee for each temp they hire, as well as paying the temp a fixed amount of severance pay when they are terminated – in addition, of course, to the monthly salary each temp receives. The company has a good understanding of when it needs temporary workers, and how many such workers it will require each month. Depending on the fee paid to the employment agency, the temporary worker’s salary, and the severance pay, it may make sense to retain an unneeded worker for one or more months if it’s known that they will be needed again in the future.

    Let’s consider an example. Suppose we know that in March the company will need 10 temps, in April they’ll need 9, and in May they’ll need 11. Suppose a temp earns $500 per month, that the employment agency receives $400 for each temp hired, and $600 is paid as severance to each temp that is terminated. If the company employs just the minimum number of temps required, then their payments will be as follows (we ignore the cost of terminating all employees at the end of the last month):

    Illustration

    The total cost to the company is $20,400. But suppose they did not terminate the unneeded temp at the end of March, but just let that person remain employed. They would then save $400 in employment agency fees (since they’d need to hire just one additional temp for May), $600 in severance pay, and only have to pay the temp worker $500, for an overall savings of $500.

    In this problem you are given, as input, the number of months for which the company is to plan its temp worker budget, the cost of hiring and firing a temp worker, the temp worker’s monthly salary, and the required minimum number of workers needed each month. You are to determine the minimum cost to the company to have at least the required minimum number of workers on hand each month. Assume there are no temporary workers on hand before the first month, and that the cost of terminating the workers at the end of the last month is not to be included in the cost. You may assume that the planning interval will be no longer than 24 months, and the hiring cost, severance pay, and monthly salary for each temp worker is greater than zero.

    Input

    There will be multiple cases to consider. The input for each case begins with an integer N, the number of months for which planning is required (never larger than 24). This is followed by three integers giving the cost of hiring a worker, the worker’s monthly salary, and the severance pay for a terminated worker. Finally there will appear N integers giving the required minimum number of workers needed in each month. The last case will be followed by a zero.

    Output

    For each input case, display the case number (1, 2, …) and the minimum cost to the company. Use the format shown in the examples below.

    Example

    Input:
    3 400 500 600 10 9 11
    8 400 600 600 11 9 10 14 9 9 13 15
    0
    
    Output:
    Case 1, cost = $19900
    Case 2, cost = $66600
    

    Added by:Camilo Andrés Varela León
    Date:2007-10-07
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:North Central North America Regional Programming Contest - 2003









    SPOJ Problem Set ()

    1873. Accumulate Cargo

    Problem code: ACARGO

    A cargo shipment containing N (1 <= N <= 105) boxes, has just arrived and it requires some regrouping. All the cargo is currently placed on a long circular conveyor belt of length L metres (1 <= L <= 109), which you can control and perform the following operations.

    • Rotate the wheel clock wise or anti-clockwise (free of cost).
    • Hold the cargo at some point and not let it move, while the belt is rolling. This causes the cargo behind it to come closer to this cargo by one step. Any consecutive sequence of cargo is grouped together and called as a luggage. The aim of the program is to group all cargo as a single luggage. Now the cost of this holding operation for one second is equal to the weight of the luggage that is held fixed. Also please note that you can hold the luggage only at ends of the luggage and never at inbetween points.
    Each unit of cargo weighs exactly one Kg. The conveyor belt rotates at a speed of one meters per second.
    This cost function directly reflects the human effort required to group the cargo. Workers would be happy if you can write a program that prints the minimal required effort to group the cargo, assuming an intelligent sequence of operations.


    Input Format:
    The input file consists of multiple testcases.
    The first line of each testcase contains two integers, N and L.
    The following N lines contain one integer each specifying the position of the ith cargo on the belt. The positions will be between 0 & L-1.
    Input terminates with a line containing N=0 and L=0 which must not be processed.

    Output Format:
    For each testcase print one integer in a single line, which is the minimal required cost for grouping all the cargo into a single luggage.

    Sample Input:
    3 5
    0
    1
    3
    2 3
    0
    1
    5 20
    2
    7
    12
    9
    13
    0 0
    
    Sample Output:
    1
    0
    10
    
    NOTE: Please use 64-bit integers.

    Added by:Prasanna
    Date:2007-10-08
    Time limit:1s-10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
    Resource:NITT ACM ICPC Local Contest 2007 [Idea from a Topcoder problem]









    SPOJ Problem Set (classical)

    1874. Burrows Wheeler Precompression

    Problem code: BWHEELER

    The Burrows-Wheeler transform (BWT, also called block-sorting compression), is an algorithm used in data compression techniques such as bzip2. It was invented by Michael Burrows and David Wheeler.

    When a character string is transformed by the BWT, none of its characters change value. The transformation permutes the order of the characters. If the original string had several substrings that occurred often, then the transformed string will have several places where a single character is repeated multiple times in a row. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.

    For example, the string:

    SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES
    

    could be transformed into this string, which is easier to compress because it has many repeated characters:

     TEXYDST.E.IXIXIXXSSMPPS.B..E.S.EUSFXDIIOIIIT
    

    Now the Burrows-Wheeler algorithm works as follows:

    • Given an input string S, eg: "abcba".
    • Find all rotations of S.
      eg: "abcba", "bcbaa", "cbaab", "baabc", "aabcb"
      
    • Now sort the strings hence produced.
      eg: "aabcb", "abcba", "baabc", "bcbaa", "cbaab"
      
    • Arrange the strings in a len(S) x len(S) grid.
      aabcb
      abcba
      baabc
      bcbaa
      cbaab
      
    • Output the row number (1-based indexing) containing the original input string. Also output the strings formed by characters in the last column.
      eg: 2 bacab


    Now given the output of Burrows-Wheeler, can you recover the orginal string?

    Input Format:
    The input file consists of multiple testcases.
    The first line of each testcase contains one integer, R, indicating the row number containing the original input string in the sorted matrix.
    The second line of each testcase contains one string, Col, which is the last column of the grid. (1 <= len(Col) <= 1000)
    Col contains only lowercase characters. 1 <= R <= len(Col).
    Input terminates with a line containing R=0 which must not be processed.

    Output Format:
    Print the original input string to the burrow wheeler's algorithm.

    Testdata:
    30 testcases
    Sample Input:
    2
    bacab
    3
    rwlb
    11
    baaabaaaabbbaba
    0
    
    Sample Output:
    abcba
    rbwl
    baaabbbbaaaaaab
    

    Added by:Prasanna
    Date:2007-10-08
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:NITT ACM ICPC Local Contest 2007 [Wikipedia/General]









    SPOJ Problem Set (classical)

    1875. Cool Numbers

    Problem code: COOLNUMS

    Cool numbers are those, whose digits can be partitioned into two sets such that the sum of the digits in either sets are equal.
    Example: 23450 is cool because 3+4+0 = 2+5; So is 91125;
    The numbers 567, 34523 are not cool, since there is no such digit partition.

    Write a program that prints the number of cool numbers in the inclusive range [A,B].


    Input Format:
    The input file consists of multiple testcases.
    Each case contains one line containing two 32-bit unsigned integers A and B. (1 <= A <= B <= 4*109).
    Input terminates with a line containing two zeros and must not be processed.

    Output Format:
    For each testcase print a single line containing one integer saying the number of cool numbers between A and B, inclusive.

    Sample Input:
    1 11
    12 20
    1 20
    3 100
    6354 234363
    123456789 234567891
    0 0
    
    Sample Output:
    1
    0
    1
    9
    82340
    54801678
    

    Test Data:
    About 50 testcases.


    Added by:Prasanna
    Date:2007-10-08
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:NITT ACM ICPC Local Contest 2007 [Topcoder problem with Constraints raised]









    SPOJ Problem Set (main)

    1876. Dragon Curves

    Problem code: DRAGONCU

    Define r(s) to be the complement of the reverse of the binary string s. i.e. Reverse s and then convert all 1's to 0's and all 0's to 1's.
    Further define a sequence of binary string as follow: s0 = 1 and sn = sn-11r(sn-1). i.e.
    s0 = 1
    s1 = 110
    s2 = 1101100
    s3 = 110110011100100
    ...

    We then program a robot to move at a steady speed of 1 unit per second and make a right-angle turn according to the characters of s10 after every unit of movement. At the kth turn, the robot turns to left if the kth character of s10 is a 1, and to right otherwise. The figure below shows the whole path of the robot.

    The robot is placed at the origin (the small circle) and face east originally. It ends up at the coordinates (-32,32) (the small spot) after 2048 seconds. The path of the robot is known as a dragon curve, a pretty well-known pattern of fractal.

    If the robot is now programmed with input string s30 (with identical initial conditions as above), it will keep moving and then stop after 231 seconds. We want to know the location of the robot at any given time.


    Input Format:
    Input consists of multiple problem instances. Each instance consists of a single non-negative integer n, where n <= 109. The input data is terminated by a "-1". There will be less than 5000 test cases.

    Output Format:
    For each input integer n, print out the location of the robot right after n second since the robot starts its journey with input string s30. The location should be printed with the format "(x,y)" in a single line.

    Sample Input:
    1
    2
    3
    2048
    1000000000
    -1
    

    Sample Output:
    (1,0)
    (1,1)
    (0,1)
    (-32,32)
    (9648,-31504)
    

    Added by:Prasanna
    Date:2007-10-08
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:NITT ACM ICPC Local Contest 2007 [Tsinghua]









    SPOJ Problem Set (main)

    1877. Enrich my purse

    Problem code: EPURSE


    Jack plays this ball game for the first time in his club. Jack has a ball, which bounces with a width of W. Coins are arranged on a straight line at regular intervals. If the ball strikes the i-th coin, Jack gains money[i] (which could possibly be negative). Jack can take atmost B turns, to throw the ball. At each turn, jack can either throw the ball from left to right, or right to left, and choose which ball to start the knock out. If he chooses to knock out from ball i to the right, he will knock out i, i+W, i+2W, ...; Similarly if he chooses to knock out from right to left, starting from ball i he will knock out, i, i-W, i-2W, ...; Please note that once a ball is knocked out, it is removed and it's place contains a void. i.e., you cant gain money[i] for the same i twice.
    Jack wants to maximise his money gained, by carefully choosing his turns. If there is more than one way to gain the same money, jack wishes to minimise the number of times he throws.

    Input Format

    The input file consists of multiple testcases.
    The first line of each testcase contains three integers, W B N (1 <= N <= 100; W,B > 0)
    The second line of each testcase contains N integers, denoting money[i]. (| money[i] | <= 106)
    Input terminates with a line containing three zeros which must not be processed.

    Output Format

    For each testcase print one line denoting the maximal money gained and the number of turns taken. Please see the sample output and stick to the output format.
    "Case#id: Jack wins $X out of Y throws."
    NOTE: You must spell the same way the sample output says. Extra spaces and case insensitivity can cause wrong answer responses.

    Testdata:
    100 testcases, Timelimit: 10s

    Sample Input:

    2 3 10
    -1 3 2 5 1 -2 0 5 1 -3
    2 3 14
    -1 3 2 5 -5 -5 1 -2 0 5 -5 -5 1 -3
    3 3 5
    -1 -2 -3 -4 -5
    1 2 6
    -1 -1 10 10 -1 -1
    0 0 0
    
    Sample Output:
    Case#1: Jack wins $15 out of 2 throws.
    Case#2: Jack wins $10 out of 3 throws.
    Case#3: Jack wins $0 out of 0 throws.
    Case#4: Jack wins $18 out of 1 throws.
    

    Output Explanation:
    We present one of the optimal solutions. We number balls from 1 to N.
    TestCase#1: [Jack takes only two throws, though he can take three]
    Throw#1: From ball#3 towards right, 2 + 1 + 0 + 1 = 4
    Throw#2: From ball#8 towards left, 5 + -2 + 5 + 3 = 11
    TestCase#2:
    Throw #1: From ball#3 towards left, 2 + -1 = 1
    Throw #2: From ball#4 towards left, 5 + 3 = 8
    Throw #3: From ball#13 towards right, 1 = 1
    TestCase#3:
    All numbers are negative. Jack takes no throws.


    Added by:Prasanna
    Date:2007-10-08
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:NITT ACM ICPC Local Contest 2007 [Self]









    SPOJ Problem Set (classical)

    1878. Farmers Cattle

    Problem code: FCATTLE


    Farmer john owns a single cow and he loves it a lot. The cow has a disease and is going to die. To survive, the cow needs medicine of a particular type each day. Let us say the cow needs medicine[i] to survive the ith day. (medicine[i] will be terminated by -1, which is an unavailable medicine, and the cow has to invariably die that day).
    To help the cow, john has decided to buy pastures of some medical value. Farmer sees a two-dimensional grid of pastures, each cell having exactly one medical herb. Now he needs to buy a sub-rectangular region of the grid, whose area cannot exceed A (A > 1). With this region the farmer intends to feed his cow, as long as possible.


    Input Format:
    The input file consists of multiple testcases.
    The first line of each testcase contains three integers, R, C and A.
    The second line consists of sequence of integers describing medicine[i]. This list will be terminated by -1.
    The next R lines contain C integers each, specifying the medicinal type of the herb in that cell. (1 <= R,C <= 200). All herbs are specified by non negative integers.
    Input terminates with a line containing three zeros and must not be processed.

    Output Format:
    For each testcase print a single line containing 5 integers:
    days r1 c1 r2 c2
    (1 <= r1 <= r2 <= R, 1 <= c1 <= c2 <= C)
    • days is the number of days the cow survives. We wish to maximise this.
    • If there are more than one solutions print the one with minimal r1.
    • If there are more than one solutions still, print the one with minimal c1.
    • If there are more than one solutions still, print the one with minimal r2.
    • If there are more than one solutions still, print the one with minimal c2.

    Sample Input:
    3 4 6
    12 30 12 100 22 -1
    30 12 5 3
    12 30 100 5
    22 3 22 100
    3 4 6
    2 30 12 100 22 -1
    30 12 5 3
    12 30 100 5
    22 3 22 100
    3 4 6
    12 30 12 100 22 -1
    30 12 5 3
    12 30 100 5
    22 12 22 100
    0 0 0
    
    Sample Output:
    4 1 1 2 3
    0 1 1 1 1
    5 1 2 3 3
    

    Added by:Prasanna
    Date:2007-10-08
    Time limit:5s-120s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:NITT ACM ICPC Local Contest 2007 [Self]









    SPOJ Problem Set (classical)

    1879. Game Time

    Problem code: GAMETIME

    Jack has got a new game of Super Mario recently. There are n castles in the game, and Princess Peach has been kidnapped by the King Koopa and enjailed in castle n - 1 (0-based). The King Koopa has Son Koopas, and the Son Koopas has Grandson Koopas, and the Grandson Koopas has Great-Grandson Koopas... The whole Koopa family is taking possession of these n castles, and there is exactly one Koopa in each castle and the King Koopa is in castle n - 1. Super Mario's task is to conquer these castles and save Princess Peach.

    Each time, Super Mario can freely choose an unconquered castle and go in to fight with the Koopa. Super Mario has time T[i] to conquer castle i and beat the Koopa in it. If Super Mario fails to conquer the castle or fails to do that within the time limit, the game is over. Otherwise, the defeated Koopa will go to seek the Father Koopa for help. If any Koopa has two or more Son Koopas beaten by Super Mario, he will get angry. Super Mario has to go to the castle of the angry Koopa and beat him immediately; otherwise the Princess Peach will be killed. If castle n - 1 is conquered and King Koopa is defeated, the game will also end, but with triumph and Princess Peach saved.

    Jack loves this game a lot, but he has to prepare for the upcoming ACM/ICPC. So he guarantees to himself that he only plays the game once a month. However, Jack really loves playing game and hates programming, he wants to maximize the time he can spend on the game without breaking his promise.


    Input Format:
    The input consists of multiple test cases.
    Each test case starts with a number N (0 < N <= 100,000) in a single line, the number of castles and Koopas. There are two lines following and each contains N numbers.
    The first line is N numbers, T[i] (0 < T[i] <= 100) for Super Mario to conquer castle i.
    The second line is N numbers of P[i] (-1 <= Pi < N), the castle (0-based) in which the Parent of each Koopa resides.
    -1 means that there is no parent for him, and the last number will always be -1, since King Koopa has no Parent Koopa. The input ends with 0(zero), which should not be processed.

    Output Format:
    Output the maximal time Jack can play in a single line for each test case.

    Sample Input:
    5
    1 2 3 4 5
    4 4 4 4 -1
    5
    2 2 2 2 2
    1 2 3 4 -1
    9
    1 1 1 1 1 1 1 1 1
    6 6 6 7 7 7 8 8 -1
    0
    
    Sample Output:
    12
    10
    8    
    

    Added by:Prasanna
    Date:2007-10-08
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:NITT Local Contest 07 [ZJU inc constrts]









    SPOJ Problem Set (classical)

    1880. Hanoi Calls

    Problem code: HANOICAL

    Theory:

    • Towers of hanoi is an arrangement consisting of three pegs and N discs of radius 1 to N.
    • Each peg can hold zero or more discs, but at any point of time, the radius of the discs must be in decreasing order from bottom to top.
    • A move consists of moving the topmost disc from one peg to another. After the move, the decending order property of pegs must hold.
    Traditional problem is: If all discs are stacked up on peg#1, how many moves will it take to move all the discs to peg#2?
    Recursive solution: Noting that for disc N to move, from peg #a to peg #b, all discs of size 1 to N-1 must be in peg #c. Hence there is exactly one minimal way to move the discs. After disc N has moved, all pegs from #c must be moved back to #a. If moves(N) denote the number of moves required to transfer N discs between two pegs (both sorted configuration), then moves(N) = moves(N-1) + 1 + moves(N-1); Solving the recurrence yields moves(N) = 2N -1; The idea i am trying to share is that, there is exactly one such move sequence.

    Now the problem is that given any initial configuration of the discs, and any final configuration, Can you tell me the minimal number of moves required to change it from initial to final configuration?


    Input Format:
    The input file consists of multiple testcases.
    The first line of each testcase contains one integer, N (1 <= N <= 30)
    The second line of each testcase contains N integers, each one of which will be between 1 and 3. The i-th integer tells you the peg number at which disc of radius i is present in the initial configuration.
    The third line contains a similar specification for the final configuration.
    Input terminates with a line containing a single zero, which must not be processed.

    Output Format:
    For each testcase print one line containing a single integer, which is the minimal number of moves to make the transfer.
    Testdata:
    100 testcases

    Sample Input:
    4
    1 1 1 1
    2 2 2 2
    3
    1 3 3
    2 1 1
    5
    1 3 2 2 2
    2 3 2 1 2
    0
    
    Sample Output:
    15
    6
    14
    
    Output Explanation:
    TestCase#1:
    This is the moves(4) = 2^4 -1;
    TestCase#2:
    [peg1, peg2, peg3] = 
    #0 [ {1}, {}, {3,2} ]
    #1 [ {1}, {2}, {3}  ]
    #2 [ {}, {2,1}, {3} ]
    #3 [ {3}, {2,1}, {} ]
    #4 [ {3}, {2}, {1}  ]
    #5 [ {3,2}, {}, {1} ]
    #6 [ {3,2}, {1}, {} ]
    

    Added by:Prasanna
    Date:2007-10-08
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:NITT ACM ICPC Local Contest 2007 [Self/Traditional]









    SPOJ Problem Set (classical)

    1881. Instruction Decoder

    Problem code: ICODER

    Mathews uses a brand new 16-bit instruction processor. (Yeah i am being sarcastic!). It has one register (say R) and it supports two instructions:

    • ADD X; Impact: R = (R + X) mod 65536
    • MUL X; Impact: R = (R * X) mod 65536
    • [For both instructions 0 <= X <= 65535]
    Mathews sees a segment of code, but doesnot know what value the register had before the code was being executed. How many possible values can the register have after the segment completed execution?


    Input Format:
    The input file consists of multiple testcases.
    The first line of each testcase contains one integer, N. (1 <= N <= 100,000).
    The following N lines contain one instructions each.
    Input terminates with a line containing N=0, which must not be processed.

    Output Format:
    For each testcase print one integer in a single line, denoting the number of different values the register can take after code execution.

    Sample Input:
    1
    ADD 3
    1
    MUL 0
    5
    MUL 3
    ADD 4
    MUL 5
    ADD 3
    MUL 2
    8
    ADD 32
    MUL 5312
    ADD 7
    MUL 7
    ADD 32
    MUL 5312
    ADD 7
    MUL 7
    0
    
    Sample Output:
    65536
    1
    32768
    16
    

    Added by:Prasanna
    Date:2007-10-08
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:NITT ACM ICPC Local Contest 2007 [Self]









    SPOJ Problem Set (classical)

    1960. Rectangles

    Problem code: RECTANGL

    You are given a set S of N points in the plane and must count the number of distinct axis-parallel rectangles whose four vertices all lie in S (that is, count those rectangles which have two sides parallel to the x-axis, and the other two sides parallel to the y-axis).

    Input

    The first line of the input is N (1 ≤ N ≤ 250000), the number of points in S. N lines then follow, where the i-th line is of the form "xi yi", giving the coordinates of a point (xi, yi) in S. All given points are distinct, and all coordinates fit into a 32-bit signed integer.

    Output

    Your output should consist of a single number, the number of distinct axis-parallel rectangles whose four vertices all lie in S, followed by a newline.

    Example

    Input:
    6
    -1 0
    -1 1
    0 0
    0 1
    1 0
    1 1
    
    Output:
    3
    

    Added by:Jelani Nelson (Minilek)
    Date:2007-10-25
    Time limit:1s-30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:MIT Individual Contest 2007









    SPOJ Problem Set (main)

    1961. Roman Roads

    Problem code: ROMANRDS

    Some 2000 years ago the Roman Empire covered a large part of Europe including the entire coast of the Mediterranean. The transportation network of that empire consisted of roads and sea routes (the two are considered equivalent and simply called roads for this problem). Each road connected exactly two cities and the road network was such that every city can be reached from Rome. However, building this network required resources (cobblestone and buoys) proportional to the total length of the network. In order to cut down on building costs and maintainance and spend the rest of the money on wine, the empire built the cheapest possible network.

    Additionally, each road had a single signpost that listed all of the other roads it connected to (at any of its two cities). There were N roads in the empire labeled 1, 2, ..., N. It is believed that a traveller once travelled all roads and for each road wrote down the numbers on its signpost, thus making a map.

    2000 years later a young archaeologist found something that looks suspiciously like that map. Your job is to write a program that determines if this can really be a map of the Roman empire and for each road output the two cities it connected. Note that roads in a valid map are always between two distinct cities.

    (Disclaimer: The description of the transportation network is for this problem only and may not necessarily be what the Roman Empire actually did. Do not cite this in your history papers: I made it up.)

    Input

    The first line of input contains N, 1N500. Each of the next N lines contains a space-separated list of integers. The i-th of these lines describes the "roads" that connect to "road" i. The first number on the line specifies the number of those "roads", di, and the following di numbers specify their labels.

    Note that although at this point we don't know if the map is valid, the input is consistent, i.e. if a road x is on the signpost of y, then y will be on the signpost of x. (Otherwise the archaeologist would know this is not a Roman map right away).

    Output

    If the input cannot describe a valid map according to the description, output "NO" on the first (and only) line of output.

    Otherwise, output "YES" and on each of the next N lines, write two integers separated by space, the numbers of the two cities that the road connected. City labeling is up to you with the only restriction that all city labels must be integers between 1 and M, where M is the total number of cities. Of course, a city can only have one label.

    Note that since we don't know the actual locations of the cities or whether the roads were straight, we have no idea what the total cost of the network might have been. The archaeologist is willing to accept any map for which she can't determine if there is a cheaper network without knowing the actual costs. It is assumed that each road had some positive cost.

    Example

    Input:
    3
    2 3 2
    2 1 3
    2 2 1
    
    Output:
    YES
    1 3
    4 1
    1 2
    

    Added by:Jelani Nelson (Minilek)
    Date:2007-10-25
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT Individual Contest 2007









    SPOJ Problem Set (main)

    1962. Circles

    Problem code: CIRCLES

    Little Gary plays the following video game. Circles pop up on the screen and disappear from it. When the screen flashes, Gary can draw a straight line on the screen and win as many points as there are circles intersected by the line. As a born-to-be-winner, Gary wants to maximize his score. Please, help him, and write a program that will determine the maximum number of points he can win each time the screen flashes.

    Input

    The first line of the input contains M (1M1000), the number of events during the game. The next M lines contain descriptions of the events, one per line. They can be in one of the following three formats:

    1 x y r
    , representing a circle of radius r popping up with the position of its center at (x, y) in the plane

    2 i
    , representing a circle i disappearing, where circle i is the ith circle that popped up since the beginning of the game; and

    3
    , representing the screen flashing.

    x, y, and r are real numbers with at most two decimals, -106 < x, y, r < 106, r > 0.

    Notes:

    • A line intersects a circle if it has at least two common points with it.
    • At any time, no two Circles on the screen have a common point.
    • At any time, there is no line that "touches" more than two circles (a line touches a circle if they have exactly one common point).
    • At any time, there are no more than 100 circles on the screen.
    • Each i determines a circle that is on the screen at the moment of removal.
    • No circle is removed twice.

    Output

    Each time the screen flashes, write an integer to a separate line, which is the maximum number of circles Gary can intersect.

    Example

    Input:
    9
    1 3.00 0.00 1.00
    1 -2.00 0.00 1.00
    3
    1 2.00 3.00 1.50
    3
    1 2.00 -4.00 1.00
    3
    2 3
    3
    
    Output:
    2
    2
    3
    2
    

    Added by:Jelani Nelson (Minilek)
    Date:2007-10-25
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









    SPOJ Problem Set (classical)

    1963. Image Projections

    Problem code: IMGPROJ

    Given an image I with N columns and M rows, a diagonal projection is the vector (d1, d2, ..., dM+N-1) where di = Σx+y-1=i I(x,y). Here I(x,y), 1xN, 1yM, is the image intensity (a non-negative integer less than 256) at column x and row y.

    You are given a set of images and you are asked to find the diagonal projection for each of them.

    Input

    The first line of input contains a positive number, the number of images that follow. For each image there is a line with N and M. The following M lines describe one row each starting from row 1. A row is described in run-length encoding by pairs of numbers separated by spaces. The first number in each pair is the length of the run and the second number is the image intensity. Obviously, for each row, the run lengths add up to N. As in the example input, there is a blank line between each two consecutive images and before the first one.

    The number of test cases is at most 10. The width of each image is less than 109 and the height is less than 103. Additionally, the total size of the input does not exceed 4 MB.

    Output

    For each image you should output one line, the diagonal projection for the image in run length encoding. The number of output lines should be the same as the number of images in the input. All the numbers on a line should be separated by exactly one space.

    When encoding the output in run-length encoding, the runs should be as long as possible, i.e. no two consecutive runs should have the same intensity value.

    Example

    Input:
    2
    
    3 3
    1 1 1 2 1 3
    1 1 1 2 1 3
    1 3 1 2 1 1
    
    3 2
    3 1
    3 1
    
    Output:
    1 1 1 3 1 8 1 5 1 1
    1 1 2 2 1 1
    

    Added by:Jelani Nelson (Minilek)
    Date:2007-10-25
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:MIT Individual Contest 2007









    SPOJ Problem Set (main)

    1964. Tree cut

    Problem code: MMCUT

    You are given a tree (a connected, acyclic graph) along with a set of commodities, i.e. pairs of vertices, (s1,t1),...,(sm ,tm) (siti). A multicut is a set of edges that when removed disconnects si from ti for all i. There is a unique path Pu,v between every pair of vertices u,v in a tree, and the max-cost of a multicut S is maxi |SPsi, ti|. You will be given a rooted tree of height 1 and a set of commodities and must return the minimum possible max-cost over all multicuts.

    Input

    The first line of the input is "N M" (1N, M100000), where N is the number of vertices in the tree and M is the number of commodities. All vertices are numbered 0, ...,N-1, and the root has label N - 1. M lines then follow, where the ith line is "si ti", representing a commodity (si, ti) where siti. Commodities are distinct: neither (si, ti) = (sj, tj) nor (si, ti) = (tj, sj) will hold when ij.

    Output

    Your output should consist of a single number, the minimum possible max-cost of a multicut, followed by a newline.

    Example

    Input:
    10 2
    0 5
    4 8
    
    Output:
    1
    

    Added by:Jelani Nelson (Minilek)
    Date:2007-10-25
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT Individual Contest 2007









    SPOJ Problem Set (main)

    1965. Set Cover

    Problem code: SETCOV

    In the set cover problem there is a collection C = {S1, ...,Sm} of subsets of the universe [n] = {0, ...,n-1}, and one must find a minimum-sized subcollection of C that still covers [n] (it may be the case that Si and Sj contain the exact same elements for some ij). A path of length r is a graph on r+1 vertices v0, ...,vr where vi has an undirected edge to vi+1 for i = 0, ...,r-1 (these are the only edges). A set cover instance I is said to be path-realizable if there exists a mapping from I to a path of length m where the Si are mapped to edges in the path and each i in [n] is mapped to a pair of (not-necessarily distinct) vertices si, ti on the path such that the edges lying between si and ti correspond exactly to the sets of C that contain i. Two sets Si,Sj must be mapped to different edges on the path if ij. You will be given a set cover instance that is guaranteed to be path-realizable and should output the size of a minimum-sized subcollection of C still covering [n].

    Input

    The first line of the input is "N M" (1 ≤ N, M ≤ 300), where N is the size of the universe and M is the number of sets Si in the collection of subsets of {0, ...,N - 1}. What follows are M groups of lines. The ith group starts with one line containing |Si|, the size of the ith subset. If |Si| = 0, the current group of lines ends. Otherwise the next line is a space-separated list of the elements contained in Si.

    Output

    If [n] cannot be covered by a subcollection of C then you should output -1, followed by a newline. Otherwise, your output should consist of two lines. The first line is the size of a minimum-sized set cover. The second line is a space-separated list of the 0-based indices of the sets in an optimal set cover.

    Example

    Input:
    3 4
    0
    2
    2 1
    2
    1 0
    0
    
    Output:
    2
    1 2
    

    Added by:Jelani Nelson (Minilek)
    Date:2007-10-25
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT Individual Contest 2007









    SPOJ Problem Set (main)

    1966. Ski Valley

    Problem code: SKIVALL

    The Society of Sport of New Hampshire has decided to build a new attraction in White Mountains. For the first time, the world will see a ski-valley, a ski path that goes downhill then uphill. They believe that skiers can gain enough speed from going down in the first part in order to climb up the second part. To maximize the joy of visitors, they want to find the longest such path.

    To simplify calculations, they approximate the mountain terrain with a matrix of square fields and obtain the height of each field from the New Hampshire Geographical Institute. A ski-valley is a sequence of neighboring fields, such that height of fields only decreases along the sequence until some point, and then it only increases until its end. No field appears more than once in a ski-valley. Two fields are neighbors if they share a common edge. The length of a ski-valley is the number of fields in its sequence.

    More technically, the terrain is an M x N matrix of fields, where (i, j) denotes a field in the ith row and jth column, and h(i, j) denotes its height. A ski-valley is a sequence (x1, y1), (x2, y2), ..., (xl, yl), such that:

    1. for any i (1il-1), either xi = xi+1 and |yi - yi+1| = 1, or yi = yi+1 and |xi - xi+1| = 1 (neighbors rule)
    2. if ij (1i, jl), then either xixj or yiyj (no repeating rule), and
    3. There exists a k (1kl), such that h(x1, y1) > h(x2, y2) > ... > h(x_k-1, y_k-1) > h(xk, yk) < h(x_k+1, y_k+1) < ... < h(xl, yl) (down-up rule).

    The length of such ski-valley is l.

    They hire you, a reputable programmer, to write a program that will find a ski-valley of maximum length. If there are multiple ski-valleys with the same (maximum) length, you can choose any of them.

    Note: Yes, they were not cautious and also allowed a ski-valley to bo only downhill or only uphill, but your job is only to adhere to the specification they gave you!

    Input

    The first line of the input contains M and N (1 ≤ M, N ≤ 60), respectively, separated by a space character. Each of the next M lines contain N numbers, such that the jth number in the ith line represents h(i, j) (-106 ≤ h(i, j) ≤ 106). No two fields in the terrain are of the same height. Numbers on a line are separated by a space character.

    Output

    In the first line of the output, write a single number lmax, which is the maximum length of a ski-valley. In the next lmax lines write a description of any ski-valley of that length. In each of the lines, write two integers separated by a space character, such that numbers xi and yi in the ith line represent (xi, yi), the ith field in the ski-valley.

    Example

    Input:
    3 4
    2 6 7 16
    1 4 3 20
    9 8 17 12
    
    Output:
    9
    3 1
    3 2
    2 2
    2 1
    1 1
    1 2
    1 3
    1 4
    2 4
    

    Added by:Jelani Nelson (Minilek)
    Date:2007-10-25
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT Individual Contest 2007









    SPOJ Problem Set (classical)

    1991. Another Continuous Fractions Problem

    Problem code: ACFRAC

    The problem description is the same as the problem CFRAC and CFRAC2.

    Input & Output

    Multiple test cases, a single line with a single uppercase character C indicates the end of the input. The number of test cases will be less than 1000.

    For each test case:

    The first line of the input contains a single uppercase character A or B.A denotes that the input following character A and output format of this test case is the same as problem CFRAC, otherwise the input following character B and output format of this test case is the same as problem CFRAC2. But please pay attention that: the width and the height of the image after the character B will not appear in the input; the original fraction will not appear in the output of the test case of type A.

    The example will make everything clear.

    Example

    Input:
    A
    75 34
    B
    ..........1......
    2.+.-------------
    ............1....
    ....4.+.---------
    ..............1..
    ........1.+.-----
    ................1
    ............5.+.-
    ................1
    C
    
    Output:
    Case 1:
    ..........1......
    2.+.-------------
    ............1....
    ....4.+.---------
    ..............1..
    ........1.+.-----
    ................1
    ............5.+.-
    ................1
    Case 2:
    75 34
    

    Added by:[Trichromatic] XilinX
    Date:2007-11-01
    Time limit:15s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:XX Colombian National Programming ACM 2006, test data by Blue Mary









    SPOJ Problem Set (classical)

    2000. Boxes (Hard)

    Problem code: BOX

    There are n boxes on the circle. The boxes are numbered from 1 to n in clock wise order. There are balls in the boxes, and the number of all the balls in the boxes is not greater than n.

    The balls should be displaced in such a way that in each box there remains no more than one ball. In one move we can shift a ball from one box to one of it's neighboring boxes.

    Write a program that: reads from the standard input the number of boxes n and the arrangement of balls in the boxes, computes the minimal number of moves necessary to displace the balls in such a way that in each box there remains no more than one ball, writes the result in the standard output.

    Input

    The first line of the input file contains an integer t representing the number of test cases. Then t test cases follows. Each test case has the following form:

    • The first line contains one positive integer n - the number of boxes
    • The second line contains n nonnegative integer separated by single spaces. The i-th number is the number of balls in the i-th box.

    Output

    For each test case, output one nonnegative integer - the number of moves necessary to displace the balls in such a way that in each box there remains no more than one ball.

    Example

    Input:
    1
    12
    0 0 2 4 3 1 0 0 0 0 0 1
    
    Output:
    19
    

    Note

    There are two input files.

    In the first input file, t=19, n<=1000, time limit=0.5 second;

    In the second input file, t=3, n<=200000, time limit=15 seconds.

    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-11-02
    Time limit:0.5s-15s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:POI III, stage 3; Special thanks to Lei Huang









    SPOJ Problem Set (classical)

    2002. Random Number Generator

    Problem code: RNG

    LoadingTime got a RNG (Random Number Generator) from his classmate several weeks ago. And he spent a lot of time study it. He found that RNG can generate a real number in range [-S,S] by executing following steps. First RNG generates n integer X1..Xn, the sum of which is equal to S. Then for each Xi, it generates a real number in range [-Xi,Xi] randomly. The output (a real number) of RNG will be the sum of the N generated real numbers. LoadingTime noticed that the distribution of the output was very interesting, and he wanted to know: for given N and X, what's the probability that the generated number is in range [A,B]. Could you help him?

    Input

    The first line contains an integer T representing the number of test cases.

    For each test case, the first line contains three integers N, A, B(1 ≤ N ≤ 10, -100 ≤ AB ≤ 100) In the second line of the test case, you are given X1...Xn(1 ≤ Xi ≤ 10).

    Output

    For each test case, print a line contains a real number representing the probablity as the problem required. It must be printed with exactly nine decimal places.

    Example

    Input:
    5
    1 -100 100
    10
    1 10 90
    10
    1 -20 5
    10
    2 -20 5
    5 5
    5 -5 10
    1 2 3 4 5
    
    Output:
    1.000000000
    0.000000000
    0.750000000
    0.875000000
    0.864720052
    
    

    Added by:Bin Jin
    Date:2007-11-03
    Time limit:1s
    Source limit:10000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:www.test-the-best.by









    SPOJ Problem Set (algo_s3)

    2005. Minus Operation

    Problem code: MINUS

    There are n integer numbers listed in one line. Every time you can arbitrarily choose two neighboring integers, kick them out and write down the result of the first number subtract the second number instead. Now, you want to get number m after you perform this operation n-1 times.

    Input

    Multiple test cases, the number of them is given in the very first line.

    For each test case:

    The first line contains two space-separated integers n(1<= n <=100) and m(-500<= m <=500). n lines follow, each contains a single integer (in the range [0,100]) denotes the original numbers.

    Output

    For each test case:

    You should output n-1 lines, each contains a single integer pi, which denotes that you are to wipe the pi-th and (pi+1)-th number in the current sequence and use their substraction instead. Each line of your output should not have any leading or trailing white spaces.

    You may assume that there is always a valid solution to each test case in the input file. If there are multiple solutions, any of them will be accepted.

    Print a blank line after each test case.

    Example

    Input:
    1
    5 4
    12
    10
    4
    3
    5

    Output:
    2
    3
    2
    1

    Added by:[Trichromatic] XilinX
    Date:2007-11-03
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:C++ 4.3.2 C++ 4.0.0-8 JAVA
    Resource:description by Blue Mary; standard program and test data by Zhou Yisu









    SPOJ Problem Set (classical)

    2006. Load Balancing

    Problem code: BALIFE


    SuperComputer Inc. have built a super-fast computer server consisting of N hyper-scalar lightning-fast processors Beta 007. These processors are numbered from 1 to N and are used to process independent jobs. Every new incoming job is assigned to an arbitrary processor. Sometimes, a processor may be assigned too many jobs while other processors have a relatively light load (or even wait idly). In that case, the whole system undergoes rebalancing.

    Rebalancing proceeds in rounds. In each round, every processor can transfer at most one job to each of its neighbors on the bus. Neighbors of the processor i are the processors i-1 and i+1 (processors 1 and N have only one neighbor each, 2 and N-1 respectively). The goal of rebalancing is to achieve that all processors have the same number of jobs.

    Given the number of jobs initially assigned to each processor, you are asked to determine the minimal number of rounds needed to achieve the state when every processor has the same number of jobs, or to determine that such rebalancing is not possible.

    Input file specification

    The input file consists of several blocks. Each block begins with a line containing a single number N(1<= N <=9000) - the number of processors. N numbers follow, separated by spaces and/or end of line characters. The i-th number denotes the number of jobs assigned to the i-th processor before rebalancing. There is a blank line after each block. The last block is followed by a single number -1 on a separate line (which should not be processed).

    Output file specification

    For each block in the input file, output the minimal number of rounds needed to rebalance loads for all the processors. If it is not possible to rebalance jobs so that each processor has the same number of jobs, output -1.

    Example

    Input file:
    3
    0 99 3
    
    2
    49 50
    
    8
    16 17 15 0 20 1 1 2
    
    10
    0 0 100 0 0 0 0 0 0 0
    
    -1
    
    Output file:
    34
    -1
    23
    70
    

    Added by:[Trichromatic] XilinX
    Date:2007-11-03
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2002









    SPOJ Problem Set (classical)

    2007. Another Very Easy Problem! WOW!!!

    Problem code: COUNT

    Background

    This problem is somewhat easier than the problem A Very Easy Problem! because of the super long time limit...

    Description

    Assurance Company of Moving (ACM) is a company of moving things for people. Recently, some schools want to move their computers to another place. So they ask ACM to help them. One school reserves K trucks for moving, and it has N computers to move. In order not to waste the trucks, the school ask ACM to use all the trucks. That is to say, there must be some computers in each truck, and there are no empty trucks. ACM wants to know how many partition shemes exists with moving N computers by K trucks, the ACM ask you to compute the number of different shemes with given N and K. You needn't care with the order. For example N=7,K=3, the the following 3 partition instances are regarded as the same one and should be counted as one sheme: "1 1 5","1 5 1","5 1 1". Each truck can carry almost unlimited computers!!

    Input

    Each line of the input contains two postisive integer N (1<=N<=5000) and K(1<=K<=N).Input is terminated by a line with N=K=0(this case should not be processed).

    Output

    For each line, output the number of different partition sheme. To avoid big integers, you may output the answer modudo 1988.

    Example

    Input:
    1 1
    7 3
    0 0

    Output:
    1
    4

    Added by:[Trichromatic] XilinX
    Date:2007-11-03
    Time limit:21s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Time limit: 1000 Years! Memory limit: 2000 GB! Acc%: 100%!









    SPOJ Problem Set (classical)

    2008. Dab of Backpack

    Problem code: BACKPACK


    One day Blue Mary goes to a nearby supermarket to buy some goods. She has a backpack, whose capacity is V-Max. She finds that there are many goods in the market, each has a volume Vi(it will always be a multiple of 10 and less than 10000) and an importance Ci(1<= Ci <=5). Since she has almost unlimited money, the only problem she is to solve is how to choose goods such that the total volume won't exceed the capacity of the backpack and the sum of the product of the volume and the importance of each good is maximum. To be an excellent mathematician, she comes up with the answer quickly, and now she wants you to do a harder task. There are two kinds of goods: main goods and attachments. If you want to buy an attachment you must buy its main good before.

    Input

    Multiple test cases, the number of them is given in the very first line.

    For each test case:

    The first line contains two space-separated integers V-Max (1<=V-Max<=32000) and the number of the goods N (1<=N<=60). N lines follow, each contains three space-separated integers Vi, Ci and a integer u. If u is not 0, this good is an attachment of good u(as the order in the input file).

    To make the problem not too difficult, Blue Mary tells you that:

    (A) An attachment won't have any attachments which belong to it.

    (B) A main good will always have less than 3 attachments.

    Output

    For each test case:

    The first and the only line contains a single integer denoted the answer.

    Example

    Input:
    1
    1000 5
    800 2 0
    400 5 1
    300 5 1
    400 3 0
    500 2 0
    
    Output:
    2200
    

    Added by:[Trichromatic] XilinX
    Date:2007-11-03
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Based on a Problem from Chinese National Olympiad in Informatics in Province 2006









    SPOJ Problem Set (classical)

    2009. Cryptography

    Problem code: CRYPTO

    Your task is to work as a cryptographer for some time, the reason is ...

    Blue Mary has set a problem using English. Since the problem is too easy and it will be boring when solving it, she has deleted all the whitespaces and punctuations in the original problem description, and lowercased all the capital latin letters. Then, she randomly chose a permutation of the English lowercase letter alphabet, and then used the corresponding letters in place of the letters in the original text.

    The encrypted text can be downloaded here.

    There is no example for this problem.

    Blue Mary's note: some tricky test cases were added on Nov. 25th, 2007 and the time limit has been changed. Programs have been rejudged and some "accepted" solutions got Wrong Answer. However, this problem can still be solved by quite clean code with length less than 1KB.


    Added by:[Trichromatic] XilinX
    Date:2007-11-03
    Time limit:1s-11s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Sadly, the ability to make a simple problem difficult to understand is seldom considered a talent.









    SPOJ Problem Set (main)

    2019. The Rolling Ball

    Problem code: ROLLBALL

    Rolling Ball

    Problem

    A solid spherical ball of radius R rolls without slipping on the inside surface of a fixed cone, whose tip points downward. The half-angle at the vertex of the cone is u. Initial conditions have been set up so that the ball travels around the cone in a horizontal circle of radius l>R, with the points on the ball that touch the cone tracing out a circle on the ball. Determine the radius of the circle of these contact points, if you want the sphere to travel around the cone as fast as possible.

    The Input

    Each line of input has integers l (R < l <= 1000000) R (0 < R <= 1000) and u (0 < u < 90) given in degrees.

    The Output

    For each line of input, output the radius of the circle of the contact points, round to integer.

    Sample Input

    220000 100 29
    

    Sample Output

    46
    


    Problemsetter --- Wu, Xiaogang
    Added by:Chen Xiaohong
    Date:2007-11-06
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









    SPOJ Problem Set (classical)

    2021. Moving Pebbles

    Problem code: PEBBMOV

    A Game of Moving Pebbles

    Problem

    Two players play the following game. At the beginning of the game they start with n (1<=n<=100000) piles of stones. At each step of the game, the player chooses a pile and remove at least one stone from this pile and move zero or more stones from this pile to any other pile that still has stones. A player loses if he has no more possible moves. Given the initial piles, determine who wins: the first player, or the second player, if both play perfectly.

    The Input

    Each line of input has integers 0 < n <= 100000, followed by n positive integers denoting the initial piles.

    The Output

    For each line of input, output "first player" if first player can force a win, or "second player", if the second player can force a win.

    Sample Input

    3 2 1 3
    

    Sample Output

    first player
    


    Problemsetter --- Chen, Jiahong
    Added by:Chen Xiaohong
    Date:2007-11-06
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6









    SPOJ Problem Set (main)

    2022. Truth Or Lie

    Problem code: TRUTHORL


    Truth Or Lie

    Problem

    Suppose you have m yes or no questions that you want to ask n people. You are allowed to ask each person exactly two different questions. He/she will answer exactly one of them correctly and one of them incorrectly, you don't know which is a correct answer and which is an incorrect one. Given their answers, determine the number of combinations of answers to the m questions that can still be correct (i.e., no contradictions).

    The Input

    First line is the number of inputs. For each set of input, start out with a line of n<=10000 and m<=200, followed by n lines. The i-th line has four integers a b c d. It means that the answer given by the i-th person for question a is b, and for question c is d. Moreover, the answer "1" means yes, and "0" means no.

    The Output

    For each line of input, output "No Inference" if the answers do not help you eliminate any wrong combination of answers or the number of combinations of possible answers is 0, otherwise output the size of the set of combinations of answers still possible.

    Sample Input

    2
    2 2
    1 1 2 0
    1 1 2 1
    4 4
    1 1 2 1
    1 1 3 0
    2 1 4 1
    3 1 4 0
    

    Sample Output

    No Inference
    2
    


  • Problemsetter --- sy
    Added by:Chen Xiaohong
    Date:2007-11-06
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









    SPOJ Problem Set (classical)

    2023. One Instruction Computer Simulator

    Problem code: ONEINSTR

    A computer with only one instruction! The instruction is:

    SUBLEQ A B C
    

    This means: subtract the value in M(A) from M(B) and store it in M(B); if the result is non-positive jump to the instruction in position C. M(i) represents the value stored in memory position i. The computer has a memory of 9999 integer positions, numbered from 0 to 9998. C > 9996, indicates the end of the program. Also, if A is negative, then the value of A is directly subtracted from M(B).

    Since there is only one instruction, it is unnecessary to represent its opcode explicitely in memory. Therefore, an instruction is stored in main memory using three consecutive memory positions, which correspond to the three instruction parameters. The memory is organized as follows:

    Position Content
    0-8      input/output variables (M0 to M8)
    9-9998   program memory (instructions+data)
    

    The following pseudo-code shows the one instruction computer simulator:

    simulate(integer M[0..9998])
       integer pc,A,B,C
       pc = 9
       while (pc<9997)
          A = M[pc]; B = M[pc+1]; C = M[pc+2]
          if(A>=0) 
             M[B] = M[B] - M[A]
          else
             M[B] = M[B] - A
          if (M[B]>0)
             pc = pc + 3
          else
             pc = C
          end_if
       end_while
    end_simulate
    

    Each iteration of the above while instruction is called a simulation cycle. You are to translate postfix instructions into this machine language. There are at most 100 arithematic terms and 99 operators. Numerical constants are non-negative and less than or equal to 10000.

    Input

    The input has several test cases, one test case per line. Each test case corresponds to an arithmetic expression in postfix notation. An expression may contain constants (integer values), input variables (M0 to M8) and arithmetic operators (+, -, *, /).

    Output

    For each test case, a program must be printed using the following format: First line indicates m, the number of instructions of the program; and the following m lines contain the program, one instruction per line, where each instruction is represented by 3 integer values separated by one blank space. Your outputed program must finish within 10^7 simlation cycles for each test case.

    Example

    Input:
    100
    M1 M2 -
    
    Output:
    3
    0 0 12
    -100 0 0
    19 19 10000
    
    4
    0 0 12
    1 2 15
    2 0 18
    21 21 10000
    

    Added by:Chen Xiaohong
    Date:2007-11-06
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Changed and Enhanced from Columbian National Contest









    SPOJ Problem Set (classical)

    2031. Please help You-Know-Who

    Problem code: YKH


    Background

    Poor You-Know-Who was out of business for quite some time, being neither dead, nor alive. He would like to get rich so that he can run for the post of Minister of Magic. From there he could unfold at least some of his evil plots even if he lost most of his magical powers. You are fed up with all this Harry Potter business and decide to help You-Know-Who make some dough. You-Know-Who inherited lots of magic powder that increases one's sense of smell for a short period of time if inhaled. He will sell it and you'll help him maximize the profit.

    Problem

    You-Know-Who has C clients. Client i will buy a[i]−b[i]*p powder if the unit price is p. That is, if You-Know-Who shows a certificate issued by the Minister saying that the asked price is the correct price. Getting one such certificate involves paying a bribe B. To maximize the profit he may buy several such certificates and use for each client the one that maximizes his profit. You must tell You-Know-Who what certificates he should get. With some luck, Harry Potter is out!

    Input

    The first line contains the number of testcases, which shall be less than 20. The testcases follow. (Possible empty lines between testcases should be ignored.)

    The first line of each testcase input contains two non-negative integers: the bribe B and the number of clients C. The next C lines describe each client by two positive integers a[i] and b[i] (on line i). You are guaranteed that all numbers in the input are at most 2000.

    Output

    For each testcase the output is a single number, the maximum profit of You-Know-Who, and it should be written on a line by itself. The answer should have either an absolute or a relative error less than 1e-6.

    Example

    Input:
    2
    10 2
    10 1
    20 3
    100 1
    5 1
    
    Output:
    46.25
    0
    

    First testcase: If YKW would have only the first client then he should choose to get a certificate for the price 5. This way he will sell 5 grams of powder for a profit of 5x5-10=15. Analogously, for the second client the optimal price would be 3.(3), which would make the client buy 10 grams of magic powder. Choosing the optimal price for each client means that two bribes must be payed, which leads to a profit of 5x5+10x3.(3)-2x10=38.(3). Nevertheless, YKW can win more money by getting only one certificate for the price 3.75. This way the profit is 6.25x3.75+8.75x3.75-10=46.25.

    The second testcase shows that sometimes it's better to not sell magic powder to some clients.


    Added by:Radu Grigore
    Date:2007-11-07
    Time limit:10s
    Source limit:10000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:CSIC 2007









    SPOJ Problem Set (classical)

    2038. Rectangle Tiling

    Problem code: TILING

    We say that a 2-dimensional, rectangular word w of size n×m (imagine it as a board with letter written in the squares) can be tiled with a rectangular pattern p if there are such occurrences of p in w (but not necessarily all of them) that no two of them overlap and each symbol (square) of w is covered by one of them. Given such word w, find a rectangular pattern p of smallest size (area) which the word w can be tiled with.

    Input

    The first line of input contains a number t (1≤t≤100) that indicates the number of test cases to follow. Each test case begins with a line consisting of two positive integers n and m (1≤n,m≤1000) indicating dimensions of the board. n lines follow, each of them containing m small letters of the English alphabet (a,b,...,z).

    Output

    For each test case output the smallest possible area of a pattern p that can be used to tile the given board.

    Example

    Input:
    3
    4 3
    aaa
    aaa
    aaa
    aaa
    4 4
    abab
    cdcd
    abab
    cdcd
    3 4
    aaaa
    aaaa
    aaab
    
    Output:
    1
    4
    12
    
    

    Added by:Pawel Gawrychowski
    Date:2007-11-10
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6









    SPOJ Problem Set (classical)

    2047. Stone Removing Game

    Problem code: REMGAME

    Consider the following game. The game is played on a 5 x 5 board. Initially every array cell has a piece in it. Two players remove pieces alternatively from the board. The player can remove any number of consecutive pieces in a row or column. For example, in the configuration depicted below where one indicates a piece, the player can either remove one piece (A1, A2, or B1), or remove two pieces (A1 and A2, or A1 and B1) simultaneously. The game ends when one player is forced to take the last piece, and the other player wins the game.


      1 2 3 4 5
    A 1 1 0 0 0
    B 1 0 0 0 0
    C 0 0 0 0 0
    D 0 0 0 0 0
    E 0 0 0 0 0


    Write a program that evaluates board configurations from this game. The program must output "winning" when there exists a winning move that no matter how the opponent responds, it will force the opponent to take the last piece. Otherwise, the program must output "losing".

    Input

    The first line contains n, the number of test cases. For each test case, a 5x5 grid of an initial game configuration is shown.

    Output

    For each case, output "winning" or "losing".

    Example

    Input:
    1 
    1 0 0 0 0 
    1 1 0 0 0 
    1 1 1 0 0 
    1 1 1 1 0 
    1 1 1 1 1
    
    Output:
    winning
    

    Added by:Chen Xiaohong
    Date:2007-11-13
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Adapted from Taiwan TPC 1999, Harder datasets.









    SPOJ Problem Set (classical)

    2050. Strange Billboard

    Problem code: CERC07B

    The marketing and public-relations department of the Czech Technical University has designed a new reconfigurable mechanical Flip-Flop Bill-Board (FFBB). The billboard is a regular two- dimensional grid of R × C square tiles made of plastic. Each plastic tile is white on one side and black on the other. The idea of the billboard is that you can create various pictures by flipping individual tiles over. Such billboards will hang above all entrances to the university and will be used to display simple pictures and advertise upcoming academic events. To change pictures, each billboard is equipped with a "reconfiguration device". The device is just an ordinary long wooden stick that is used to tap the tiles. If you tap a tile, it flips over to the other side, i.e., it changes from white to black or vice versa. Do you agree this idea is very clever?

    Unfortunately, the billboard makers did not realize one thing. The tiles are very close to each other and their sides touch. Whenever a tile is tapped, it takes all neighboring tiles with it and all of them flip over together. Therefore, if you want to change the color of a tile, all neighboring tiles change their color too. Neighboring tiles are those that touch each other with the whole side. All inner tiles have 4 neighbors, which means 5 tiles are flipped over when tapped. Border tiles have less neighbors, of course.

    example

    For example, if you have the billboard configuration shown in the left picture above and tap the tile marked with the cross, you will get the picture on the right. As you can see, the billboard reconfiguration is not so easy under these conditions. Your task is to find the fastest way to "clear" the billboard, i.e., to flip all tiles to their white side.

    Input

    The input consists of several billboard descriptions. Each description begins with a line containing two integer numbers R and C (1 <= R,C <= 16) specifying the billboard size. Then there are R lines, each containing C characters. The characters can be either an uppercase letter "X" (black) or a dot "." (white). There is one empty line after each map. The input is terminated by two zeros in place of the board size.

    Output

    For each billboard, print one line containing the sentence "You have to tap T tiles.", where T is the minimal possible number of taps needed to make all squares white. If the situation cannot be solved, output the string "Damaged billboard."instead.

    Example

    Input:
    5 5
    XX.XX
    X.X.X
    .XXX.
    X.X.X
    XX.XX
    
    5 5
    .XX.X
    .....
    ..XXX
    ..X.X
    ..X..
    
    1 5
    ...XX
    
    5 5
    ...X.
    ...XX
    .XX..
    ..X..
    .....
    
    8 9
    ..XXXXX..
    .X.....X.
    X..X.X..X
    X.......X
    X.X...X.X
    X..XXX..X
    .X.....X.
    ..XXXXX..
    
    0 0
    
    Output:
    You have to tap 5 tiles.
    Damaged billboard.
    You have to tap 1 tiles.
    You have to tap 2 tiles.
    You have to tap 25 tiles.
    
    

    Added by:Rafal
    Date:2007-11-15
    Time limit:1s-20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set (classical)

    2051. Cell Phone

    Problem code: CERC07C


    Nowadays, everyone has a cellphone, or even two or three. You probably know where their name comes from. Do you. Cellphones can be moved (they are "mobile") and they use wireless connection to static stations called BTS (Base Transceiver Station). Each BTS covers an area around it and that area is called a cell.

    The Czech Technical University runs an experimental private GSM network with a BTS right on top of the building you are in just now. Since the placement of base stations is very important for the network coverage, your task is to create a program that will find the optimal position for a BTS. The program will be given coordinates of "points of interest". The goal is to find a position that will cover the maximal number of these points. It is supposed that a BTS can cover all points that are no further than some given distance R. Therefore, the cell has a circular shape.

    example

    The picture above shows eight points of interest (little circles) and one of the possible optimal BTS positions (small triangle). For the given distance R, it is not possible to cover more than four points. Notice that the BTS does not need to be placed in an existing point of interest.

    Input

    The input consists of several scenarios. Each scenario begins with a line containing two integer numbers N and R. N is the number of points of interest,1 <= N <= 2 000. R is the maximal distance the BTS is able to cover, 0 <= R < 10 000. Then there are N lines, each containing two integer numbers X_i, Y_i giving coordinates of the i-th point, |X_i|, |Y_i| < 10 000. All points are distinct, i.e., no two of them will have the same coordinates.

    The scenario is followed by one empty line and then the next scenario begins. The last one is followed by a line containing two zeros.

    A point lying at the circle boundary (exactly in the distance R) is considered covered. To avoid floating-point inaccuracies, the input points will be selected in such a way that for any possible subset of points S that can be covered by a circle with the radius R +0.001, there will always exist a circle with the radius R that also covers them.

    Output

    For each scenario, print one line containing the sentence "It is possible to cover M points.", where M is the maximal number of points of interest that may be covered by a single BTS.

    Example

    Input:
    
    8 2
    1 2
    5 3
    5 4
    1 4
    8 2
    4 5
    7 5
    3 3
    
    2 100
    0 100
    0 -100
    
    0 0
    
    Output:
    
    It is possible to cover 4 points.
    It is possible to cover 2 points.
    

    The first sample input scenario corresponds to the picture, providing that the X axis aims right and Y axis down.


    Added by:Rafal
    Date:2007-11-16
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set ()

    2052. Hexagonal Parcels

    Problem code: CERC07H

    A civil engineer that has recently graduated from the Czech Technical University encountered an interesting problem and asked us for a help. The problem is more of economical than engineering nature. The engineer needs to connect several buildings with an infrastructure. Unfortunately, the investor is not the owner of all the land between these places. Therefore, some properties have to be bought first.

    The land is divided into a regular "grid" of hexagonal parcels, each of them forms an independent unit and has the same value. Some of the parcels belong to the investor. These parcels form four connected areas, each containing one building to be connected with the others. Your task is to find the minimal number of parcels that must be acquired to connect the four given areas.

    example

    The whole land also has a hexagonal shape with six sides, each consisting of exactly H parcels. The above picture shows a land with H = 4, parcels with letters represent the four areas to be connected. In this case, it is necessary to buy four additional parcels. One of the possible solutions is marked by crosses.

    Input

    The input contains several scenarios. Each scenario begins with an integer number H,which specifies the size of the land, 2 <= H <= 20. Then there are 2.H - 1 lines representing individual "rows" of the land (always oriented as in the picture). The lines contain one non-space character for each parcel. It means the first line will contain H characters, the second line H +1, and so on. The longest line will be the middle one, with 2.H - 1 characters. Then the "length" descends and the last line contains H parcels, again.

    The character representing a parcel will be either a dot (".") for the land that is not owned by the investor, or one of the uppercase letters "A", "B", "C", or "D". The areas of parcels occupied by the same letter will always be connected. It means that between any two parcels in the same area, there exists a path leading only through that area.

    Beside the characters representing parcels, the lines may contain any number of spaces at any positions to improve "human readability" of the input. There is always at least one space between two letters (or the dots). After the land description, there will be one empty line and then the next scenario begins. The last scenario is followed by a line containing zero.

    Output

    For each scenario, output one line with the sentence "You have to buy P parcels.", where P is the minimal number of parcels that must be acquired to make all four areas connected together.

    Areas are considered connected, if it is possible to find a path between them that leads only through parcels that have been bought.

    Example

    Input:
    4
       B . . C
      . . . . C
     . A . . C .
    . A A . . . .
     . A . . . .
      . . . D D
       . . . .
    
    0
    
    Output:
    You have to buy 4 parcels.
    
    

    Added by:Rafal
    Date:2007-11-16
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set (classical)

    2053. Key Task

    Problem code: CERC07K

    The Czech Technical University is rather old - you already know that it celebrates 300 years of its existence in 2007. Some of the university buildings are old as well. And the navigation in old buildings can sometimes be a little bit tricky, because of strange long corridors that fork and join at absolutely unexpected places.

    The result is that some first-graders have often difficulties finding the right way to their classes. Therefore, the Student Union has developed a computer game to help the students to practice their orientation skills. The goal of the game is to find the way out of a labyrinth. Your task is to write a verification software that solves this game.

    The labyrinth is a 2-dimensional grid of squares, each square is either free or filled with a wall. Some of the free squares may contain doors or keys. There are four different types of keys and doors: blue, yellow, red, and green. Each key can open only doors of the same color. You can move between adjacent free squares vertically or horizontally, diagonal movement is not allowed. You may not go across walls and you cannot leave the labyrinth area. If a square contains a door, you may go there only if you have stepped on a square with an appropriate key before.

    Input

    The input consists of several maps. Each map begins with a line containing two integer numbers R and C (1 <= R, C <= 100) specifying the map size. Then there are R lines each containing C characters. Each character is one of the following:
    Hash mark '#' Wall
    Dot '.' Free square
    Asterisk '*' Your position
    Uppercase letter 'B','Y','R','G' Blue, yellow, red or green door
    Uppercase X 'X' Exit

    Note that it is allowed to have * more than one exit,
    * no exit at all,
    * more doors and/or keys of the same color, and
    * keys without corresponding doors and vice versa.

    You may assume that the marker of your position ("*") will appear exactly once in every map. There is one blank line after each map. The input is terminated by two zeros in place of the map size.

    Output

    For each map, print one line containing the sentence "Escape possible in S steps.", where S is the smallest possible number of step to reach any of the exits. If no exit can be reached, output the string "The poor student is trapped!" instead. One step is defined as a movement between two adjacent cells. Grabbing a key or unlocking a door does not count as a step.

    Example

    Input:
    1 10
    *........X
    
    1 3
    *#X
    
    3 20
    ####################
    #XY.gBr.*.Rb.G.GG.y#
    ####################
    
    0 0
    
    Output
    Escape possible in 9 steps.
    The poor student is trapped!
    Escape possible in 45 steps.
    
    

    Added by:Rafal
    Date:2007-11-16
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set (classical)

    2054. Gates of Logic

    Problem code: CERC07L


    The Department of Computer Science and Engineering runs courses dealing not only with algo- rithms but also with computer hardware. One such introductory course explains basic principles of integrated circuits ("chips"), binary logic, boolean algebra, etc. As you may know, the very basic units of logical circuits are called gates. A gate is an element performing one simple logical operation. It can be connected to other gates using lines.

    Logical circuits may be drawn as pictures with the gates represented as squares with inputs on the left and outputs on the right. In each square, there is a symbol that determines the gate type: Number 1 denotes an OR gate (its outputs are 0 if and only if there is no input with the value of 1), & is an AND gate (outputs are 1 if and only if there is no 0 input), and = is a XOR gate (outputs are 1 if and only if there is an odd number inputs that have the value of 1).

    Your task is to scan such a "picture" and compute values of all named circuit outputs. The lines may split and join again but you may assume that each "value consumer" (input port of a gate or a named output) will be connected to exactly one "value source" (output port of a gate or an input value). There will be no feedback loops, i.e., there exists no cycle that would lead through the same gate twice.

    Input

    The input contains several pictures. Each picture consists of at least one and at most 200 rows composed of the following characters:

    * Space (" "). Empty space in the picture. Spaces are used to indent other characters to appropriate locations, because the exact position of characters is often important. Trailing spaces at the end of input rows may be present but may also be left out.

    * Dash ("-"). Horizontal line. It connects characters on its left and right together, those characters will always exist and be able to "accept" the connection.

    * Pipe ("|"). Vertical line, connects characters that are directly above and below. Like with the horizontal line, those characters will always accept the connection.

    * Plus sign ("+"). Line connection or a bend. Connects characters on all four sides. All characters that are able to accept the connection are considered connected (there will always be at least two). However, there may be sides that contain a non-empty character that is not connected. For example, if a dash is present on a position directly below the plus sign, they are not considered connected.

    * Lowercase letter x ("x"). Crossing of two lines without a connection. All four neigh- boring characters will accept the connection. The character above is connected to the one below and the character to the left with the one on the right, but there is no mutual connection between these two pairs.

    * Equal sign ("="). Represents an input or output port. It always connects characters on its left and right, at least one of these characters is the port. If there is a port on the left, it may only be a value source. If there is a port on the right, it may only be a value consumer.

    * Lowercase letter o ("o"). Negation. There will always be a gate on the left and a port on the right of this character. It makes the particular gate output negated.

    * Hash mark ("#"). Gate, which has always a rectangular shape with two vertical and two horizontal sides. The left vertical side may be connected to input ports, the right side to output ports (possibly negated). No two gates will touch each other's side, which means that any two vertically or horizontally neighboring hash marks are always parts of the same gate.

    The rectangle size will always be at least 3 characters in both directions, which means there is at least one character inside. All inner characters are empty (spaces), with exactly one exception. That single non-empty character denotes the gate type (note that it may have different meaning than outside the gate area) and will be a digit "one" ("1"), ampersand ("&"), or an equal sign ("=").

    * Binary digit ("0"and"1"). Input value of the circuit. It is connected to the character on its right, which is always an equal sign.

    * Uppercase letter ("A" through "Z"). Named output of the circuit. It accepts connection from its left, which is always an equal sign. Each letter will appear at most once, which means the number of circuit outputs is between 0 and 26, inclusive. Each picture will be terminated by a row consisting solely of asterisk ("*") characters (at least one). The last picture will be followed by two such rows. No row in the input will be longer than 200 characters.

    Output

    For each picture, print the values of all named outputs, sorted alphabetically. Each output row should contain three characters: output name (one uppercase letter), equals sign, and a binary value (zero or one). Print one empty line after each test case.

    Example

    Input:
           0=+
             |
             | #######
             +=#     #
               # &   #o=--+
      1=------=#     #    |
               #     #    |
               #######    +--=### ###
                          |   #=#=#1#o==X
             1=-----------x--=# # ###
                     1=---x--=###
                          +------------=Y
    ***********************************
    1=A
    ***
    *
    
    
    Output:
    X=0
    Y=1
    
    A=1
    

    Added by:Rafal
    Date:2007-11-16
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set (classical)

    2055. Weird Numbers

    Problem code: CERC07N

    Binary numbers form the principal basis of computer science. Most of you have heard of other systems, such as ternary, octal, or hexadecimal. You probably know how to use these systems and how to convert numbers between them. But did you know that the system base (radix) could also be negative. One assistant professor at the Czech Technical University has recently met negabinary numbers and other systems with a negative base. Will you help him to convert numbers to and from these systems.

    A number N written in the system with a positive base R will always appear as a string of digits between 0 and R - 1, inclusive. A digit at the position P (positions are counted from right to left and starting with zero) represents a value of R^P. This means the value of the digit is multiplied by R^P and values of all positions are summed together. For example, if we use the octal system (radix R = 8), a number written as 17024 has the following value:

    1.8^4 + 7.8^3 + 0.8^2 + 2.8^1 + 4.8^0 = 1.4096 + 7.512 + 2.8+4.1 = 7700

    With a negative radix -R, the principle remains the same: each digit will have a value of (-R)^P. For example, a negaoctal (radix R = -8) number 17024 counts as:

    1.(-8)^4 + 7.(-8)^3 + 0.(-8)^2 + 2.(-8)^1 + 4.(-8)^0 = 1.4096 - 7.512 - 2.8+4.1 = 500

    One big advantage of systems with a negative base is that we do not need a minus sign to express negative numbers. A couple of examples for the negabinary system (R = -2):

    decimal negabinary decimal negabinary decimal negabinary
    -10
    -9
    -8
    -7
    -6
    -5
    -4
    1010
    1011
    1000
    1001
    1110
    1111
    1100
    -3
    -2
    -1
    0
    1
    2
    3
    1101
    10
    11
    0
    1
    110
    111
    4
    5
    6
    7
    8
    9
    10
    100
    101
    11010
    11011
    11000
    11001
    11110

    You may notice that the negabinary representation of any integer number is unique, if no "leading zeros" are allowed. The only number that can start with the digit "0", is the zero itself.

    Input

    The input will contain several conversions, each of them specified on one line. A conversion from the decimal system to some negative-base system will start with a lowercase word "to" followed by a minus sign (with no space before it), the requested base (radix) R, one space, and a decimal number N.

    A conversion to the decimal system will start with a lowercase word "from", followed by a minus sign, radix R, one space, and a number written in the system with a base of -R.

    The input will be terminated by a line containing a lowercase word "end". All numbers will satisfy the following conditions: 2 <= R <= 10, -1 000 000 <= N <= 1 000 000 (decimal).

    Output

    For each conversion, print one number on a separate line. If the input used a decimal format, output the same number written in the system with a base -R. If the input contained such a number, output its decimal value.

    Both input and output numbers must not contain any leading zeros. The minus sign "-"may only be present with negative numbers written in the decimal system. Any non-negative number or a number written in a negative-base system must not start with it.

    Example

    Input
    to-2 10
    from-2 1010
    to-10 10
    to-10 -10
    from-10 10
    end
    
    Output
    11110
    -10
    190
    10
    -10
    
    

    Added by:Rafal
    Date:2007-11-16
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set (classical)

    2056. Rectangular Polygon

    Problem code: CERC07P


    In this problem, we will help the Faculty of Civil Engineering. They need a software to analyze ground plans of buildings. Specifically, your task is to detect outlines of a building when all of its corners are given.

    example

    You may assume that each building is a rectangular polygon with each of its sides being parallel either with X or Y axis. Therefore, each of its vertex angles is exactly either 90 or 270 degrees.

    Input

    The input contains several buildings. The description of each building starts with a single positive integer N, the number of corners (polygon vertices), 1 <= N <= 1000. Then there are N pairs of integer numbers X_i,Y_i giving coordinates of individual corners, |X_i|, |Y_i| <= 10 000.

    You may assume that all corners are listed and no two of them have the same coordinates. The polygon does always exist, it is closed, its sides do not intersect or touch (except neighboring sides, of course), and it contains no "holes" inside. In other words, the outline is formed by one closed line. The order of corners in the input file may be arbitrary.

    There is an empty line after each building, then the next one is described. After the last building, there is a single zero that signals the end of input.

    Output

    For each building, output one line containing N characters without any whitespace between them. The characters should be uppercase letters that specify directions of individual walls (sides) when the building outline is followed. "N" stands for North (the positive direction of the Yaxis), "E" for East (the positive direction of the X axis), "W" for West, and "S" for South. The "walk" should start in the vertex that has been given first in the input and always proceed in the clockwise direction.

    Example

    Input
    4
    0 0
    2 2
    0 2
    2 0
    
    6
    1 1
    2 2
    0 1
    1 0
    0 2
    2 0
    
    0
    
    Output
    NESW
    WNESWN
    

    The second sample input corresponds to the picture.


    Added by:Rafal
    Date:2007-11-16
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set (classical)

    2058. Reaux! Sham! Beaux!

    Problem code: CERC07R

    Roshambo - this simple game is known all around the world. In German, it is called "Schnick, Schnack, Schnuck", in Japanese "Janken", in Spanish "Cachipún",in Polish "Papier, kamieñ, no¿yce". The Czechs call it "Kámen, nù¾ky, papír".

    Whatever is the name of the game, its principles remain the same. Two players simultaneously form their hand into one of three possible shapes (symbols): Rock (closed fist), Paper (open hand), or Scissors (two fingers extended). If both of them show the same symbol, it is a tie and no points are given. Otherwise, one of the symbols wins: Rock blunts Scissors, Scissors cut Paper, and Paper covers Rock.

    Czech Technical University students also know the game very well and use it to resolve small disputes. Imagine, for example, two students living together in one room. Yesterday evening, there was a small celebration, and in the morning, no one wants to go to the lectures. They agreed that one person would be enough to take notices for both, but who will be the poor one. Roshambo is a very effective way to decide.

    Did you know there are even the World Series of Roshambo. Our organizing team would like to host the World Championships in 2009. Your task is to help us in developing a Roshambo scoring system and write a program that evaluates one game between two players.

    Since the participants will come from different countries, the system must accept input in various languages. The following table shows names of three Roshambo symbols. Note that in some languages, there may be two different words for the same symbol.

    Language Code Rock Scissors Paper
    Czech
    English
    French
    German
    Hungarian
    Italian
    Japanese
    Polish
    Spanish
    cs
    en
    fr
    de
    hu
    it
    jp
    pl
    es
    Kamen
    Rock
    Pierre
    Stein
    Ko | Koe
    Sasso | Roccia
    Guu
    Kamien
    Piedra
    Nuzky
    Scissors
    Ciseaux
    Schere
    Ollo | Olloo
    Forbice
    Choki
    Nozyce
    Tijera
    Papir
    Paper
    Feuille
    Papier
    Papir
    Carta | Rete
    Paa
    Papier
    Papel

    Input

    The input contains several games. Each game starts with two lines describing players. Each of these two lines contains two lowercase letters specifying the language used by the player (see the language code in the table above), one space, and a player name. The name will consist from at most twenty upper- or lower-case letters.

    After the players description, there are at most 100 lines containing individual rounds. Each round is described by two words separated with one space. The words name the symbol shown by the first and second player, respectively. All symbols are named in the mother tongue of the concerned player. All allowed words are shown in the table above, the first letter will be always in uppercase, all other letters in lowercase.

    The last round is followed by a line containing one single dash character ("-") and then the next game begins. The only exception is the last game in the input, which is terminated by a dot (".") instead of the dash.

    Output

    For each game, print five lines of output. The first line should contain the string "Game #G:", where G is the number of the game, starting with one.

    The second line will contain the first player name followed by a colon (":"), one space and the number of rounds won by that player. The number should be followed by one space and the word "points". Use the singular form "point" if (and only if) the number of points of the player equals one.

    The third line has the same format and shows the second player's name and points.

    The fourth line displays the outcome of the game. It must contain the word "WINNER" followed by a colon, space and the name of the player who gained more points. If both players have the same number of points, the fourth line will contain words "TIED GAME" instead.

    The fifth line is left empty to visually separate individual games.

    Example

    Input
    cs Pepik
    en Johnny
    Nuzky Scissors
    Papir Rock
    Papir Scissors
    -
    de Gertruda
    cs Lenka
    Stein Papir
    Schere Kamen
    .
    
    Output
    Game #1:
    Pepik: 1 point
    Johnny: 1 point
    TIED GAME
    
    Game #2:
    Gertruda: 0 points
    Lenka: 2 points
    WINNER: Lenka
    
    

    Added by:Rafal
    Date:2007-11-16
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set (classical)

    2059. Robotic Sort

    Problem code: CERC07S

    Somewhere deep in the Czech Technical University buildings, there are laboratories for examin- ing mechanical and electrical properties of various materials. In one of yesterday's presentations, you have seen how was one of the laboratories changed into a new multimedia lab. But there are still others, serving to their original purposes.

    In this task, you are to write software for a robot that handles samples in such a laboratory. Imagine there are material samples lined up on a running belt. The samples have different heights, which may cause troubles to the next processing unit. To eliminate such troubles, we need to sort the samples by their height into the ascending order.

    Reordering is done by a mechanical robot arm, which is able to pick up any number of consecutive samples and turn them round, such that their mutual order is reversed. In other words, one robot operation can reverse the order of samples on positions between A and B.

    A possible way to sort the samples is to find the position of the smallest one (P_1) and reverse the order between positions 1 and P_1, which causes the smallest sample to become first. Then we find the second one on position P_2 and reverse the order between 2 and P_2. Then the third sample is located etc.

    example

    The picture shows a simple example of 6 samples. The smallest one is on the 4th position, therefore, the robot arm reverses the first 4 samples. The second smallest sample is the last one, so the next robot operation will reverse the order of five samples on positions 2-6. The third step will be to reverse the samples 3-4, etc.

    Your task is to find the correct sequence of reversal operations that will sort the samples using the above algorithm. If there are more samples with the same height, their mutual order must be preserved: the one that was given first in the initial order must be placed before the others in the final order too.

    Input

    The input consists of several scenarios. Each scenario is described by two lines. The first line contains one integer number N, the number of samples, 1 <= N <= 100 000. The second line lists exactly N space-separated positive integers, they specify the heights of individual samples and their initial order.

    The last scenario is followed by a line containing zero.

    Output

    For each scenario, output one line with exactly N integers P_1,P_2,...P_N, separated by a space. Each P_i must be an integer (1 <= P_i <= N) giving the position of the i-th sample just before the i-th reversal operation.

    Note that if a sample is already on its correct position P_i, you should output the number P_i anyway, indicating that the "interval between P_i and P_i" (a single sample) should be reversed.

    Example

    Input
    6
    3 4 5 1 6 2
    4
    3 3 2 1
    0
    
    Output
    4 6 4 5 6 6
    4 2 4 4
    
    

    Added by:Rafal
    Date:2007-11-16
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set (classical)

    2060. Tough Water Level

    Problem code: CERC07W

    Czech Technical University has the word "technical" in its name. Beside others, this means that lectures in physics are important here. Do you still remember some of the basic physical principles.

    For example, imagine a simple glass of water. Or, we will rather call it a cup to avoid ambiguity of this word. So, imagine a simple cup (made of glass) that is partially filled with water. You might have noticed that the stability of such a cup depends on the amount of water inside. If you brush against a full cup, it is relatively easy to knock it down and spill its contents. If the cup is empty, there is fortunately nothing to be spilled, but other than that, the situation does not improve much - it is still easy to knock the cup down with only a little force. The best stability is usually achieved with a "half-full" cup.

    In this problem, your task is to determine the water level that makes a cup as much stable as possible. For the purpose of this problem, we will make a simple assumption that the "stability" of a cup is higher, if its center of mass (sometimes also called the center of gravity) is lower (closer to the bottom).

    The center of mass can be informally defined as follows: Imagine that glass and water consist of a very large number of very small particles. Then the center of mass is an average of the position of all these particles. The average is weighted by particle masses. Since the density of glass is approximately 2 500 kg.m-3 and the density of water only 1 000 kg.m-3, we will suppose that the mass of a glass particle is 2.5 times higher than the mass of a water particle of the same size.

    All cups considered in this problem will have an exact rotary shape. But their radius may vary with the height - some cups are wider at the top, others are wider at the bottom. Also, the thickness of the glass may not be constant.

    example

    The left figure shows a typical cup considered in this problem. It can be fully described by its height (H), thickness of the bottom (B), and two functions R and T . Both of these functions take a current height as their argument and they give the outer radius (R) and glass thickness (T ) in the appropriate height. Please note that the thickness is always measured strictly horizontally and may therefore not reflect the "real thickness" of the glass in its usual meaning.

    Input

    The input contains several cup descriptions. Each description consists of three lines. The first line contains two numbers: H (cup height) and B (bottom thickness), 0 < B < H <= 100. The second line contains an expression R(x) (radius), the third line an expression T (x) (glass thickness). All data are given in centimeters. The last description is followed by a line with two zeros.

    The expressions will contain only digits ("0" through "9"), decimal points ("."), four basic operators ("+", "-", "*", and "/"), parentheses ("("and")"), and the lowercase letters "x" denoting the input variable (height measured from the cup bottom).

    Vx, 0 <= x <= H, the radius will satisfy: 0.1 < R(x) <= 100

    Vx, B <= x <= H, the thickness will satisfy: 0.1 <= T (x) < R(x)

    Arithmetical operators have their usual meaning and priorities, i.e., multiplication and division have a higher priority than addition and subtraction.

    Output

    For each cup, output the sentence "Pour L litres / W cm of water.", where L is the amount of water that must be poured into the cup to reach the maximal stability (in litres). W is the water level (in centimeters) measured from the bottom of the cup. Both numbers must be given with exactly three decimal digits.

    Example

    
    Input
    9 1
    3+x/6
    17/8-x/8
    10 1
    (x+10)
    10/(x+10)
    0 0
    
    Output
    Pour 0.030 litres / 3.365 cm of water.
    Pour 0.878 litres / 2.193 cm of water.
    

    Added by:Rafal
    Date:2007-11-16
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Central European Programming Contest, Prague 2007









    SPOJ Problem Set (classical)

    2070. Minimum Distance

    Problem code: MINDIST

    Given an weighted tree, you are to find two nodes A and B of the tree(A and B needn't to be different), such that the length of the path between A and B is less than or equals to a given integer S, and the maximum distance from each node of the tree to this path is minimum.

    Input

    The first line of the input contains a single integer T, the number of test cases. T blocks follow.

    For each test case, the first line contains two space-separated integer N (1<=N<=100000) and S(0<=S<=100000000).N-1 lines follow, each contains three integers X(1<=X<=N), Y(1<=Y<=N) and Z(1<=Z<=1000), denotes that there is an (undirected) edge weighted Z between node X and Y. The input is correct.

    Output

    T lines, each contains a single integer denoted the minimum distance.

    Example

    Input:
    2
    5 2
    1 2 5
    2 3 2
    2 4 4
    2 5 3
    8 6
    1 3 2
    2 3 2
    3 4 6
    4 5 3
    4 6 4
    4 7 2
    7 8 3
    
    Output:
    5
    5
    
    
    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-11-19
    Time limit:15s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:description by Blue Mary; standard program and test data by g201513









    SPOJ Problem Set (classical)

    2123. Candy I

    Problem code: CANDY

    Jennifer is a teacher in the first year of a primary school. She has gone for a trip with her class today. She has taken a packet of candies for each child. Unfortunatelly, the sizes of the packets are not the same.

    Jennifer is afraid that each child will want to have the biggest packet of candies and this will lead to quarrels or even fights among children. She wants to avoid this. Therefore, she has decided to open all the packets, count the candies in each packet and move some candies from bigger packets to smaller ones so that each packet will contain the same number of candies. The question is how many candies she has to move.

    Input specification

    The input file consists of several blocks of data. Each block starts with the number of candy packets N(1<= N <=10000) followed by N integers (each less than 1000) in separate lines, giving the number of candies in each packet. After the last block of data there is the number -1.

    Output specification

    The output file should contain one line with the smallest number of moves for each block of data. One move consists of taking one candy from a packet and putting it into another one. If it is not possible to have the same number of candies in each packet, output the number -1.

    Example

    Input file:
    5
    1
    1
    1
    1
    6
    2
    3
    4
    -1
    
    Output file:
    4
    -1
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 1999









    SPOJ Problem Set (classical)

    2124. Last Non-Zero Digit of Factorials

    Problem code: FCTRL4

    Tom is fascinated by big numbers. Most of all he likes factorials. First, he computed N! for some small values of N. But factorials were getting longer and longer very quickly and each of them had a long sequence of zeroes at its end. Since he was unable to consider so many digits in his research and he thought that the research on zeroes would be boring, he decided to focus on the last non-zero digit of factorials.

    For example 4!=24 so the last non-zero digit is 4. For N=5 we have 5!=120 and the last non-zero digit 2.

    Tom needs to know the last non-zero digit of N! for several specific values of N. Help him please.

    Input specification

    The input file consists of several positive integers (less than 10100) delimited by whitespace.

    Output specification

    The output file contains the last non-zero digit of N! for each integer N from the input file. Digits should be delimited by whitespace.

    Example

    Input file:
    1
    2
    3
    4
    5
    6
    7
    8
    
    Output file:
    1
    2
    6
    4
    2
    2
    4
    2  
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 1999









    SPOJ Problem Set (classical)

    2125. Number Labyrinth

    Problem code: LABYR2


    Fred is a robotic mouse built by a group of students of artificial intelligence. Fred can move around in the labyrinth shown in the picture below. Whenever Fred comes to a place marked by a number, he has to choose one of the possible directions. Behavior of the mouse should look chaotic and complex enough so that it will impress students' supervisor.

    +--------4
    |        |
    |  8--9  |
    |  |  |  |
    2--7--0  |
    |  |     |
    1  6-----+
    

    Numbered places in the labyrinth are called nodes. Fred has one integer X stored in its memory and can perform some calculations. In each node (except node 1) he chooses a direction according to X, decreases X by 1 and goes to the chosen node. The direction is chosen according to this rules:

    Node 2: Compute X mod 3.
            If the result is 0, go to 7
                             1, go to 1
                             2, go to 4.
    
    Node 4: Let Y be X written backwards (in decimal system).
            If Y>X then go to 6 otherwise go to 2.
    
    Node 6: Compute the number of digits of X (in decimal system).
            If the result is even then go to 4 otherwise go to 7.
    
    Node 7: Compute (X*X) mod 7.
            If the result is 0 go to 2
                             1 go to 6
                             2 go to 8
                             4 go to 0.
    
    Node 8: Compute X mod 5.
            If the result is 2 or 3 then go to 7 otherwise go to 9.
    
    Node 9: If you have come from 8 then go to 0.
            If you have come from 0 then go to 8.
    
    Node 0: Let Y be the third least significant digit of X in decimal system
            (if X<100 then Y=0). If Y<=7 then go to 7 otherwise go to 9. 
    

    At the beginning of each experiment, the experimenter puts the mouse in the node 0 and initializes value X by voice. After that, the mouse starts to move. The mouse displays current value of X on its digital display. The experiment finishes when the mouse enters the node 1, the result of the experiment is the number displayed. If the value of X decreases to zero, the experiment fails and its result is -1.

    Input file description

    The input file contains several initial values of X(less than two-million) as they were told by the experimenter.

    Output file description

    For each value of X in the input file write to a separate line of the output file the result of the corresponding experiment (see example output).

    Example

    Input file:
    thirteen
    fourteen
    one-thousand
    one-million-three-hundred-and-twenty-five-thousand-nine-hundred-and-seventy-nine
    
    Output file:
    -1
    9
    789
    1325784
    

    Blue Mary's Note: new test cases were added on Jun.6, 2008.

    Another Note: One of the test cases has something wrong & it has been fixed in Jul. 19, 2008. Thanks to Robert Gerbicz and Stephen Merriman's discussion in the forum.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 1999









    SPOJ Problem Set (classical)

    2127. Rain

    Problem code: RAIN3

    Doctor Jones is a famous archeologist. He did some research on the Tiribaki Islands recently. His most famous discovery was the Meteoronome - a machine with a yellow button used by the Tiribakian highest priest to predict the weather. The Meteoronome had been set up by the gods at the Beginning of Time. Tiribakians pressed the button every day. As a result, the Meteoronome produced a number - the expected rainfall in millimetres for the next day. More precisely, after i button hits (counted since the Beginning of Time) Meteoronome gives the expected rainfall for the day i since the Beginning of Time.

    Unfortunately, the Meteoronome has not been used for several thousands of years and nobody knows how many steps should be performed to reach the current date. Researchers have spent a lot of effort to find out how the Meteoronome works. A mathematical model has been proposed: The Meteoronome is initialized by a pair of integers, s[0] and t[0]. For the i-th step, the Meteoronome computes the values

    s[i] = (78901 + 31*s[i-1]) mod  699037
    t[i] = (23456 + 64*t[i-1]) mod 2097151
    

    The output of the i-th step is the number

    a[i]=(s[i] mod 100 + 1) * (t[i] mod 100 + 1)
    

    Doctor Jones's friend, Ms. Linda Watson, is now planning a holiday on Tiribaki Islands. She would like to stay there as long as possible but she hates the rain. She can stand no more than M millimetres of rainfall during her entire stay on Tiribaki.

    Doctor Jones wants to help his friend and to compute the longest period which she can safely stay on Tiribaki. He simulated N steps of the Meteoronome. This way, he obtained a sequence of numbers a[1],a[2],...,a[N] which represent predictions for N subsequent days. Now he wants to find the largest K such that for each period of at most K subsequent days from day i to day j the sum of the predictions a[i]+a[i+1]+...+a[j] is less than or equal to M. Linda can be sure that if she stays on Tiribaki for at most K days, she can endure the rain (provided that N is large enough).

    Input specification

    The input file consists of several blocks of data. The first line of the input file contains the number of blocks. Each block contains four integers delimited by whitespace: s[0], t[0] - the initial values for the Meteoronome, N (1<= N <=1500000)- the length of the sequence and M - the maximum sum of a subsequence. All the input data fits into 32-bit signed integer.

    Output specification

    The output file contains one line for each block of input data. In this line there is a single integer K as specified above.

    Example

    Input file:
    1
    123456 123456 10 10000
    
    Output file:
    2
    

    Note, that the sequence produced by Meteoronome for this input file is 4664,1248,267,4900,837,4048,990,6935,1155,490. No subsequence of length 2 has sum greater than 10000 and there are subsequences of length 3 with greater sum.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 1999









    SPOJ Problem Set (main)

    2128. K-In-A-Row

    Problem code: KROW

    Hansel and Gretel do not listen to their teacher at school. Instead they secretly play a game called K-In-A-Row. One day in the evening they started to argue who had won more games that day. They collected all the papers they had used for playing the game and they started to count how many times each of them had won. But it was very tedious and they were sleepy. Help them to count how many games each of them had won.

    K-In-A-Row is played in a square grid with M times N squares. Two players alternate in their moves. A player chooses an empty square and fills in his/her sign (Hansel uses cross 'x' and Gretel uses circle 'o'). The game is won by the player who first places at least K his/her own signs in a row (either horizontally, vertically or in one of the two diagonal directions). The game stops immediately after one of the players completes K of his/her signs in a row; thus it may never happen that both players have completed K of their signs in a row. If no player creates such a row, nobody wins.

    Input file specification

    The first line contains the number of games L. It is followed by L blocks, each describing one game. Each block starts with a line containing 3 numbers M, N and K. Numbers M and N give the size of the grid (M,N<200) and K is the length of the required row. The following N lines each containing M characters describe the situation after the end of the game. Character '.' denotes an empty field, characters 'x' and 'o' denote fields marked by Hansel and Gretel respectively. You may assume that the input is correct.

    Output file specification

    The output file consists of two numbers separated by a colon ':'. The first number denotes the number of the games won by Hansel, the second one gives the number of the games won by Gretel.

    Example

    Input file:
    2
    3 3 3
    .x.
    .xo
    oox
    4 7 4
    ....
    ..x.
    ooox
    oxx.
    oox.
    o.ox
    ..xx
    
    Output file: 
    0:1
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
    Resource:IPSC 2000









    SPOJ Problem Set (classical)

    2129. Cake

    Problem code: CAKE2

    Some time ago a VERY huge cake was made in the village called Nalomena Trieska. Well, it was infinitely large and infinitely thin. For our needs it looked exactly like an infinite plane. It was not very tasty, so nobody wanted to eat it. Instead, local children started to play with it. Each of them drew one straight line on the plane. These lines divided the plane into many parts. For a few hours the children were happy, they jumped from one part into another and played other similar games. But then little Tommy suddenly asked: "How many parts does the cake have?" "1999." answered Martin. "No, 2000 !" replied Richard. "Well, I think it's only 1748." stated Michael. And they started to argue. Now their parents need your help, because the children spend all their time counting the parts of the cake.

    Input file specification

    The first line of the input file contains the number of straight lines N(N<=3000). Each of the next N lines contains four integers x1,y1,x2,y2 (the absolute value of each number is at most 10000). These integers are the coordinates of two different points in the plane [x1,y1] and [x2,y2]. These two points determine one straight line in the plane. You can assume that no two straight lines are the same.

    Output file specification

    The output file contains a single integer giving the number of parts into which given N lines divide the plane.

    Example

    Input file:
    4
    5 0 0 5
    4 0 4 5
    2 4 3 4
    1 1 1 5
    
    Output file:
    9
    
    Added some unofficial test cases.
    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s-7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2000









    SPOJ Problem Set (classical)

    2130. Trolls

    Problem code: TROLLS


    In a secret forest, there are many trolls. They are intelligent and most of them even knows programming languages C or PASCAL. They have written many programs. With their super computers, their programs will run for a very short time and they can get the correct answer. Being an excellent programmer, you can even come up with the answer without computers!!!

    Input

    There's no real input file. The four programs can be downloaded here.

    Output

    For program1.txt and program2.txt in the zip file:

    Your output should contain a single integer denoting the number of "*" the program will output.

    For program3.txt and program4.txt in the zip file:

    Your output should contain a single integer denoting the number the program will output.

    You can merge the 4 output lines together to get the real output file and submit it.

    Example

    If program1.txt is

    var i:integer;
    begin
      for i:=2 to 8 do write('*');
    end.
    
    #include <stdio.h>
    void main() {
      int i;
      for(i=2; i<=8; i++) printf("*");
    }
    

    The corresponding line should be:

    7
    

    If program3.txt is

    var a, i: integer;
    
    begin
      a := 0;
      for i:= 1 to 9 do
        a := a * 10 + i;
      writeln(a);
    end.
    
    
    #include <stdio.h>
    
    void main() {
      int i, a;
      a = 0;
      for(i=1; i<=9; i++)
        a = a * 10 + i;
      printf("%d\n", a);
    }
    

    The correspoding line should be

    123456789
    

    Note

    The numbers fit into the type "int" in C program or "integer" in PASCAL program in the zip file can be arbitrarily large because the computers used by trolls are super computers.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:TEXT
    Resource:IPSC 2000 and IPSC 2001









    SPOJ Problem Set (classical)

    2131. Get Back!

    Problem code: GETBACK

    Somewhere deep in a desert lives a small, completely forgotten tribe N'Gubara. All the men, women and children of the tribe live with a few camels in the N'Gubara oasis (the N'Gubara people don't have great creativity when it comes to geography names). These poor people have only the N'Gubara well, a few acres of irrigated land and the N'Gubara cave. Yes, the cave.

    You do not remember exactly how you have come to N'Gubara. Maybe your car broke when you travelled across the desert. Maybe you jumped out of an airplane. Maybe you were brought here by Martians. But this does not matter now. You know that you are here, pretty far from any civilization. And you desperately want to go home.

    The only possibility how to get home is to walk across the desert to Desertville, the closest city. You have to use paths in the desert shown in your map. Each such path connects two restpoints. The N'Gubara oasis and Desertville are also considered to be restpoints. You can walk, but you need water. For each mile travelled, you have to drink one unit of water. You are able to carry at most C units of water at once. Thus, you can never walk more than C miles without replenishing your water supply. The shortest way to Desertville is probably much longer than C miles. It would thus seem that you will stay in N'Gubara forever, but there's a trick: at the end of each path, there is a restpoint with an empty water reservoir. You can transport water into a reservoir from N'Gubara or from other reservoirs where you stored some water previously. You can then use the stored water later on (the water doesn't evaporate). Of course, you can take only as much water from any reservoir as you brought into it. You may use as much water from the N'Gubara oasis as you need, but since water is very valuable in the desert, you promised that you will use only the minimal amount needed for your return to Desertville. In this task, we want you to compute the minimal amount of water you need.

    Input file specification

    Input contains several test cases, the number of them is given in the very first line.

    The first line contains three integers N, M and C, where N is the number of the restpoints, M is the number of the paths and C is your carrying capacity. M lines follow, each describing one path on the map. Each line contains three numbers x, y and l, where x and y are the restpoints joined by a path and l is the length of that path in miles. The restpoints are numbered from 1 to N, where restpoint 1 is the N'Gubara oasis and restpoint N is Desertville.

    You may assume all the numbers in the input file are non-negative integers less than 100.

    Output file specification

    For each test case:

    Your output file should contain a single integer - the minimum amount of water needed for you to get from N'Gubara to Desertville. If there is no possibility how to get to Desertville with your current carrying capacity C, you should output the number -1.

    Example

    Input file:
    1
    9 10 25
    1 2 3
    2 3 12
    3 4 4
    3 5 9
    4 9 13
    5 9 5
    2 6 10
    6 7 10
    7 8 10
    8 9 10
    
    Output file:
    65
    

    Note: You can get to Desertville as follows: first you take 25 units of water from N'Gubara, go to restpoint 2, leave there 19 units in the reservoir and go back to N'Gubara. Then you repeat this trip, bringing additional 19 units to restpoint 2. Last, you take 15 units from N'Gubara to restpoint 2. Now you have 19+19+12 = 50 units of water here. You take a round trip to point 3 and back, leaving there 1 unit of water. Now you take all water left from point 2, go to point 3, take the one unit from point 3 (now you have 25-12+1=14 units) and go via restpoint 5 to Desertville.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2000









    SPOJ Problem Set (classical)

    2132. Puzzle

    Problem code: PUZZLE2

    Sam loves all kinds of puzzles. Recently he received a very special puzzle - a grid of N x M squares, each square is occupied either by a red or by a blue pebble. The puzzle is controlled by several buttons.

    Each row of the grid has its corresponding black button. When you press a black button, a complicated mechanism of the puzzle flips the colors of all pebbles in the row corresponding to that button (all red pebbles in this row become blue and vice versa).

    Each column of the grid has its corresponding white button. When you press exactly two white buttons simultaneously, the puzzle mechanism exchanges the contents of the two columns corresponding to those buttons without changing the order of the pebbles in the columns.

    Sam has found the puzzle very interesting. Unfortunately, he lent it to his daughter Ann yesterday. She was able to understand the idea of the puzzle very quickly and she gave him this teasing task. She drew two arrangements - initial and final and she changed the colors of the pebbles according to the initial arrangement. Sam's task is to decide whether there exists a sequence of puzzle operations which transforms the initial arrangement of the puzzle to the final arrangement.

    Input file specification

    The input file contains several blocks of input data. The first line of the input file contains K - the number of blocks. The first line of each block contains integers N(1<=N<=100) and M(1<=M<=100). Each of the next N lines contain M words (either RED or BLUE), describing the initial Ann's arrangement of the colors of the pebbles. One blank line follows. The next N lines contain M words corresponding to the final arrangement of the colors.

    Output file specification

    The output file contains K lines, the i-th line corresponds to the i-th block of the input data. Each line contains either YES or NO, the answer to the Ann's question.

    Example

    Input file:
    2
    3 4
    BLUE RED BLUE RED
    RED BLUE BLUE RED
    BLUE BLUE BLUE BLUE
    
    BLUE RED BLUE RED
    RED RED BLUE BLUE
    BLUE BLUE BLUE BLUE
    2 2
    BLUE BLUE
    BLUE RED
    
    RED RED
    RED RED
    
    Output file 
    YES
    NO
    
    

    Note: In the first block of the input data it suffices to use the black button for the second row and then to press the white buttons for the first and the third columns simultaneously.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2000









    SPOJ Problem Set (classical)

    2136. Candy II

    Problem code: CANDY2


    Little Michael loves candies. Most of all, he likes chocolate, strawberry and banana flavored ones. No wonder that he has candy bags everywhere - there are at least four bags on his table, one or two in the pockets of his jeans, and one under his bed (just in case). Each bag contains some candies of all three flavors. Whenever he wants to eat a candy, he finds the nearest bag (which is usually is not very far because he has really A LOT of them) and eats the candy he wants.

    Yesterday, he wanted a strawberry one, so he opened one of his bags and... It is almost impossible to describe how great his disappointment was when he found out that there were no strawberry candies left in that bag. To make the matters worse, there were also none in the second bag he found. He was sure that he had lots of strawberry candies left, but he didn't know in which bags they were. Therefore, he decided to reorganize his candies, and keep the candies of the three different flavors in three distinct bags. He brought all his bags into the center of his room and realized, that there are really an awful lot of them.

    Michael has N bags full of candies. He knows the number of candies of each flavor in each bag. He wants to put all chocolate ones into one bag, all strawberry ones into another bag and all banana ones into yet another bag. He has to move the candies one-by-one, because he always has to look at it to determine its flavor. Moving one candy from one bag into another takes 1 second. Your task is to select the bag for each flavor, so that the total time required for Michael to move all the candies into their bags would be minimal.

    Input file specification

    The first line of the input file contains a single integer N - the number of bags (N<=5000). Each of the following N lines consists of three numbers ci, si, bi - the numbers of chocolate, strawberry and banana candies in the i-th bag. The bags are numbered from 0 to N-1 in the order in which they appear in the input.

    Output file specification

    Output file should contain three lines with the following text:

    C[Bag for chocolate candies]
    S[Bag for strawberry candies]
    B[Bag for banana candies]
    

    The numbers C, S, B have to be such that the total number of the required moves is minimal. If there are more solutions, you may choose any of them.

    Example

    Input file:
    5
    10 10 10
    40 39 40
    10 20 30
    30 20 10
    1 2 27
    
    Output file:
    3
    1
    2
    

    Note: In this case Michael has to move 200 candies. If the bags for the different flavors were chosen in any other way, he would have to move more than 200 candies.

    Note: the test data is very naive for this problem.
    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2001









    SPOJ Problem Set (classical)

    2138. Pibonacci

    Problem code: PIB

    You might have heard of the Fibonacci numbers and of the number pi. If you let these two ideas merge, a new and esoteric concept comes into being: the Pibonacci numbers. These can be defined for real x>=0 by:

    P(x) = 1 for 0<=x<4
    P(x) = P(x-1) + P(x-pi) for 4<=x,

    where pi = 3.1415926535... In this problem, you are asked to compute P(x) for a given x.

    Input file specification

    The input file contains several non-negative integer numbers (less than 30000) each on a separate line. The last line contains -1 marking the end of the input file.

    Output file specification

    For each non-negative real number in the input file, output the corresponding Pibonacci number. If the Pibonacci number be more than 50 digits long, divide it on the consecutive lines, outputting 50 digits on each (the last line may contain less digits).

    Example

    Input file:
    0
    4
    11
    -1
    

     

    Output file:
    1
    2
    20
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:42s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2001; standard program and test data by Blue Mary









    SPOJ Problem Set (classical)

    2139. Gossipers

    Problem code: GOSSIPER


    Doulnee Keltchow is a small town in the middle of nowhere; what makes it so famous is the number of gossipers who live there. Every morning, each gossiper finds out a new gossip, a gossip so unique that nobody else in the town knows it. The gossipers talk, gossip and exchange rumors all day long. What happens when two gossipers meet? Of course, they exchange all the gossips they have heard so far. Your task is to determine whether every gossiper will know all the gossips by the end of the day.

    Input file specification

    The input file consists of multiple test cases separated by blank lines. On the first line of every test case there are two positive integers N(1<=N<=2100) and M(1<=M<=12000), where N is the number of gossipers and M is the number of meetings. On the next N lines there are the names of the gossipers. The name of each gossiper is a single word consisting of lower- and uppercase letters. The following M lines describe the meetings in the order they happened. Each meeting is described by two distinct names of the gossipers separated by a single space. The values M=N=0 indicate the end of the input file.

    Output file specification

    The output file should contain for each test case one line containing a single word "YES" if every gossiper knows all the gossips, or "NO", otherwise.

    Example

    Input file:
    3 3
    Alice
    Bob
    Cindy
    Alice Bob
    Bob Cindy
    Cindy Alice
    
    4 4
    Kirk
    Lucy
    Mike
    Nancy
    Kirk Lucy
    Lucy Mike
    Mike Nancy
    Nancy Lucy
    
    0 0
    
    Output file:
    YES
    NO
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2001









    SPOJ Problem Set (classical)

    2140. (un)Fair Play

    Problem code: FAIRONOT

    It is not an easy job to be a coach of a football team. Especially if you do not coach great teams like Ajax, Inter, Dynamo (ok, fill in the name of your dream team), but only a mediocre one like FC Dead Horse, playing in the second league. The season is almost over, only a few matches are left to play. All of sudden the team manager comes to you and tells you bad news: the main sponsor of your club is not happy with your results and decided to stop sponsoring your team, which probably means the end of your club. The sponsor's decision is final and there is no way to change it unless... unless your team miraculously wins the league.

    The manager left you in deep thought. If you increase the number of practices and offer players a generous bonus for each match, you may be able to win all the remaining matches. Is that enough? You also have to make sure that teams with many points lose against teams with few points so that in the end, your team will have more points than any other team. You know some of the referees and can bribe them to manipulate the result of each match. But first you need to figure out how to manipulate the results and whether it is possible at all.

    Problem Description

    There are N teams numbered 1 through N, your team has the number N. The current number of points of each team and the list of remaining matches are given. Your task is to find out whether it is possible to manipulate each remaining match so that the team N will finish with strictly more points than any other team. In every match, the winning team gets 2 points, the losing team gets 0. If the match ends with a draw, both teams get 1 point.

    Input file specification

    The input file consists of several blocks. Each block has the following form: The first line contains two numbers N(1<= N <=100) and M(0<= M <=1000). The next line contains N numbers separated by spaces giving the current number of points of teams 1, 2, ..., N respectively. The following M lines describe the remaining matches. Each line corresponds to one match and contains two numbers a and b (a not equal to b) identifying the teams that will play in the given match. The last block is followed by a "-1"(without quotes) on a separate line.

    Output file specification

    For each block in the input file, output YES if you can manipulate the remaining matches so that the team N would win the league, or NO otherwise.

    Example

    Input file:
    5 8
    2 1 0 0 1
    1 2
    3 4
    2 3
    4 5
    3 1
    2 4
    1 4
    3 5
    5 4
    4 4 1 0 3
    1 3
    2 3
    3 4
    4 5
    -1
    
    Output file:
    YES
    NO
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2002









    SPOJ Problem Set (classical)

    2141. Golden Garden

    Problem code: GARDEN


    Little Jelly is playing in the Golden Garden alone. She is such a pretty girl that the Evil Uncle wants to catch her. The Evil Uncle drives his flying saucer over the Golden Garden and trys to inhale Little Jelly.

    It is known that the Golden Garden is a perfect rectangle and the Evil Uncle's flying saucer can inhale her if and only if she is in a circle with a certian radius around the flying saucer.

    Your task is to avoid the Evil Uncle catching Little Jelly. First of all, you should find out the common area of the gardan and the inhaling circle.

    Input

    There are multiple test cases in the input file. First line of each test case are three integers x, y and r, For the coordinate of the center of the inhaling circle.

    The second line contains four integers x1, y1, x2 and y2. Which are the coordinate of the Gold Garden. The Gold Garden is such a perfect rectangle so that its sides are parallel to the axis.

    All numbers in the input are integers and do not reach 1000 by their absolute values. Sides of the Golden Garden are non-zero.

    Output

    For each test cases, output only one line with one real number which is the common area of the garden and the circle. Your answer must be accurate up to 0.000001.

    Note

    There are two input files for this problem. If you get Wrong Answer, click on the "wrong answer" to get more details. For each test file, my judge will give you the id of the test case for which your program gives a wrong response.

    Example

    Input:
    0 0 5
    3 3 7 7
    
    Output:
    0.547426365104
    
    Warning: enormous input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:7s-13s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Description, standard program & test data by g201513









    SPOJ Problem Set (classical)

    2142. Arranging Flowers

    Problem code: FLOWERS

    Bratislava has a long tradition in organizing an international flower exhibition – Flora. Professor Andrew as a true flower lover visited the Flora exhibition also this year. He was pleased by the most beautiful flowers and other plants of the world – roses, orchids, magnolias, cactuses. All flowers were nicely arranged.

    The flower arrangement that was the most appealing to him (at least mathematically) was composed of many kinds of flowers arranged in a rectangular grid, such that each row of the grid contained each kind of flowers exactly once and each column of the grid contained each kind of flowers at most once.

    Professor Andrew is a good mathematician and soon he realized that the number of columns of the grid has to be the same as the number of different kinds of flowers in the arrangement. But soon he encountered a problem he was unable to solve: He would like to add more rows of flowers to the arrangement without violating the rules stated above. (Note that he may not modify the existing rows and therefore he may not use any new kinds of flowers in the new rows.) Help him add as many rows as possible!

    Input file specification

    The input data set describes several flower arrangements; on the first line their number is given. Each flower arrangement description begins with two positive integers N(1<= N <=220) and M, representing the number of columns and rows of the grid. The different kinds of flowers are represented by numbers 1,2,...,N. The following M lines contain N integers each representing the kinds of flowers in one row of the arrangement.

    Output file specification

    For each flower arrangement, output K in the first line, then print K lines containing N numbers each, where K is the maximum number of lines that can be added to the arrangement, describing the added rows. The numbers in the output file may be separated by exactly one space. If there are mutiple number of solutions, you must output the lexicographically first solution.

    Print a blank line after each test case.

    There is no special judge program for this problem.

    Example

    Input:
    2
    
    3 2
    3 2 1
    1 3 2
    
    4 2
    1 4 3 2
    2 1 4 3
    
    Output:
    1
    2 1 3
    
    2
    3 2 1 4
    4 3 2 1
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:35s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2003









    SPOJ Problem Set (classical)

    2143. Dependency Problems

    Problem code: DEPEND


    We bought a brand new computer and now we would like to install an operating system. The only problem is that our chosen operating system consists of many packages and they cannot be installed in an arbitrary order. E.g. you cannot install the package tuxracer, which depends on the package libSDL, before you install libSDL. But libSDL can depend on another packages and so on. The packages may only be installed one at a time. You may install a package only if you already installed all packages it depends on. Your task is to determine how many packages can be installed on our computer.

    Input file specification

    The input file contains a single line for each available package. The line for each package P begins with the name of the package. The name of each package is a non-empty string of printable characters containing no spaces. Following the name of the package P is the dependency list of P. The dependency list is simply a list of names of packages that P depends on, separated by spaces. A whitespace followed by a single 0 (zero) is at the end of each line. You may assume that no package has the name '0'.

    The dependency list of a package P may be empty; in that case, P does not depend on any packages and may be installed immediately. It is possible that a package Q occurs in the dependency list of a package P more than once; this merely means that P depends on Q, nothing more. Only the packages that have a dependency list in the input file are available and may be installed. It is possible that a package P depends on a package that is not available. Such a package cannot be installed.

    The number of lines in the input file will be less than 9000.

    Output file specification

    The output consists of one number -- the maximum number of packages that may be installed on the computer.

    Example

    Input file
    a b c b 0
    b c 0
    c 0
    d e f 0
    e f 0
    f e 0
    g h 0
    
    Output file
    3
    
    Note

    Package c can be installed immediately. Package b depends only on c, and hence can also be installed once we installed c. Finally, package a depends only on b and c and can now also be installed. It is easy to verify that no other packages can be installed.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s-5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2003









    SPOJ Problem Set (classical)

    2144. K Edge-disjoint Branchings

    Problem code: FOREST


    Given a directed graph, may contains repeated edges. We assume that the graph contains and only contains K edge-disjoint branchings rooted by node 0.
    A branching for a graph is a set of directed edges that from a certain root (root, in this problem, is node 0) we can find one path to every other node in the graph by only the edges in the branching.
    K edge-disjoint branching is K branchings that share no common edges.
    Your task which is easy and funny is to find out the K branchings.

    Input

    The first line of input contains a single integer T, (T<=20), denoting the number of test cases.
    For each test case:
    The first line contains two integers N and K, (2<=N<=500,2<=K<=6), which is the number of the nodes in the graph and the number of edge-disjoint branchings.
    Then next (N-1)*K lines contains the information about the edges. There are 2 integers X and Y in every line, meaning there exist an edge from X to Y in the graph.

    Output

    You should output the branchings you have found.
    For every test cases, print the number of test case at the start of output, then you should output K lines.
    Each line is about a branching which contains N-1 integers that the ID of the edges in this branching.
    The ID of edges starts with 0. Every edge will appear and only appear once in the output.
    See samples for further details.

    Example

    Input:
    2
    2 2
    0 1
    0 1
    3 2
    0 1
    0 2
    2 1
    1 2
    Output:
    Case 1:
    0
    1
    Case 2:
    0 3
    1 2

    Test data have been enhanced.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:g201513









    SPOJ Problem Set (classical)

    2147. Root of a Linear Equation

    Problem code: ROOT

    Given two nonnegative integers a and b, you are to generate the solution of the equation b*x=a.

    Input

    The number of test cases is given in the very first line. For each test case there is a single line containing two integers a and b without any leading zeroes, separated by a single space.

    Tip: For more than 95% of test cases, int in C/C++/Java or longint in Pascal is enough.

    The input file is about 1.4 KB.

    Output

    For each test case, output a single line containing the root in decimal cyclic notations, or "Invalid Input!!!"(without quotes) if the solution is not unique or the solution doesn't exist. See the example for more details.

    The output file is about 1.3MB.

    Example

    Input:
    8
    1 1
    1 2
    1 3
    1 4
    1 6
    24 2
    15 7
    1 89
    
    Output:
    1.0
    0.5
    0.(3)
    0.25
    0.1(6)
    12.0
    2.(142857)
    0.(01123595505617977528089887640449438202247191)
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:15s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:UVA 942; USACO 79; test data by Blue Mary









    SPOJ Problem Set (classical)

    2148. Candy III

    Problem code: CANDY3

    A class went to a school trip. And, as usually, all N kids have got their backpacks stuffed with candy. But soon quarrels started all over the place, as some of the kids had more candies than others. Soon, the teacher realized that he has to step in: "Everybody, listen! Put all the candies you have on this table here!"

    Soon, there was quite a large heap of candies on the teacher's table. "Now, I will divide the candies into N equal heaps and everyone will get one of them." announced the teacher.

    "Wait, is this really possible?" wondered some of the smarter kids.

    Problem specification

    You are given the number of candies each child brought. Find out whether the teacher can divide the candies into N exactly equal heaps. (For the purpose of this task, all candies are of the same type.)

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case looks as follows: The first line contains N : the number of children. Each of the next N lines contains the number of candies one child brought.

    Output specification

    For each of the test cases output a single line with a single word "YES" if the candies can be distributed equally, or "NO" otherwise.

    Example

    Input:
    2
    
    5
    5
    2
    7
    3
    8
    
    6
    7
    11
    2
    7
    3
    4
    
    Output:
    YES
    NO
    
    Note: the input file will not exceed 1MB.
    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s-2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2006









    SPOJ Problem Set (classical)

    2149. Biased Standings

    Problem code: BAISED

    Usually, results of competitions are based on the scores of participants. However, we are planning a change for the next year of IPSC. During the registration each team will be able to enter a single positive integer : their preferred place in the ranklist. We would take all these preferences into account, and at the end of the competition we will simply announce a ranklist that would please all of you.

    But wait... How would that ranklist look like if it won't be possible to satisfy all the requests?

    Suppose that we already have a ranklist. For each team, compute the distance between their preferred place and their place in the ranklist. The sum of these distances will be called the badness of this ranklist.

    Problem specification

    Given team names and their preferred placements find one ranklist with the minimal possible badness.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case looks as follows: The first line contains N : the number of teams participating in the competition. Each of the next N lines contains a team name (a string of letters and numbers) and its preferred place (an integer between 1 and N, inclusive). No two team names will be equal.

    Output specification

    For each of the test cases output a single line with a single integer : the badness of the best ranklist for the given teams.

    Example

    Input:
    2
    
    7
    noobz 1
    llamas 2
    Winn3rz 2
    5thwheel 1
    NotoricCoders 5
    StrangeCase 7
    WhoKnows 7
    
    3
    ThreeHeadedMonkey 1
    MoscowSUx13 1
    NeedForSuccess 1
    
    Output:
    5
    3
    
    Explanation:

    In the first test case, one possible ranklist with the minimal badness is:

    1. noobz
    2. llamas
    3. Winn3rz
    4. 5thwheel
    5. NotoricCoders
    6. WhoKnows
    7. StrangeCase
    

    In the second test case all ranklists are equally good.

    Note: the input file will not exceed 5MB.
    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s-3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2006









    SPOJ Problem Set (classical)

    2150. Counting Subsequences

    Problem code: SUBSEQ


    "47 is the quintessential random number," states the 47 society. And there might be a grain of truth in that.

    For example, the first ten digits of the Euler's constant are:

    2 7 1 8 2 8 1 8 2 8
    

    And what's their sum? Of course, it is 47.

    Try walking around with your eyes open. You may be sure that soon you will start discovering occurences of the number 47 everywhere.

    Problem specification

    You are given a sequence S of integers we saw somewhere in the nature. Your task will be to compute how strongly does this sequence support the above claims.

    We will call a continuous subsequence of S interesting if the sum of its terms is equal to 47.

    E.g., consider the sequence S = (24, 17, 23, 24, 5, 47). Here we have two interesting continuous subsequences: the sequence (23, 24) and the sequence (47).

    Given a sequence S, find the count of its interesting subsequences.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    The first line of each test case contains the length of a sequence N. The second line contains N space-separated integers : the elements of the sequence.

    Output specification

    For each test case output a single line containing a single integer : the count of interesting subsequences of the given sentence.

    Example

    Input:
    2
    
    13
    2 7 1 8 2 8 1 8 2 8 4 5 9
    
    7
    2 47 10047 47 1047 47 47
    
    Output:
    3
    4
    
    Note: the input file will not exceed 4MB.
    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:3s-5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2006









    SPOJ Problem Set (classical)

    2151. Digital Calculator

    Problem code: CALCULAT


    Dan likes playing with his pocket calculator during those long, boring math classes. Just now the teacher started to talk about the factorial function.

    N factorial, denoted by N!, is the product of all the integers between 1 and N, inclusive. For example 6! = 6*5*4*3*2*1 = 720.

    Dan took out his calculator out of his pocket to play around with this new function. Unfortunately his calculator quickly ran out of digits and only showed overflow errors. Soon, Dan realized that the factorial function grows very quickly. Still, he would like to know at least some of its digits.

    Problem specification

    Given three positive integers N(1<= N <=108), K(1<= K <=50), L(1<= L <=100), compute the first K digits and the last L digits of N factorial.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case consists of one line containing three positive integers N, K and L separated by single spaces. Neither K nor L will exceed the number of digits in N!.

    Output specification

    For each test case output one line containing two strings A and B separated by a single space. Here, A is the string composed of the first K digits of N! and B is the string composed of the last L digits of N!.

    Example

    Input:
    3
    
    6 2 1
    
    10 3 2
    
    8 5 5
    
    Output:
    72 0
    362 00
    40320 40320
    
    Note : for all test cases whose N>=100, its K<=15.
    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s-10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2006









    SPOJ Problem Set (classical)

    2152. Hilbert Curve

    Problem code: FRACTAL

    The Hilbert Mole is a small and very rare mole. The first and only specimen was found by David Hilbert at his backyard. This mole lives in a huge burrow under the ground, and the border of this burrow forms a Hilbert curve of n-th order (Hn).

    Figure 1. Hilbert curves, order 1 to 4.

    Hilbert curves can be defined as follows. H1 is a unit square with open top side (figure 1(a)), Hn consists of four copies of Hn-1: bottom left and bottom right are copied without changes, top left is rotated 90o counter-clockwise and top right is rotated 90o clockwise. These small copies are connected by three segments of unit length (figure 1(b),(c),(d)).

    Figure 2. Burrow, filled with water.

    Trying to exterminate the mole, Mr. Hilbert fills the burrow with water (figure 2). But air inside the burrow prevents water from filling it entirely. In this problem we suppose that air and water are incompressible and cannot leak throw the borders of the burrow. Your task is to find the total area of the burrow, filled with water.

    Note that water can flow over the obstacle only when its level is strictly higher. See examples on figure 3 for further clarification.

    Figure 3. More examples of filled burrows.

    Input

    Multiple test cases. For each test case:

    The first line of the input file contains two integer numbers: n and alpha - order of Hilbert curve and slope angle of surface in degrees (1 <= n <= 12, 0 <= alpha < 90).

    Input terminates by EOF.

    Output

    For each test case:

    The first line of the output file must contain a single real number - the total area of the burrow, filled with water. The relative error of the answer must not exceed 10-6.

    Example

    Input:
    5 30
    3 45
    4 10
    3 0
    
    Output:
    190.803847577293
    15.5
    91.573591766702
    26.0
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:ACM/ICPC Northeastern Europe Programming Contest(Northern Subregional) 2008, with description modified









    SPOJ Problem Set (classical)

    2153. Internet is Faulty

    Problem code: IMATCH


    David has a problem. He wants to transfer a big file through the internet from his home computer to his computer at work. The size of his file is S kilobytes.

    The internet consists of N computers, numbered from 1 to N. David's home computer has the number 1 and his computer at work has the number 2. Some pairs of computers are connected by different types of links (such as network cables or wi-fi). Some of these links (e.g., a satellite dish) may be unidirectional, thus for simplicity we will assume that all links are unidirectional.

    The data are sent across the network in packets, each packet contains exactly one kilobyte of data. For each link David knows how faulty it is, i.e. the probability that a network packet gets from one computer to the other through the link. We assume that all transfers are independent from each other. That is, regardless of whether the previous packet was transferred successfully or not, the probability that the next one will pass through remains the same.

    Since the network is faulty and the work computer might be many links away from the home computer, the transfer of David's file along even the best route between the two computers might take too long. Luckily, David has an account on some of the machines in the network. He may use these machines as temporary storage, and thus shorten the time of the transfer.

    The file transfer will consist of several steps. In each step, David selects a series of links starting with a computer that already has the file and ending with a computer David has an account on. Prior to the transfer, the file is split into S packets. Then the packets are sent one after another along the chosen route. The probability that a packet successfully arrives at the destination computer is the product of probabilities that it passes all the links. If the packet is lost it is resent immediately. Each attempt to send a packet, successful or unsuccessful, takes exactly one millisecond, regardless of the number of links on the route. After the entire file is transferred, David may start another transfer from the new machine, and so on.

    Problem specification

    You are given the number of computers N and the file size S. For each pair of computers u, v we know the probability p(u, v) that a network packet passes successfully through the direct link from computer u to v. (The value zero means that there is no direct link from u to v.) Finally, you are given a list of servers where David has an account.

    Find a way how to send David's file so that the expected transfer time is minimized, and output this expected time in milliseconds. You may assume that the expected transfer time is less than 1 000 000 000 (1 billion) milliseconds.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case looks as follows: The first line contains a positive integer 2<= N <=200 giving the number of computers on the internet.

    N lines follow. The i-th of these lines contains N integers, each of them between 0 and 100, inclusive. These integers give the probabilities p(i, 1), p(i, 2), ..., p(i, N) in percents.

    The next line contains a non-negative integer M – the number of computers on which David has an account. The following line contains M integers – the numbers of these computers. This list will always contain the integers 1 and 2 (corresponding to David's home and work computer).

    The last line contains an integer S – the size of David's file in kilobytes.

    Output specification

    For each test case output a single line with a real number – the expected time of the transfer in milliseconds when using the best possible strategy.

    Each number in the output file should have sufficiently many decimal places. We recommend printing all results rounded to seven decimal places. Your output will be considered correct if each number has an absolute or relative error less than 10-6.

    Example

    Input:
    2
    
    4
    0 0 40 66
    0 0 0 30
    40 47 0 66
    0 30 66 0
    4
    1 2 3 4
    47
    
    5
    0 1 20 0 0
    0 0 0 0 0
    0 0 0 50 90
    0 20 0 0 0
    0 0 0 90 0
    3
    1 2 5
    10
    
    Output:
    207.897153
    111.111111
    

    Hint

    In the second case, we have four possible strategies.

    The first one is to use the direct link from 1 to 2. This link is really really faulty, and the expected time for this solution is 1000 milliseconds. The second strategy is to transfer the file from computer 1 to computer 2 using the route 1-3-4-1. The probability that a packet passes this route is 20% * 50% * 20% = 2%, and thus the expected transfer time is 500 milliseconds. The third strategy is to use the route 1-3-5-4-2. Here the probability of successfully transfering a packet is 3.24% and the expected transfer time is roughly 308.6 milliseconds.

    The optimal solution is to use the computer 5 as temporary storage. We will first transfer the file along the route 1-3-5, and then along the route 5-4-2. For each of the transfers the probability is 20% * 90% = 18%, and thus the expected time of each of the transfers is 55.5555 milliseconds.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s-11s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2007









    SPOJ Problem Set (classical)

    2154. Kruskal

    Problem code: KRUSKAL


    A three-headed monkey was on his (theirs?) peaceful way from his dorm to the university. He decided to use the subway. But as soon as he descended into the station, he was stopped by a strange geek with a flashlight, saying strange words...

    "I am a servant of the Secret Group Order, wielder of the flame of Primes. Your limited knowledge of partial derivatives will not avail you, flame of Riemann! You shall not pass! You can't beat Kruskal in his game!"

    The three-headed monkey shook his head. The left one. But there was no way out. If he wanted to get to the university in time, he had to play.

    (Many others in his situation would use the distract-and-run tactics to get past the evil Kruskal into the subway. However, this was not possible in this case : nobody will turn around upon hearing "Hey! Look behind you! A three-headed monkey!" when he already sees the monkey in front of him...)

    So, what was the game about? It is a two-player game. At the beginning there are N (not necessarily equal) heaps of matches. On each turn, a player may only remove matches from one heap only, and he has to remove between 1 and K matches, inclusive. A player wins if after his move the size of some heap is a prime number. The three-headed monkey moves first.

    Problem specification

    You will be given several starting positions. For each of them, determine whether the three-headed monkey can win this game. You may assume that Kruskal (the monkey's opponent) plays optimally.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases.

    Each test case looks as follows: on the first line there are the two integers N(1<= N <=200) and K(1<= K <=100), separated by a single space. N lines follow, one for each heap of matches. The i-th of these lines contains a single integer ai(3<= ai < 232) giving the number of matches on the i-th heap.

    Output specification

    For each test case output one line. If the monkey can win the game, output the string "YES", otherwise output the string "NO".

    Example

    Input:
    2
    
    3 3
    48
    15
    4
    
    2 3
    51
    51
    
    Output:
    YES
    NO
    
    Note: a somewhat hard test has been removed.
    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:3s-9s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2006









    SPOJ Problem Set (classical)

    2157. Anti-Blot System

    Problem code: ABSYS

    Jimmy is a hard-working pupil in his second year at primary school. Recently he decided to convert all his notes into an electronic version. Sadly, he found that his math notes were full of ink blots.

    He scanned the notes and sent them through his own OCR package (yes, he coded it all by himself at the age of 8). The OCR package replaced all ink blots by the string "machula".

    Problem specification

    You are given Jimmy's notes, processed by the OCR. They contain simple math exercises, which were used to practice addition on positive integers. Your task is to recover the damaged part of the notes.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case consists of exactly one line. The line represents an equation of the form "number + number = number", where each number is a positive integer. One part of the equation will be replaced by the string "machula". The string always covers a contiguous non-empty sequence of digits, possibly even an entire number. You may assume that for each equation in the input there will be exactly one way to fill in the missing digits.

    Output specification

    For each test case, the output shall contain one line of the form "number + number = number". The line must represent the equation from that test case with all missing digits filled in.

    Example

    Input:
    3
    
    23 + 47 = machula
    
    3247 + 5machula2 = 3749
    
    machula13 + 75425 = 77038
    
    Output:
    23 + 47 = 70
    3247 + 502 = 3749
    1613 + 75425 = 77038
    

    Note: int in C++/C/Java or longint in Pascal is enough.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2007









    SPOJ Problem Set (classical)

    2159. Delicious Cake

    Problem code: CAKE3


    Lenka likes to bake cakes since her childhood, when she has learned to bake from her mom. She soon became a cake expert able to bake chocolate cakes, apple pies, muffins, cookies, cheese cakes, tortes and many other cakes.

    Recently, she has started her studies of math at Comenius University in Bratislava. In the first year she is taking combinatorics class. Today she is studying for the final exam. Since the brain needs a lot of sugar to study math, she has baked, just for herself, her favorite, very delicious, strawberry cake.

    The cake, still hot, is lying on an N×M inch sheet pan. Hungrily waiting for the cake to cool off Lenka came up with an interesting combinatorial question: How many different possibilities to cut the cake are there so that every connected piece consists of some number of 1×1 inch unit squares?

    Problem specification

    The cake can be viewed as a grid consisting of N×M unit squares. We are allowed to cut the cake along the grid lines. As a result the cake splits into several connected pieces. (Two unit squares remain connected if they share a side which was not cut.) How many different ways are there to cut the cake? We consider two cuttings of the cake to be the same if the resulting connected pieces of both cuttings have the same shape and are at the same positions within the cake. In other words, we are only counting those cuttings where no cut leads between two unit squares that are in the same connected piece.

    The following picture ilustrates all the 12 different possible ways how to cut a 2×2 inch cake: 12 possible ways of cutting a 2×2 cake
    Note that cutting, for example, as on following picture
    Not a good way of cutting
    is the same as not cutting at all.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case consists of a single line with two positive integers N and M – dimensions of the cake.

    Output specification

    For each test case output a line with a single positive integer – the number of different possibilities how to cut the cake.

    Example

    Input:
    2
    
    1 2
    
    2 2
    
    Output:
    2
    12
    
    Note

    For all the test cases, min(N,M)<=5, max(N,M)<=130.

    Blue Mary's Note: The data has been enhanced on Feb.28, 2008 to avoid precalculated tables. Sorry to some users.
    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:8s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2007









    SPOJ Problem Set (classical)

    2160. Here-There

    Problem code: HERE


    Do you know the game Here-There? I presume you don't. It's a virtual board game, so you should first learn how this virtual board looks like.

    The process of making the board is remarkably simple. You start by taking a square with side of length 3N, divide it into nine smaller squares of equal size and remove the central one. Then, you repeat the same divide-and-remove-the-centre process with each of the eight smaller squares over and over (N times in total), until you are left with a grid that consists of many little squares with side length 1 – and of many holes. By the way, the number N is called the degree of the board.

    The game itself consists of two steps. First, your opponent chooses two squares on the board, one of them will be "Here" and the other one "There". Your task is to estimate the least number of steps you have to take if you started Here and wanted to get to There. One step consists of moving to another square, which has a common side with the one you're standing on. Obviously, you cannot move over the removed parts of the board. If you guess the number of steps correctly, you get a point.

    You would really like to become a master of this game, so you have written down the sizes of the boards and the positions of the Here and There squares from several games in the past. Now, you'd like to find the exact number of steps you need to take to get from Here to There on each of the boards. Each square is described by two numbers between 1 and 3N, the first of them denoting the column and the second one the row the square is in. The square in the upper left corner of the board has coordinates (1, 1), as you can see on the picture below.

    You can see one of the shortest paths between squares (1, 1) and (4, 8) on the picture, consisting of 10 steps.

    Problem specification

    You are given several boards and pairs of squares on them and your task is to find the steps-distances between the squares in each pair.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case consists of five integers D(1<= D <=39), Hc, Tc, Hr, Tr, specifying the degree of the board D, the coordinates of Here (Hc, Hr) and the coordinates of There (Tc, Tr).

    Output specification

    For each of the test cases, output a single line with one integer – the steps-distance between Here and There.

    Example

    Input:
    2
    
    1 1 2 2 1
    
    2 1 1 4 8
    
    Output:
    2
    10
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2007









    SPOJ Problem Set (classical)

    2161. Pixel Shuffle

    Problem code: JPIX

    Shuffling the pixels in a bitmap image sometimes yields random looking images. However, by repeating the shuffling enough times, one finally recovers the original images. This should be no surprise, since "shuffling" means applying a one-to-one mapping (or permutation) over the cells of the image, which come in finite number.

    Your program should read a number n , and a series of elementary transformations that define a "shuffling" of n * n images. Then, your program should compute the minimal number m (m > 0) , such that m applications of always yield the original n * n image.

    For instance if is counter-clockwise 90o rotation then m = 4.

    Input

    Test cases are given one after another, and a single 0 denotes the end of the input. For each test case:

    Input is made of two lines, the first line is number n (2 <= n <= 210 , n even). The number n is the size of images, one image is represented internally by a n * n pixel matrix (aji) , where i is the row number and j is the column number. The pixel at the upper left corner is at row 0 and column 0.

    The second line is a non-empty list of at most 32 words, separated by spaces. Valid words are the keywords id, rot, sym, bhsym, bvsym, div and mix, or a keyword followed by -. Each keyword key designates an elementary transform (as defined by Figure 1), and key- designates the inverse of transform key. For instance, rot- is the inverse of counter-clockwise 90o rotation, that is clockwise 90o rotation. Finally, the list k1, k2, ..., kp designates the compound transform = k1ok2o ... okp . For instance, "bvsym rot-" is the transform that first performs clockwise 90o rotation and then vertical symmetry on the lower half of the image.

    Figure 1: Transformations of image (aji) into image (bji)

    Output

    For each test case:

    Your program should output a single line whose contents is the minimal number m (m > 0) such that is the identity. You may assume that, for all test input, you have m < 231.

    Example

    Input:
    256
    rot- div rot div
    256
    bvsym div mix
    0
    
    Output:
    8
    63457
    

    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:13s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set (classical)

    2162. Towers of Powers

    Problem code: TOWER

    One of the many problems in computer-generated graphics is realistically modeling the "orderly randomness" of things like mountain ranges and city skylines. A new student intern at a graphics company had an idea - use fluctuations in number representations to model height. In this problem you will compute several such number representations and show the "skylines" they produce.

    Let n be any positive integer, and let b be an integer greater than or equal to 2. The complete base - b expansion of n is obtained as follows. First write the usual base - b expansion of n, which is just a sum of powers of b, each multiplied by a coefficient between 1 and b - 1, omitting terms with zero coefficients. For example, if n = 20000 and b = 3, the base - 3 expansion of 20000 is given by

    20000 = 39 + 35 + 2×33 + 2×32 + 2

    To obtain the complete base - b expansion, we apply the same procedure to the exponents until all numbers are represented in base b. For n = 20000 and b = 3 we would have

    20000 = 332 + 33 + 2 + 2×33 + 2×32 + 2

    As another example, consider n = 16647 and b = 2. The resulting expansion is

    16647 = 222 + 1 + 22 + 2 + 222 + 1 + 22 + 2 + 1

    The rising and falling heights of the numbers form the number's "skyline".

    For each pair of integers n and b in the input, display the complete base - b representation of n. Your display should use multiple output lines for different exponent heights. The display must begin with n = , followed by the expansion. Answers should use an asterisk as the multiplication symbol between coefficients and powers of b. Zero terms must not be printed, and unnecessary coefficients and exponents must not be shown (for example, display 1 instead of b0, b2 instead of 1*b2 and b instead of b1). To assist in accurately viewing the skyline of the number, the display must show one character (either a digit, +, or *) per column of the multi-line display; there must be no unnecessary spaces. The correct format is illustrated in the sample output shown below.

    Answers must be displayed using no more than 80 columns. Expansions requiring more than 80 columns must be split between terms, into two or more sets of display lines to show the remaining portion of the expansion. The second and following parts of the answer must begin in the same column as the first part of the answer and should contain the same number of (possibly blank) lines. The split may only occur between terms of the number itself (the bottom line), not between terms in an exponent. See the sample output for an example. Note that each set of display lines starts with a blank line.

    Input

    Input is a sequence of pairs of integers, n and b, followed by a pair of zeroes. Each value for n will be positive, and each value for b will be greater than or equal to 2. All values will fit into 64 bits unsigned integers (the maximum is therefore 18446744073709551615).

    Output

    For each input pair print the complete base - b expansion of n as described above. Print a line containing

    n in complete base b:
    

    preceding each expansion. Separate the output for consecutive pairs by a line of exactly 80 hyphens. All coefficients, bases, and exponents are to be displayed as standard base 10 integers.

    Example

    Input:
    20000 3
    16647 2
    1000 12
    85026244 3
    0 0
    
    Output:
    20000 in complete base 3:
    
              2
             3   3+2    3    2
    20000 = 3  +3   +2*3 +2*3 +2
    --------------------------------------------------------------------------------
    16647 in complete base 2:
    
              2+1  2     2+1
             2   +2 +2  2     2
    16647 = 2         +2    +2 +2+1
    --------------------------------------------------------------------------------
    1000 in complete base 12:
    
               2
    1000 = 6*12 +11*12+4
    --------------------------------------------------------------------------------
    85026244 in complete base 3:
    
                 2           2         2         2         2       2       2
                3 +2*3+1    3 +2*3    3 +3+2    3 +3+1    3 +2    3 +1    3
    85026244 = 3        +2*3      +2*3      +2*3      +2*3    +2*3    +2*3
    
    
                   2*3+2  2*3+1    3
               +2*3     +3     +2*3 +3+1
    

    Note

    The number of test cases will be no more than 100. The judge of this problem compares your output and the expected output, an extra whitespace will cause Wrong Answer.


    Added by:[Trichromatic] XilinX
    Date:2007-12-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:ACM ICPC World Final 1998









    SPOJ Problem Set (classical)

    2171. Ambiguous Codes

    Problem code: AMCODES

    An extensive area of research in computer science is the field of communications. With computer networks being part of everyday life of many people, the development of ways for making networks faster, more reliable and secure is constantly needed. This practical need motivates an extensive research activity in the theory behind communications.

    The very first thing needed to establish any kind of communication is a common code. A code is a way of changing the form of a piece of information into some other form, in general to make it possible to convey that piece of information from one place to another. Flag codes used by boats and the Morse code used in telegraphy are examples of codes for translating letters into different forms to enable communication over different media.

    More formally, a code is a set of strings composed of symbols from one alphabet. Each string defined in the code is called a code word. A message is then composed concatenating a set of code words to convey the information needed. For example, in Morse code the alphabet is composed of the symbols hyphen and dot; letter “S” is represented by the code word “...”, letter “O” is represented by the code word “---”, and therefore the distress message “SOS” in Morse code is “...---...”.

    Codes for communication can have many desirable and undesirable properties such as ambiguity, entropy, redundancy, and many more. In this problem we will focus on ambiguity as a key property.

    A code is ambiguous when there exists a message using that code that can be partitioned into different sequences of code words. In other words, in an ambiguous code a message may have more than one meaning. For example, consider the binary alphabet, composed of symbols {0,1}. For the code composed of the words {10, 01, 101} the message 10101 can be understood as 10-101 or 101-01 and therefore the code is ambiguous. On the other hand, for the code composed of the words {01, 10, 011} no ambiguous message exists and therefore the code is unambiguous.

    As a part of the computer science community, you are required to develop a tester that checks if codes are ambiguous. In case a code is indeed ambiguous, you are also required to report the length (i.e. the number of symbols) of the shortest ambiguous message for that code.

    Input

    Each test case will consist on several lines. In all test cases the alphabet will be the set of hexadecimal digits (decimal digits plus the uppercase letters “A” to “F”). The first line of a test case will contain an integer N (1 <= N <= 100), the number of code words in the code. Each of the next N lines describes a code word and contains a different and non-empty string of at most 50 hexadecimal digits.

    Input is terminated by N = 0.

    Output

    For each test case, output a single line with the length of the shortest ambiguous message for the provided code or -1 if the code is unambiguous.

    Example

    Input:
    3
    10
    01
    101
    3
    AB
    BA
    ABB
    0
    
    Output:
    5
    -1
    

    Added by:Camilo Andrés Varela León
    Date:2007-12-02
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:The 2007 ACM South American Programming Contest









    SPOJ Problem Set (classical)

    2175. Emoticons

    Problem code: EMOTICON

    Emoticons are used in chat and e-mail conversations to try to express the emotions that printed words cannot. This may seem like a nice feature for many, but a lot of people find it really annoying and wants to get rid of emoticons.

    George is one of those people. He hates emoticons so bad, that he is preparing a plan to remove all emoticons from all e-mails in the world. Since you share his visionary plans, you are preparing a special program to help him.

    Your program will receive the list of emoticons to proscribe. Each emoticon will be a string of characters not including any whitespace. You will also receive several lines of text. What you need to do is change some characters of the text into spaces to ensure no emoticon is left on the text. For an emoticon to be considered to appear in the text it has to appear in a single line and be made of consecutive characters.

    To help George’s plan remain secret as long as possible, you need to do your job with the minimum possible amount of character changes.

    Input

    The input file contains several test cases. Each test case consists of several lines. The first line of each test case will contain two integers separated by a single space: N, the number of emoticons to proscribe, and M, the number of lines the text has. The next N lines contain one emoticon each, a non-empty string of at most 15 characters. Each of the last M lines of the test case contains a line of text of at most 80 characters. You can assume 1 <= N,M <= 100.

    Valid input characters for emoticons are uppercase and lowercase letters, digits and the symbols “!?.,:;-_’#$%&/=*+(){}[]” (quotes for clarity). Each line of the text may contain the same characters with the addition of the space character.

    The input is terminated by N = M = 0.

    Output

    For each test case, output exactly one line containing a single integer that indicates the minimum number of changes you need to make to the entire text to ensure no emoticon on the list appears in it.

    Example

    Input:
    4 6
    :-)
    :-(
    (-:
    )-:
    Hello uncle John! :-) :-D
    I am sad or happy? (-:-(?
    I feel so happy, my head spins
    (-:-)(-:-)(-:-)(-:-) :-) (-: :-)
    but then sadness comes :-(
    Loves you, Joanna :-)))))
    3 1
    :)
    ):
    ))
    :):)):)):)):(:((:(((:):)
    0 0
    
    Output:
    11
    8
    

    Added by:Camilo Andrés Varela León
    Date:2007-12-02
    Time limit:4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:The 2007 ACM South American Programming Contest









    SPOJ Problem Set (classical)

    2185. Musical Optimization

    Problem code: MUSIC

    Bessie the cow used to write musical melody. A musical melody is represented as a sequence of N (1 <= N <= 100,000) notes numbered 1..N. Note i is represented by the integer Ai (-10,000 <= Ai <= 10,000).

    To Bessie's cow-like mind, a musical melody is called 'perfect' if and only if the sum of all the notes in any of its consecutive subsequences is strictly positive.

    For a given musical melody, Bessie wants to make it perfect, but she wants to change the melody as little as possible.

    Thus, to perfect the melody, she repeatedly chooses a consecutive subsequence of the melody, [x, y] (1 < x <= y < N), whose sum S is negative. Then she adds S to both Ax-1 and Ay+1, while subtracting S from both Ax and Ay. (It is possible to subtract from the same note twice if x = y.)

    Given a musical melody, compute the minimum number of steps to make the melody perfect.

    Input

    * Line 1: The single integer N.

    * Lines 2..N+1: Line i+1 contains the single integer Ai.

    Output

    * Line 1: A single integer that represents the minimum number of steps needed to make the given musical melody perfect. If there are no solutions, output -1 instead.

    Example

    Input:
    5
    13
    -3
    -4
    -5
    62
    
    Output:
    2
    
    Explanation

    There is a musical melody with length of 5. The notes are (13, -3, -4, -5, 62).

    First, we choose the range [2, 4]; its sum is (-3) + (-4) + (-5) = -12. After the first step, the melody becomes (1, 9, -4, 7, 50). Second, we choose the range [3, 3], whose sum is -4, and the melody after the second step becomes (1, 5, 4, 3, 50). The melody is perfect now.

    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-12-03
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Lei HUANG [g201513] , used in USACO









    SPOJ Problem Set (classical)

    2189. Making Pairs

    Problem code: MKPAIRS

    The 2*N (3 <= N <= 1,000) cows have assembled the Bovine Accordion and Banjo Orchestra! They possess various levels of skill on their respective instruments: accordionist i has an associated talent level Ai (0 <= Ai <= 1,000); banjoist j has an associated talent level Bj (0 <= Bj <= 1,000).

    The combined "awesomeness" of a pairing between cows with talents Ai and Bj is directly proportional to the talents of each cow in the pair so a concert with those two cows will earn FJ precisely Ai * Bj dollars in "charitable donations". FJ wishes to maximize the sum of all revenue obtained by his cows by pairing them up in the most profitable way.

    Unfortunately, FJ's accordionists are a bit stuck up and stubborn. If accordionist i is paired with banjoist j, then accordionists i+1..N refuse to be paired with banjoists 1..j-1. This creates restrictions on which pairs FJ can form. FJ thus realizes that in order to maximize his profits, he may have to leave some cows unpaired.

    To make matters worse, when one or more of the musicians is skipped, they will be greatly upset at their wasted talent and will engage in massive binge drinking to wash away their sorrows.

    After all pairings are made, a list is constructed of the groups of each of the consecutive skipped musicians (of either instrument). Every group of one or more consecutive skipped cows will gather together to consume kegs of ice cold orange soda in an amount proportional to the square of the sum of their wasted talent.

    Specifically, FJ has calculated that if the x-th to y-th accordionists are skipped, they will consume precisely (Ax + Ax+1 + Ax+2 + ... + Ay)2 dollars worth of orange soda in the process of drinking themselves into oblivion. An identical relationship holds for the banjoists. FJ realizes that he'll end up getting stuck with the bill for his cows' drinking, and thus takes this into account when choosing which pairings to make.

    Find the maximum amount of total profit that FJ can earn after the contributions are collected and the orange soda is paid for.

    Input

    * Line 1: A single integer: N

    * Lines 2..N+1: Line i+1 contains the single integer: Ai

    * Lines N+2..2*N+1: Line i+N+1 contains the single integer: Bi

    Output

    * Line 1: A single integer that represents the maximum amount of cash that FJ can earn.

    Example

    Input:
    3
    1
    1
    5
    5
    1
    1
    
    Output:
    17
    

    Explanation

    There are 6 cows: 3 accordionists and 3 banjoists. The accordionists have talent levels (1, 1, 5), and the banjoists have talent levels (5, 1, 1).

    FJ pairs accordionist 3 with banjoist 1 to get earn A3 * B1 = 5 * 5 = 25 in profit. He loses a total of (1 + 1)2 + (1 + 1)2 = 8 dollars due to the cost of soda for his remaining cows. Thus his final (net) profit is 25 - 8 = 17.

    Time limit has been doubled on Aug.8, 2008, enjoy :)


    Added by:[Trichromatic] XilinX
    Date:2007-12-04
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Lei HUANG [g201513] , used in USACO CHN07









    SPOJ Problem Set (classical)

    2202. Tan and His Interesting Game

    Problem code: TAN1

    Background

    Tan always creates some interesting and strange games to kill time,and the Pick-Number Game on Tree is his favorite one.He got the idea from his another game(Pick-Number Game on sequence): there is an integer sequence, he picks a number from the head or the tail of the sequence each turn.When the sequence gets empty,he gets another sequence A,in which A[i] is the i-th integer he picks, then he calculates:

    S=A[0]*50+A[1]*51+...+A[n-1]*5n-1, while n is the length of the sequence.If S modudo 8 equals to 3,he wins, otherwise he loses(Tan is such a strange person that he likes games with strange rules).

    Tan got tired of generating sequence randomly before playing a game, and he changed the rule to avoid it.This time he plays the game on trees. He generates a big tree. Every time he wants to play, he chooses two nodes (A,B) randomly and he finds the path connected A,B (including A,B).In this way he gets a sequence and he can play games.He calls this game "Game(A,B)".He can play many times on a big tree without generating a new one.If he can win in Game(A,B),he says that Game (A,B) is a good game,otherwise Game(A,B) is a bad game.

    If a game is a bad game,he can never win,so he has to find a way to identify if a game is bad or good.

    He played this game for a long time,and he thought he found a great law: if Game(A,B) is a good game and Game(B,C) is a good game,then Game(A,C) is a good game.And if Game(A,B) is a bad game and Game(B,C) is a bad game,the (A,C) is a bad game.But soon he found it was wrong,but he wanted to know in how many cases it is right.

    P.S:"Tan" in Chinese means funny and droll. And Mr.Tan in the story is a real person.

    Task

    The input data describes a tree with integer numbers on each of its nodes.You should count the number of triple (A,B,C) (A,B,C are distinct nodes) that (A,B),(B,C),(A,C) are all good games or all bad games((A,B,C) and (B,C,A) are supposed to be counted once).

    Input

    The first line of the test data is the number of test case t,then t test case follow.

    For each test case:

    The first line contains a single integer M,the number of nodes in the tree(M<=100000).

    M lines follow, each contains two integers Fi and Vi. Fi is the father of node i (Fi=0 if node i is the root).Vi is the number on the node i.(0<=Vi<=40000)

    Output

    For each test case:

    The first and only line contains a single integer S, which means there are S triples(A,B,C) that (A,B),(B,C),(A,C) are all good games or all bad games.

    Example

    Input:
    1
    3
    0 3
    1 5
    1 7
    
    Output:
    0
    
    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2007-12-07
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:description and test data by LoLitter; standard program by rendezvous









    SPOJ Problem Set (classical)

    2270. Balloons in a Box

    Problem code: BALLOON


    You must write a program that simulates placing spherical balloons into a rectangular box.

    The simulation scenario is as follows. Imagine that you are given a rectangular box and a set of points. Each point represents a position where you might place a balloon. To place a balloon at a point, center it at the point and inflate the balloon until it touches a side of the box or a previously placed balloon. You may not use a point that is outside the box or inside a previously placed balloon. However, you may use the points in any order you like, and you need not use every point. Your objective is to place balloons in the box in an order that maximizes the total volume occupied by the balloons.

    You are required to calculate the volume within the box that is not enclosed by the balloons.

    Input

    The input consists of several test cases. The first line of each test case contains a single integer n that indicates the number of points in the set (1<=n<=6). The second line contains three integers that represent the (x, y, z) integer coordinates of a corner of the box, and the third line contains the (x, y, z) integer coordinates of the opposite corner of the box. The next n lines of the test case contain three integers each, representing the (x, y, z) coordinates of the points in the set. The box has non-zero length in each dimension and its sides are parallel to the coordinate axes.

    The input is terminated by the number zero on a line by itself.

    Output

    For each test case print one line of output consisting of the test case number followed by the volume of the box not occupied by balloons. Round the volume to the nearest integer. Follow the format in the sample output given below.

    Place a blank line after the output of each test case.

    Example

    Input:
    2
    0 0 0
    10 10 10
    3 3 3
    7 7 7
    0
    
    Output:
    Box 1: 774
    
    

    Added by:[Trichromatic] XilinX
    Date:2008-01-03
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC World Final 2002 (unofficial testdata)









    SPOJ Problem Set (classical)

    2271. Undecodable Codes

    Problem code: UCODES

    Phil Oracle has a unique ability that makes him indispensable at the National Spying Agency. His colleagues can bring him any new binary code and he can tell them immediately whether the code is uniquely decodable or not. A code is the assignment of a unique sequence of characters (a codeword) to each character in an alphabet. A binary code is one in which the codewords contain only zeroes and ones. For example, here are two possible binary codes for the alphabet {a,c,j,l,p,s,v}.

    The encoding of a string of characters from an alphabet (the cleartext) is the concatenation of the codewords corresponding to the characters of the cleartext, in order, from left to right. A code is uniquely decodable if the encoding of every possible cleartext using that code is unique. In the example above, Code 1 is uniquely decodable, but Code 2 is not. For example, the encodings of the cleartexts "pascal" and "java" are both 001010101010. Even shorter encodings that are not uniquely decodable are 01 and 10.

    While the agency is very proud of Phil, he unfortunately gives only "yes" or "no" answers. Some members of the agency would prefer more tangible proof, especially in the case of codes that are not uniquely decodable. For this problem you will deal only with codes that are not uniquely decodable. For each of these codes you must determine the single encoding having the minimum length (measured in bits) that is ambiguous because it can result from encoding each of two or more different cleartexts. In the case of a tie, choose the encoding which comes first lexicographically.

    Input

    One or more codes are to be tested. The input for each code begins with an integer m, 1<=m<=20, on a line by itself, where m is the number of binary codewords in the code. This is followed by m lines each containing one binary codeword string, with optional leading and trailing whitespace. No codeword will contain more than 20 bits.

    The input is terminated by the number zero on a line by itself.

    Output

    For each code, display the sequential code number (starting with 1), the length of the shortest encoding that is not uniquely decodable, and the shortest encoding itself, with ties broken as previously described. The encoding must be displayed with 20 bits on each line except the last, which may contain fewer than 20 bits. Place a blank line after the output for each code. Use the format shown in the samples below.

    Example

    Input:
    3
    0
    01
    10
    5
    0110
    00
    111
    001100
    110
    5
    1
    001
    0001
    00000000000000000001
    10000000000000000000
    0
    
    Output:
    Code 1: 3 bits
    010
    
    Code 2: 9 bits
    001100110
    
    Code 3: 21 bits
    10000000000000000000
    1
    
    

    Added by:[Trichromatic] XilinX
    Date:2008-01-03
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC World Final 2002 (unofficial testdata)









    SPOJ Problem Set (classical)

    2272. Crossing the Desert

    Problem code: DESERT


    In this problem, you will compute how much food you need to purchase for a trip across the desert on foot.

    At your starting location, you can purchase food at the general store and you can collect an unlimited amount of free water. The desert may contain oases at various locations. At each oasis, you can collect as much water as you like and you can store food for later use, but you cannot purchase any additional food. You can also store food for later use at the starting location. You will be given the coordinates of the starting location, all the oases, and your destination in a two-dimensional coordinate system where the unit distance is one mile.

    For each mile that you walk, you must consume one unit of food and one unit of water. Assume that these supplies are consumed continuously, so if you walk for a partial mile you will consume partial units of food and water. You are not able to walk at all unless you have supplies of both food and water. You must consume the supplies while you are walking, not while you are resting at an oasis. Of course, there is a limit to the total amount of food and water that you can carry. This limit is expressed as a carrying capacity in total units. At no time can the sum of the food units and the water units that you are carrying exceed this capacity.

    You must decide how much food you need to purchase at the starting location in order to make it to the destination. You need not have any food or water left when you arrive at the destination. Since the general store sells food only in whole units and has only one million food units available, the amount of food you should buy will be an integer greater than zero and less than or equal to one million.

    Input

    The first line of input in each trial data set contains n (2 <= n <= 20), which is the total number of significant locations in the desert, followed by an integer that is your total carrying capacity in units of food and water. The next n lines contain pairs of integers that represent the coordinates of the n significant locations. The first significant location is the starting point, where your food supply must be purchased; the last significant location is the destination; and the intervening significant locations (if any) are oases. You need not visit any oasis unless you find it helpful in reaching your destination, and you need not visit the oases in any particular order.

    The input is terminated by a pair of zeroes.

    Output

    For each trial, print the trial number followed by an integer that represents the number of units of food needed for your journey. Use the format shown in the example. If you cannot make it to the destination under the given conditions, print the trial number followed by the word "Impossible."

    Place a blank line after the output of each test case.

    Example

    Input:
    4 100 
    10 -20 
    -10 5 
    30 15 
    15 35 
    2 100 
    0 0 
    100 100 
    0 0 	 
    
    Output:
    Trial 1: 136 units of food
    
    Trial 2: Impossible
    
    

    Added by:[Trichromatic] XilinX
    Date:2008-01-03
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC World Final 2002 (unofficial testdata)









    SPOJ Problem Set (classical)

    2273. Ferries

    Problem code: FERRY

    Millions of years ago massive fields of ice carved deep grooves in the mountains of Norway. The sea filled these grooves with water. The Norwegian people call them fjords. This landscape of mountains and water is beautiful, but it makes traveling difficult. The usual scheme is: drive some kilometers, wait for a ferry, cross a fjord with the ferry, drive some more kilometers, and so on until the destination has been reached. To reach a destination as early as possible, most people have the following strategy: drive as fast as allowed (the maximum speed is 80 km/h) to the next ferry, and wait until it goes. Repeat until the destination has been reached.

    Since driving fast requires more fuel than driving slow, this strategy is both expensive and harmful to the environment. The new generation of cruise control systems is designed to help. Given the route you want to go, these systems will gather information about the ferries involved, calculate the earliest possible time of arrival at the final destination, and calculate a driving scheme that avoids driving faster than needed. The systems will calculate your road speed so that you board the next ferry the moment it leaves.

    Given a route (a sequence of road-pieces and crossings with ferries), you must write a program to calculate the minimal time it takes to complete this route. Moreover, your program must find a driving scheme such that the maximal driving speed at any point during the trip is as small as possible.

    Input

    The input file contains one or more test cases. Each test case describes a route. A route consists of several sections, each section being either a piece of road or a crossing. The first line in the description contains a single number s (s > 0), which is the number of sections in the route. The next s lines contain the descriptions of the sections. Every line describing a section starts with two names: the place of departure and the place of arrival, followed by either the word ‘road’ or the word ‘ferry’ indicating what kind of section it is. If the section is a road, its length (a positive integer) is given in km. For example:

    Dryna Solholmen road 32

    Lines describing ferry sections have more information. Following the word “ferry”, the duration of the ferry crossing, in minutes (a positive integer) is given. This is followed by the frequency f (f > 0) of the ferry, that is, the number of times the ferry departs in a single hour. The next f integers give the departure times of the ferry, in ascending order. For example:

    Manhiller Fodnes ferry 20 2 15 35

    The ferry travels from Manhiller to Fodnes in 20 minutes, and it leaves twice an hour (on 0h15, 0h35, 1h15, 1h35,…). The beginning of the entire trip always starts at a full hour. The sections in a route are consecutive, that is, if a section goes from A to B then the next section starts at B. Every route in the input can be traveled in no more than 10 hours.

    The input is terminated by the number zero on a line by itself.

    Output

    Output for each test case is a single line containing three items. The first item is the test case number. The second is the total travel time for an optimal scheme in the form hh:mm:ss. The third item is the maximal road speed in an optimal scheme rounded to two digits to the right of the decimal point.

    Place a blank line after the output of each test case.

    Example

    Input:
    1
    Bygd Bomvei road 7
    2
    Ferje Overfarten ferry 20 2 5 25
    Overfarten Havneby ferry 30 3 10 30 50
    5
    Begynnelse Brygge road 30
    Brygge Bestemmelse ferry 15 4 10 25 40 55
    Bestemmelse Veiskillet road 20
    Veiskillet Grusvei road 25
    Grusvei Slutt ferry 50 1 10
    0
    
    Output:
    Test Case 1: 00:05:15 80.00
    
    Test Case 2: 01:00:00 0.00
    
    Test Case 3: 03:00:00 45.00
    
    

    Added by:[Trichromatic] XilinX
    Date:2008-01-03
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC World Final 2002 (unofficial testdata)









    SPOJ Problem Set (classical)

    2274. Island Hopping

    Problem code: ISLHOP

    The company Pacific Island Net (PIN) has identified several small island groups in the Pacific that do not have a fast internet connection. PIN plans to tap this potential market by offering internet service to the island inhabitants. Each groups of islands already has a deep-sea cable that connects the main island to the closest internet hub on the mainland (be it America, Australia or Asia). All that remains to be done is to connect the islands in a group to each other. You must write a program to help them determine a connection procedure.

    For each island, you are given the position of its router and the number of island inhabitants. In the figure, the dark dots are the routers and the numbers are the numbers of inhabitants. PIN will build connections between pairs of routers such that every router has a path to the main island. PIN has decided to build the network such that the total amount of cable used is minimal. Under this restriction, there may be several optimal networks. However, it does not matter to PIN which of the optimal networks is built.

    PIN is interested in the average time required for new customers to access the internet, based on the assumption that construction on all cable links in the network begins at the same time. Cable links can be constructed at a rate of one kilometer of cable per day. As a result, shorter cable links are completed before the longer links. An island will have internet access as soon as there is a path from the island to the main island along completed cable links. If mi is the number of inhabitants of the ith island and ti is the time when the island is connected to the internet, then the average connection time is:

    Input

    The input consists of several descriptions of groups of islands. The first line of each description contains a single positive integer n, the number of islands in the group (n <= 50). Each of the next n lines has three integers xi, yi, mi, giving the position of the router (xi, yi) and number of inhabitants mi(mi > 0) of the islands. Coordinates are measured in kilometers. The first island in this sequence is the main island.

    The input is terminated by the number zero on a line by itself.

    Output

    For each group of islands in the input, output the sequence number of the group and the average number of days until the inhabitants are connected to the internet. The number of days should have two digits to the right of the decimal point. Use the output format in the sample given below.

    Place a blank line after the output of each test case.

    Example

    Input:
    7
    11 12 2500
    14 17 1500
    9 9 750
    7 15 600
    19 16 500
    8 18 400
    15 21 250
    0
    
    Output:
    Island Group: 1 Average 3.20
    
    

    Added by:[Trichromatic] XilinX
    Date:2008-01-03
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC World Final 2002 (unofficial testdata)









    SPOJ Problem Set (classical)

    2275. Toil for Oil

    Problem code: OIL

    Prospecting for new sources of oil has become a high-technology industry. With improved drilling technology it has become economically viable to seek out ever smaller and harder to reach deposits of oil. However, using exploratory drilling to locate these deposits is not cost-efficient, so researchers have developed methods to detect oil indirectly.

    One such method to detect oil is sonar, which uses reflected sound waves to locate caves in underground rock formations. Determining how much oil can be contained in such a cave is a difficult problem.

    In this problem, you will be given some cross-sections of underground caves, represented by polygons such as the ones shown in the figure. Some of the points bounding the polygon may be holes through which oil can seep out into the surrounding rock (represented by black circles in the figure). Given the polygonal shape of the cave and the positions of the holes, you must compute the maximum amount of oil that could be in the cave (shown as gray shaded areas in the figure). This amount is limited by the fact that, in any connected body of oil, the oil level can never be above a hole, since it would drain into the surrounding rock instead.

    Input

    The input contains several cave descriptions, each in the form of a polygon that specifies a cross-section of a cave. The first line of each description contains a single integer n, representing the number of points on the polygon (3 <= n <= 10000).

    Each of the following n lines contains three integers xi, yi, hi. The values (xi, yi) give the positions of the points on the boundary of the polygon in counterclockwise order. The polygon is simple, that is, it does not cross or touch itself. The value of hi is equal to 1 if the point is a hole through which oil can seep out, and 0 otherwise. The "upward" direction in each case is the positive y-axis.

    The input is terminated by a zero on a line by itself.

    Output

    For each cave description, print its oil capacity. Approximate the oil capacity by the area within the given cross-section that may contain oil, rounded to the nearest integer.

    Example

    Input:
    4 
    10 0 0 
    5 10 1 
    0 20 0 
    -10 0 0 
    11 
    0 6 0 
    1 5 1 
    6 0 0 
    10 4 0 
    8 6 0 
    6 4 0 
    4 6 0 
    8 10 0 
    10 8 0 
    12 10 0 
    8 14 1 
    0
    
    Output:
    150
    27
    
    Test data has been corrected and enhanced on Sep. 13, 2010. Thanks to Danny Sleator's help.
    Added by:[Trichromatic] XilinX
    Date:2008-01-03
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC World Final 2002 (unofficial testdata)









    SPOJ Problem Set (classical)

    2276. Partitions

    Problem code: RECTNG2

    A partition of a rectangle is either a whole rectangle or a subdivision the rectangle into either a upper part and a lower part or a left part and a right part, and each part is a partition of the corresponding rectangle. Figure 1 shows several examples of partitions.

    Figure 2 shows three equal sized rectangles, partitioned into sub-rectangles. Partition B is obtained from partition A by partitioning two of the sub-rectangles of A. Generally, if a partition B is obtained from A by partitioning one or more of its sub-rectangles, we say that B is finer than A, or that A is coarser than B. This relation is partial: partition C is neither coarser nor finer than A or B.

    Given two partitions D and E of the same rectangle, infinitely many partitions exist that are finer than both D and E. In Figure 3 both F and G are finer than D and E. Among the partitions that are finer than both D and E, a unique one exists that is coarsest. This partition is called the infimum of D and E. In Figure 3, partition F is the infimum of D and E.

    In Figure 4, both H and J are coarser than D and E. Here J is the finest partition that is coarser than D and E. Then J is the supremum of D and E.

    Write a program that, given two partitions of the same rectangle, finds the infimum and the supremum of these partitions.

    Input

    The input file contains one or more test cases. The first line of each test case gives the width w and height h of the rectangle (0 < w, h <= 20). In the next h+1 lines the two partitions are given, as in the sample. Each of these lines contains 4*w+3 characters. The first 2*w+1 of these belong to the first partition; the last 2*w+1 of these belong to the second partition. A space separates the two partitions. Horizontal lines are created using underscores ‘_’, vertical lines using ‘|’.

    The input is terminated by a pair of zeroes.

    Output

    For every case in the input file the output contains a single line containing the case number (in the format shown in the sample), followed by the infimum and the supremum of the two partitions, using the same format as the input.

    Place a blank line after the output of each test case.

    Example

    Input:
    4 3
     _ _ _ _   _ _ _ _ 
    |_ _ _ _| |_|_ _ _|
    |   |   | |       |
    |_ _|_ _| |_ _ _ _|
    3 4
     _ _ _   _ _ _ 
    | |   | | |   |
    | |   | |_|_ _|
    |_|_ _| |   | |
    |_ _|_| |_ _|_|
    0 0
    
    Output:
    Case 1:
     _ _ _ _   _ _ _ _ 
    |_|_ _ _| |_ _ _ _|
    |   |   | |       |
    |_ _|_ _| |_ _ _ _|
    
    Case 2:
     _ _ _   _ _ _ 
    | |   | |     |
    |_|_ _| |     |
    |_|_|_| |     |
    |_ _|_| |_ _ _|
    
    
    Please read the problem statement carefully. The judge compares your output and the expected output, any extra whitespace will cause Wrong Answer.
    Added by:[Trichromatic] XilinX
    Date:2008-01-03
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS PERL 6
    Resource:ACM/ICPC World Final 2002 (unofficial testdata)









    SPOJ Problem Set (classical)

    2277. Silly Sort

    Problem code: SSORT


    Your younger brother has an assignment and needs some help. His teacher gave him a sequence of numbers to be sorted in ascending order. During the sorting process, the places of two numbers can be interchanged. Each interchange has a cost, which is the sum of the two numbers involved.

    You must write a program that determines the minimal cost to sort the sequence of numbers.

    Input

    The input file contains several test cases. Each test case consists of two lines. The first line contains a single integer n (n>1), representing the number of items to be sorted. The second line contains n different integers (each positive and less than 1000), which are the numbers to be sorted.

    The input is terminated by a zero on a line by itself.

    Output

    For each test case, the output is a single line containing the test case number and the minimal cost of sorting the numbers in the test case.

    Place a blank line after the output of each test case.

    Example

    Input:
    3
    3 2 1
    4
    8 1 2 4
    5
    1 8 9 7 6
    6
    8 4 5 3 2 7
    0
    
    Output:
    Case 1: 4
    
    Case 2: 17
    
    Case 3: 41
    
    Case 4: 34
    
    

    Added by:[Trichromatic] XilinX
    Date:2008-01-03
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC World Final 2002 (unofficial testdata)









    SPOJ Problem Set (classical)

    2317. Bracket Sequence

    Problem code: LEXBRAC

    Correct Bracket Sequence (CBS) is a sequence that can be obtained through following rules:
    1) An empty string is the CBS.
    2) If A is a CBS, then B = (A) is also a CBS.
    3) If A is a CBS, then B = [A] is also a CBS.
    4) If A and B are CBS, then C = AB is also a CBS.
    Length of the CBS is the number of brackets in it, and this number is always even.
    Assume that '(' < ')' < '[' < ']'.
    CBS a1a2 ... an is lexicografically smaller than the CBS b1b2 ... bn if and only if there exists an integer i, i <= n, so that aj=bj, for each j, 1 <= j < i and ai < bi.

    Illustration

    Enumerate all CBS length 4 in lexicographical order: (()), ()(), ()[], ([]), [()], [[]], [](), [][].

    Task

    Your task is to find k-th CBS with length n in lexicographical order

    Input

    Contains 2 integers n (2..250) and k (1..10^120)

    Output

    Print the k-th CBS with length n in lexicographical order

    Example

    Input:
    4
    3
    Output:
    ()[]
    

    Added by:Chinh Nguyen
    Date:2008-01-10
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6









    SPOJ Problem Set (main)

    2318. Overlapping Words

    Problem code: WORDS

    Consider the following game: you are given a word W that contains only lower-case letters ("a" to "z"). You are also given a set of words and you are allowed to do the following operation: choose a suffix of W and replace it with another word (you can do this only if that word contains the suffix as its prefix). For example, if the current words is "acmicpc" you can choose to replace the suffix "pc" with any word in the set you are given that starts with "pc", e.g. "pcaaargh" thus forming the word "acmicpcaaargh". You can then repeat this procedure as many times as you wish. You are free to choose any suffix of the current word as long as it matches a prefix of the word you are replacing it with. You can also choose not to do the operation at all. Each suffix you replace must have length at least 1 (you cannot replace the "null suffix" with a word).

    You are also given an integer L, 1 ≤ L ≤ 5. Your task is to find how many different subwords of length exactly L can be produced using the following operation. A "subword" means a substring of length L.

    Input

    The first line of the input file contains two integers, N and L separated by space. N, 1 ≤ N ≤ 100 is the number of words in the set (including the initial word). The next N lines describe one word each. No other symbols except small latin letters, and the end-of-line symbol are found on these lines. Each word has length at least L and at most 128. The word you start with is the first word in this set.

    Output

    The only line of the output should contain one integer: the number of different subwords of length L that can be produced using the operation described above.

    Example

    Input:
    2 5
    acmicpc
    pcaaaaaaargh
    
    Output:
    11
    

    Added by:Jelani Nelson (Minilek)
    Date:2008-01-10
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT 1st Team Contest 2007









    SPOJ Problem Set (main)

    2319. Sequence

    Problem code: BIGSEQ

    You are given the sequence of all K-digit binary numbers: 0, 1,..., 2K-1. You need to fully partition the sequence into M chunks. Each chunk must be a consecutive subsequence of the original sequence. Let Si (1 ≤ i ≤ M) be the total number of 1's in all numbers in the ith chunk when written in binary, and let S be the maximum of all Si, i.e. the maximum number of 1's in any chunk. Your goal is to minimize S.

    Input

    In the first line of input, two numbers, K and M (1 ≤ K ≤ 100, 1 ≤ M ≤ 100, M ≤ 2^K), are given, separated by a single space character.

    Output

    In one line of the output, write the minimum S that can be obtained by some split. Write it without leading zeros. The result is not guaranteed to fit in a 64-bit integer.

    Example

    Input:
    3 4
    
    Output:
    4
    

    Added by:Jelani Nelson (Minilek)
    Date:2008-01-10
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT 1st Team Contest 2007









    SPOJ Problem Set (classical)

    2320. Manhattan

    Problem code: DISTANCE

    The L1 distance of two d-dimensional points is the sum of absolute values of their coordinate differences (i.e. Σi=1d |xi - yi| for two points x,y). Given N points in the plane you must find the farthest pair of points under the L1 distance metric and output their distance.

    Input

    The first line of the input is "N d" (2 ≤ N ≤ 100000, 1 ≤ d ≤ 6) signifying that there are N points in d-dimensional space. N lines then follow, where the ith line is a space-separated list of d numbers, the coordinates of the ith point. All given coordinates are integers that are at most 1000000 in absolute value, and all given points are distinct.

    Output

    Your output should consist of a single integer, the farthest distance between a pair of input points, followed by a newline.

    Example

    Input:
    3 2
    0 0
    -5 0
    1 1
    
    Output:
    7
    

    Added by:Jelani Nelson (Minilek)
    Date:2008-01-10
    Time limit:1s-30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:MIT 1st Team Contest 2007









    SPOJ Problem Set (classical)

    2321. Segments

    Problem code: SEGMENTS

    There are N horizontal line segments in the plane. The ith segment has some height hi (which may be negative) and runs from x = ai to x = bi (ai < bi). Segments do not contain their endpoints. You must draw a set of vertical lines (note lines and not line segments) so that every given horizontal segment is intersected at least once and at most R times by vertical lines in such a way that R is minimized.

    Input

    The first line of the input is N (1 ≤ N ≤ 400), the number of horizontal line segments. N lines then follow, where the ith line is "ai bi hi". Each of ai,bi,hi are 32-bit signed integers. Horizontal segments may overlap.

    Output

    Your output should consist of a single integer, the smallest value of R that is achievable, followed by a newline.

    Example

    Input:
    3
    0 1 5
    0 2 -2
    1 2 7
    
    Output:
    2
    

    Added by:Jelani Nelson (Minilek)
    Date:2008-01-10
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:MIT 1st Team Contest 2007









    SPOJ Problem Set (main)

    2322. Tree Game

    Problem code: TREEGAME


    A complete binary tree of depth h is given. You can asign the value 0 or 1 to each leaf. Its internal nodes compute their values based on the values of their children, which is 0 if both children have value 1, and 1 otherwise. You play a game with a computer. The computer can ask you for a value of any leaf, and you can tell him either 0 or 1. The computer wants to know the root value, and he will keep asking until he is absolutely sure what the root value is. Your goal is to make him ask as many questions as possible. It is known that you can make a computer ask for all leaves. For a given sequence of leaves determine a sequence of 0's and 1's as answers to those leaves such that at no point before asking the last leaf value can the computer be sure of the root value. You must answer each question optimally (i.e. you should not make use of the knowledge of what the computer's (i+1)st query will be when you answer the ith query).

    Input

    In the first line of input the number h is given (1 ≤ h ≤ 15). In the second line a space-separated list of 2h numbers are given. They are a permutation of the numbers 1, 2, ..., 2h, and they represent the order of asked leaves (leaves of a tree are indexed from left to right).

    Output

    On a single line write a space-separated sequence of 0's and 1's corresponding to the values of leaves in the given order of being asked. If there are multiple solutions, write any of them. Do not output a response for the last query.

    Example

    Input:
    3
    5 2 7 3 1 6 8 4
    
    Output:
    1 1 1 1 0 0 1
    

    Added by:Jelani Nelson (Minilek)
    Date:2008-01-10
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT 1st Team Contest 2007









    SPOJ Problem Set (main)

    2323. Broken Compass

    Problem code: COMPASS

    A group of adventurers are on an expedition to reach the North Pole. The only instrument they have is a compass that points to the pole. However, the compass is broken and although its measurements are consistent, the direction it points to is some fixed but unknown angle away from true North. For example, if the error angle is 90 degrees, the compass will always point East at times when it should point North. This error angle may be zero, in which case the compass is not broken.

    Input

    To overcome this difficulty the group decided to take measurements at several different points and try to recover the location of the North pole from that. For simplicity, we assume that the region around the North pole is a plane in which a coordinate system is introduced. Each point is then described by a pair of real numbers (x,y), x,y ∈ [-200, 200]. One of those points (not necessarily (0,0)) is the location of the pole. The compass would always point to that location if it were not broken. Instead, it always points a fixed angle away from the true direction to the pole. In this problem we assume that the magnetic pole is the same as the geographic pole and that it is a point source.

    Output

    The first line of input specifies one integer number N, N < 10, the number of measurements taken. Each of the next N lines contains four space separated real numbers: the first two are the x and y coordinates of the point at which the measurement was taken, the third and fourth are (ux, uy), the direction of a unit vector indicating where the compass needle points. There should be only one line of output that should contain two real numbers separated by space: the x and y coordinates of the pole. Your output is considered correct if it is within an additive 0.01 of the correct answer. All measurements are consistent and it is always possible to determine the location of the North pole from them. None of the measurements is made on the pole.

    Example

    Input:
    4
    1.000000 0.000000 -0.000000 -1.000000
    -1.000000 0.000000 0.000000 1.000000
    0.000000 1.000000 1.000000 0.000000
    0.000000 -1.000000 -1.000000 0.000000
    
    Output:
    0.000000 0.000000
    

    Added by:Jelani Nelson (Minilek)
    Date:2008-01-10
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT 1st Team Contest 2007









    SPOJ Problem Set (main)

    2324. Mario

    Problem code: MARIOGAM

    Mario lives in an N x M maze grid. In this maze there are coin boxes, monsters, pipe systems, and walls. Whenever Mario enters a cell containing a coin box, he jumps to hit the box and gets as many coins as there are in the box (coin boxes do not disappear or lose coins after being hit). When Mario enters a cell with a monster, he loses a life. Pipe systems are like teleporters: for each system there is exactly one exit with at least one (but possibly several) entrances leading to that exit. When Mario walks into the entrance to a pipe system he is teleported to that pipe system's unique exit. Walking into a pipe system's exit does nothing special. Finally, Mario cannot walk into walls.

    Mario decides to play a game. In the beginning of the game he starts with three lives at some given position, and at each time step he looks at all neighboring cells (excluding walls) and chooses one neighboring cell uniformly at random to walk to (x neighbors y if x is directly above, below, to the left, or to the right of y). If Mario has no non-wall neighboring cells then he stays at his current location. The game is over when either Mario is out of lives or it is impossible for him to collect more coins. Help Mario figure out the expected number of coins he will earn in one play of the game.

    Input

    The first line of the input is "N M" (1 ≤ N,M ≤ 15), giving the dimensions of the maze. What follows are N lines, each of which are M characters in length. The ith line displays the contents of the cells in the ith row of the maze. Mario starts in the unique cell with an '$' (which, beside holding Mario, is otherwise an empty cell). Cells with monsters are designated with '!'. Cells with coin boxes are represented by a number between 0 and 9 (inclusive), which is the number of coins in that coin box. Each pipe system is associated with a distinct letter between 'a' and 'z' (inclusive). A pipe system's entrances are designated with lower case letters, and the unique exit for a given pipe system has the corresponding capitalized letter (e.g. a pipe system with entrances labeled 'c' has exactly one exit, and it is labeled 'C'). Every pipe system appearing in the maze is guaranteed to have exactly one exit and at least one entrance. The character '#' designates a wall, and '.' designates an empty cell that Mario can just walk through.

    Output

    If the expected number of coins Mario collects is infinite, output -1. Otherwise, output a single real number, the expected number of coins Mario collects before the game is over. Your answer should be accurate to within either an absolute or relative error of 10-6 of the actual answer. Your output should be followed by a newline.

    Example

    Input:
    2 3
    $1!
    a.A
    
    Output:
    3.000000000
    

    Added by:Jelani Nelson (Minilek)
    Date:2008-01-10
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT 1st Team Contest 2007









    SPOJ Problem Set (main)

    2325. String Distance

    Problem code: STRDIST


    Let A = a1a2...ak and B = b1b2...bl be strings of lengths k and l, respectively. The string distance between A and B is defined in the following way (d[i,j] is the distance of substrings a1...ai and b1...bj, where 0 ≤ i ≤ k and 0 ≤ j ≤ l -- i or j being 0 represents the empty substring). The definition for d[i, j] is d[0, 0] = 0 and for (i, j) ≠ (0, 0) d[i, j] is the minimum of all that apply:

    • d[i, j - 1] + 1, if j > 0
    • d[i - 1, j] + 1, if i > 0
    • d[i - 1, j - 1], if i > 0, j > 0, and ai = bj
    • d[i - 1, j - 1] + 1, if i > 0, j > 0, and ai ≠ bj
    • d[i - 2, j - 2] + 1, if i ≥ 2, j ≥ 2, ai = bj-1, and ai-1 = bj

    The distance between A and B is equal to d[k,l].

    For two given strings A and B, compute their distance knowing that it is not higher than 100.

    Input

    In the first line, k and l are given, giving the lengths of the strings A and B (1 ≤ k, l ≤ 105). In the second and third lines strings A and B, respectively, are given. A and B contain only lowercase letters of the English alphabet.

    Output

    In the first line, write one number, the distance between A and B, followed by a newline.

    Example

    Input:
    8 8
    computer
    kmpjutre
    
    Output:
    4
    

    Added by:Jelani Nelson (Minilek)
    Date:2008-01-10
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:MIT 1st Team Contest 2007









    SPOJ Problem Set (classical)

    2371. Another Longest Increasing Subsequence Problem

    Problem code: LIS2

    Given a sequence of N pairs of integers, find the length of the longest increasing subsequence of it.

    An increasing sequence A1..An is a sequence such that for every i < j, Ai < Aj.

    A subsequence of a sequence is a sequence that appears in the same relative order, but not necessarily contiguous.

    A pair of integers (x1, y1) is less than (x2, y2) iff x1 < x2 and y1 < y2.

    Input

    The first line of input contains an integer N (2 ≤ N ≤ 100000).

    The following N lines consist of N pairs of integers (xi, yi) (-109xi, yi ≤ 109).

    Output

    The output contains an integer: the length of the longest increasing subsequence of the given sequence.

    Example

    Input:
    8
    1 3
    3 2
    1 1
    4 5
    6 3
    9 9
    8 7
    7 6
    
    Output:
    3
    

    Added by:Bin Jin
    Date:2008-01-20
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8









    SPOJ Problem Set (classical)

    2412. Arranging Amplifiers

    Problem code: ARRANGE

    Scientists at the TIFR, Mumbai, are doing some cutting edge research on the Propagation of Signals. A young researcher comes up with a method of progressively amplifying signals, as they progress along a path. The method involves the placing of Amplifiers at regular distances along the line. Each amplifier is loaded with a number a(i), which is called its amplification factor. The method of amplification is simple: an amplifier which recieves a signal of strength X, and has Y loaded in it, results in a signal of strength Y^X [ Y to the power X]. In course of his research, the young scientist tries to find out, that given a set of n amplifiers loaded with a(0), a(1), a(2), ...., a(n-1), which particular permutation of these amplifiers, when placed at successive nodes, with the initial node given a signal of strength 1, produces the strongest output signal.

    this is better illustrated by the following example : 5 6 4
    4^(5^(6^1)) is the strength of the strongest signal, which is generated by putting amplifier loaded with 6 in first place, 5 in second place and 4 in third place.

    Given a list of integers specifying the set of amplifiers at hand, you must find out the order in which they must be placed, to get the highest signal strength. In case their exist multiple permutations with same output, you should print the one which has bigger amplifiers first.

    Input

    First line of input contains T, the number of test cases. For each test case first line contains a number ni, which is equal to the number of amplifiers available. Next line contains n integers, separated by spaces which denote the values with which the amplifiers are loaded.

    Output

    Output contains T lines, one for each test case. Each line contains ni integers, denoting the order in which the amplifiers should be kept such that the result is strongest.

    Example

    Input:
    2
    3
    5 6 4
    2
    2 3
    
    Output:
    6 5 4
    2 3
    

    Constraints and Limits

    T ≤ 20, Ni ≤ 10^5.
    Each amplifier will be loaded with a positive integer p, 0 < p ≤ 10^9.
    No two amplifier > 1 shall be loaded with the same integer.


    Added by:Ajay Somani
    Date:2008-02-04
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:CodeCraft 08 Anshuman Singh









    SPOJ Problem Set (classical)

    2413. Building Beacons

    Problem code: BUILD


    A Millionaire Eccentric Mathematician purchases a small Island, to build his residence. In order to keep away Trespassers, he decides to Build some Beacons (Towers) on the perimeter of the Island. To build these Beacons, he visits the Mainland to purchase Stone.

    Being obsessed with Prime Numbers, the stone blocks he orders are all Regular Tridecagons (13 Sides). However, their heights are variable. On delivery of the Blocks, he orders them to be flattened perfectly from the top and the bottom, so that the Tridecagonal shape is viewable from the Top (or Bottom), in such a way that the Height of each block measures to a power of 2. The stones, procured from various sources, are of Variable strength. He intends to build the Beacons by placing Stone Blocks one over the other. The heights of the Towers are specified by the Mathematician, and they are also Prime Numbers. He instructs the Architect to make sure that once the Beacons are complete, the strengths of the used stones add up to the Maximum Possible Number.

    The Architect, not knowing how the job can be done, or even whether it CAN be done, with such complicated restrictions, approaches you to find this out for him.

    Input

    First line of input contains a positive integer T, the number of test cases. The first line of each test case contains a positive integer K, equal to the total number of stones available. This line is followed by K lines, each containing a pair of positive integers X,Y. Here X denotes the height of that stone (here the height would be 2X) and Y denotes its value. Followed is a line containing an integer N, the number of towers. Each of the next N lines contain a single positive number, which is the height H of the corresponding tower the mathematician wants to build.

    Output

    Output contains T lines, one for each test case, containing a number denoting the maximum sum total of strengths of rocks used to construct the Beacons if solution is possible, else the message "Plan Failed!".

    Example

    Input:
    1
    2
    2 3
    0 4
    1
    5
    
    
    Output:
    7
    

    Constraints and Limits

    T ≤11, H < 10^281, 0 ≤ X ≤ 977, 0 < Y ≤ 977, 0 ≤ k ≤ 977 , N ≤ 97


    Added by:Ajay Somani
    Date:2008-02-05
    Time limit:4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:CodeCraft 08, Problem Setter: Gaurav Agarwal,Anshuman Singh









    SPOJ Problem Set (classical)

    2414. Calculate The Cost

    Problem code: CCOST

    In a small Village near the Himalayas, there is a rich Land-Owner, in Possession of a vast, rectangular tract of land. Unknown to him, a Major Oil Corporation has verified the existence of a vast Oil Resource beneath the land owned by him.

    The Oil Company sends a Man to negotiate the purchase of a rectangular field from within the landowner's land, with sides parallel to those of his area. The Landowner, valuing his land according to the trees growing in it and the area to be purchased, gives the company man a Map of his Land, marking the location of trees of different types, and a list of the worth of each type of tree.

    To ensure the most economic purchase of land with the required dimensions, the Company Man provides you with the data in his possession, and alongwith that, a list of the land areas that he considers good by his judgement.

    You must provide, for each land area that he has listed, the Sum Total of the values of the Trees that lie Within or On the Boundary of that land area.

    Input

    The first line of the input contains an integer T, which is the number of test cases. For each test case, the first line contains an integer n, equal to the number of trees in the area. This line is followed by n lines each containing 3 integers separated by spaces which are coordinate of the tree ( x, y ) and value of that tree. Following this is an integer R, equal to the number of proposols of land areas given by the Company Man. Next R lines contain 4 integers each (x1, y1, x2, y2) which are the coordinates of lower left ( x1,y1 ) and upper right ( x2, y2 ) corner of the rectangular area.

    Output

    For each test case, your program should output R lines containing the sum of values of the Trees which lie inside or on the corresponding rectangular plot. There should NOT BE any blank lines between output of different test cases.

    Example

    Input:
    1
    3
    1 1 2
    2 2 3
    3 3 4
    2
    1 1 1 2
    0 0 5 5
    
    Output:
    2
    9
    

    Constraints and Limits

    T ≤ 10, n ≤ 10^5, r ≤ 50000, 0 ≤ x,y ≤ 10^7, value of any tree ≤ 10^4.
    For any rectangular area 0 ≤ x1 ≤ x2 ≤ 10^7, 0 ≤ y1 ≤ y2 ≤ 10^7
    Note 1: There can be more than one trees at the same point.
    Note 2: The input data is large ( about 15 MB ), Be careful about your input output routines.
    .


    Added by:Ajay Somani
    Date:2008-02-05
    Time limit:8s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:CodeCraft 08, Problem Setter: Ajay Somani,Anshuman Singh









    SPOJ Problem Set (classical)

    2415. Kirchhof Law

    Problem code: RESIST


    Input

    Multiple test cases. For each test case:

    The first line contains integers N and M; N is a number of nodes in the circuit (2 < N <= 100), M is the number of resistors (0 <= M <= 300). Each of the next M lines consists of three integers Ai, Bi and Ri — description of a resistor that has resistance Ri connecting the nodes Ai and Bi (1 <= Ai , Bi <= N; 1 <= Ri <= 100).

    Input terminates by EOF.

    Output

    For each test case, output the total resistance between the nodes 1 and N rounded within two digits after a decimal points.

    Example

    Input:
    4 5
    1 2 15
    2 4 5
    1 3 10
    3 4 10
    2 3 1
    
    Output:
    9.40
    

    Added by:[Trichromatic] XilinX
    Date:2008-02-05
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Timus Online Judge, test data by g201513









    SPOJ Problem Set (main)

    2416. Distinct Subsequences

    Problem code: DSUBSEQ

    Given a string, count the number of distinct subsequences of it ( including empty subsequence ). For the uninformed, A subsequence of a string is a new string which is formed from the original string by deleting some of the characters without disturbing the relative positions of the remaining characters.
    For example, "AGH" is a subsequence of "ABCDEFGH" while "AHG" is not.

    Input

    First line of input contains an integer T which is equal to the number of test cases. You are required to process all test cases. Each of next T lines contains a string s.

    Output

    Output consists of T lines. Ith line in the output corresponds to the number of distinct subsequences of ith input string. Since, this number could be very large, you need to output ans%1000000007 where ans is the number of distinct subsequences.

    Example

    Input:
    3
    AAA
    ABCDEFG
    CODECRAFT
    
    
    Output:
    4
    128
    496
    

    Constraints and Limits

    T ≤ 100, length(S) ≤ 100000
    All input strings shall contain only uppercase letters.


    Added by:Ajay Somani
    Date:2008-02-05
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:C C++ 4.3.2 JAVA
    Resource:CodeCraft 08, Problem Setter: Jin Bin









    SPOJ Problem Set (classical)

    2417. Eliminate The Enemies

    Problem code: ENEMY

    In a modification of the popular game 'Pacman', the player has to move in a two-dimensional grid. Several cells of the grid are blocked. The player can start from any cell that is not blocked and can move in any of the directions, i.e. north, west,south or east, provided that the cells are unblocked.

    As soon as the player passes a cell, an enemy is generated in that cell, making it impossible for the player to pass through that cell again. Thus, the player can pass through any given cell only once. The player has to traverse all the unblocked cells in the grid in order to win .

    The player can begin at any free cell. Note that the same path with different starting points and even with the same starting point but with different paths of traversal is treated as different routes. The problem requires you to print the total number of all such possible routes.

    Input

    Each test case starts with a line containing two integers, m and n. Each of the next m lines contain a string of n characters describing the configuration of the grid. '*' denotes a blocked cell and '.' denotes unblocked cells. The input ends with a case having m = 0 and n = 0 and this case need not be processed.

    Output

    For each test case, print one line containing the total number of possible routes for the corresponding case. As this number can be quite large, you should print ans%1000000007 where ans is the required result.

    Example

    Input:
    3 3
    ...
    .*.
    ...
    3 7
    ...*...
    .*.*.*.
    .......
    3 3
    ***
    *.*
    ***
    0 0
    
    
    Output:
    16
    8
    1
    

    Constraints and Limits

    m ≤ 100, n ≤ 7, number of test cases ≤ 50


    Added by:Ajay Somani
    Date:2008-02-05
    Time limit:6s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8 ERL
    Resource:CodeCraft 08, Problem Setter: Jin Bin









    SPOJ Problem Set (classical)

    2418. Flying Frogs

    Problem code: FFROG

    WiseFrog, The King of FrogLand is on his Deathbed. He has 2 Sons, SensibleFrog and SmartFrog. Both of them are "Infinitely Intelligent". To decide who will succeed him as King, he devises a Strategy Game for the two Sons-

    An Arena is constructed, in the form of a Rectangle, having m X n Square Areas. They are labelled as (i,j), starting from the Upper Left extremity of the Arena [i=0,1,2...n-1; j=0,1,2...m-1]. The Squares in the Arena are filled with Flying Frogs, in a Random Manner, such that there can be any number of Frogs in each square.

    Once the Arena is ready, the 2 Frog Princes begin to play the Game, which is played in the following manner: SensibleFrog, being the King's favourite, starts the Game.

    Each Prince takes his turn alternately. In his turn, he is permitted a maximum of K moves, and a minumum of 1 move. A "Move" is defined as the Issuing of an Order to any Frog of his choice. The "order" consists of the Direction to jump in, and the Number of Squares to Cover ( which should be positive ), the directions of movement permitted being Up and Left Only. However, the Order must not be such that it causes the Frog to land outside the Arena. Being Flying Frogs, the frogs in the Arena can jump any distance without trouble.

    If there arrives a situation where the Prince having his turn does not have ANY move Possible ( that is, ALL the Flying Frogs are already at the top-left most square of the arena ), the other Prince is declared the Winner. Given all the Starting Conditions, your task is to find out who becomes the King of FrogLand.

    Input

    First line of input contains an integer T, equal to the number of test cases. Followed is the description of each of the T test cases and you are required to process all test cases. First line of each test case contains three integers m,n,k ( in this order ). Each of the next m lines contain n integers separated by spaces. Jth integer in ith line corresponds to the number of Flying Frogs in Square (i,j) in the arena.

    Output

    Output contains one line for each test case. You have to output "SensibleFrog Wins!." if SensibleFrog wins and "SmartFrog Wins!." otherwise.

    Example

    Input:
    3
    1 1 1
    837465
    2 2 1
    0 0
    0 1
    2 2 2
    0 0
    0 2
    
    
    Output:
    SmartFrog Wins!.
    SmartFrog Wins!.
    SensibleFrog Wins!.
    
    

    Constraints and Limits

    T ≤ 20, 1 ≤ m,n ≤ 1000, m*n ≤ 10^5, 1 ≤ k ≤ 10^9 , 0 ≤ Number of Frogs in a square ≤ 10^100.
    The total input data in each of the input file doesn't exceed 5 MB.


    Added by:Ajay Somani
    Date:2008-02-05
    Time limit:4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:CodeCraft 08, Problem Setter: Ajay Somani









    SPOJ Problem Set (classical)

    2419. G-Line Grid

    Problem code: GLGRID


    The 21st century introduces the multicores. As a result a research is going on in parallel Computing. With time the number of processor would grow very large. As of now, Professor Biloo at IIIT asks a student to implement the following code on multiple G-line processors.

            for(i=1;i<=x;i++){
                    for(j=1;j<=x;j++){
                            for(k=1;k<=a;k++){
                                    z=z%y;
                            }
                    }
                    for(j=1;j<=b;j++){
                            z=z/y;
                    }
            }
            for(i=1;i<=c;i++){
                    z=z%y;
            }
    

    The students experiments and finds that the only significant operations are the modulus(%) and division(/) operation which take almost equal time. The time taken by other operations may be ignored in the order analysis. He finds a algorithm to solve the problem in which these operations can be carried out in random order. For his testing he chooses M processors . Each processor will carry out exactly M operations (% or /) .The performance is optimal when such a scheme exactly covers all the operations.

    Puzzled, the student finds that this can only be done for some specific values of x for given a,b and c. He wants to trick the professor, so he needs few values of x for which his algorithm works. However, to make the professor feel that he manually did it these values of x need to be as small as possible.

    Given the values of a,b,c and k, output the first k values of x, for which the student's algorithm works.

    Note: The value of x should be greater than or equal to 0.

    Input

    The first line of input contains an integer t , the number of testcases. For each testcase , there is exactly one line which contains 4 space separated a,b,c and k.

    Output

    For each test case, output the corresponding k values of x, each in successive different lines.

    Example

    Input:
    1
    1 2 1 4
    
    
    Output:
    0
    1
    2
    3
    
    

    Constraints and Limits

    t ≤ 10. The values in the output vi ≤ 10^12. Each of the intermediate values will fit in a 64 bit variable. The values a,b,c would be such that 0 ≤ a,b,c ≤ 100 and b^2-4ac ≥ 0. k ≤ 1000.

    Note : Test data to this problem was modified on Feb 7.
    Note 2: There were some mistakes in the test data discovered on March 11, 2008. New tricky cases provided by Blue Mary are also put up now and some "Accepted" solutions have received wrong answer. My apologies to one and all for the mistakes.


    Added by:Ajay Somani
    Date:2008-02-05
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:CodeCraft 08 Anshuman Singh









    SPOJ Problem Set (classical)

    2420. Hospital at Hands

    Problem code: HHAND

    In a remote part of the Country, there lies a group of towns, quite far from any other areas. These towns are connected by a set of roads, having the property that there is exactly one path connecting any two towns, and every town is connected.

    Apollo Hospitals Ltd. decides to invest in this area, and build some Hospitals. Their analyst has a monumental task ahead of him. His job is to find out a Set of continuous towns, from among them, to build one hospital in each. The path connecting the first town to the last town in the set (which obviously passes through all the remaining ones) should not be more than length L, to avoid inconvenience to the visiting doctors. Also, the analyst has to make sure that his selection of target towns is such that the people of the area have to cover the least distance to reach the hospital closest to them.

    Thus, the towns where Hospitals will be built have to be chosen keeping in mind that the sum of distances that people from each town will need to cover, in order to reach the Hospital closest to them, should be Minimum. You have to find this minimum sum.

    Input

    First line of input contains an integer T which is equal to the number of test cases. You are required to process all test cases.Each test case starts with 2 space separated integers N,L. N denotes the number of towns and L is the length of path connecting first and last town in the set. Next N-1 lines follow each contains two space separated integers a and b denoting a road between A and B. A and B are 0 based.

    Output

    Output consists of T lines. Ith line in the output corresponds to the minimum sum total of the distances of all the towns with the nearest hospital for the Ith test case.

    Example

    Input:
    2
    3 1
    0 1
    1 2
    4 1
    0 1
    1 2
    2 3
    
    
    Output:
    1
    2
    

    Constraints and Limits

    T ≤ 30, n ≤ 10000, 0 < L ≤ 100


    Added by:Ajay Somani
    Date:2008-02-05
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:CodeCraft 08 Aryan-Gaurav,Ajay Somani









    SPOJ Problem Set (classical)

    2421. Incrementing The Integer

    Problem code: ININT

    Starting from the number '1', every time you can choose a digit from the current number and add it to the number itself. 23, for example, could be changed into 25 or 26. To get 100, using the above scheme, paths A and B are both possible. A requires 21 steps, but B needs only 17 (which is also the minimum)

    A. 1-2-4-8-16-17-18-19-20-22-24-28-36-39-48-56-62-68-76-83-91-100
    B. 1-2-4-8-16-17-24-28-36-39-48-56-62-68-76-83-91-100

    C is another 17 step solution for 100.

    C. 1-2-4-8-16-22-24-28-36-39-48-56-62-68-76-83-91-100

    Now, you are given several numbers, for each number, print the minimum steps S and number of solutions T. As T could be quite large, you should print T%1000000007 instead.

    Input

    Each line of input contains a integer K as a test case. Input ends with End Of File.

    Output

    For each test case print the minimum steps and solutions in a single line. If it's impossible to get the number, print "IMPOSSIBLE" instead. ( without the quotes ).

    Example

    Input:
    16
    100
    87
    
    Output:
    4 1
    17 2
    IMPOSSIBLE
    

    Constraints and Limits

    Number of test cases ≤ 100, 1 ≤ K ≤ 10^9.


    Added by:Ajay Somani
    Date:2008-02-05
    Time limit:6s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:CodeCraft 08, Problem Setter: Jin Bin









    SPOJ Problem Set (classical)

    2422. Jazzy Job

    Problem code: JAZZYJOB


    With the magnification of the Energy Crisis, Chemists have decided to re-examine the existing procedures of preparation of various Chemical Substances.

    As part of this Project, they list all the elements that they commonly find as raw material (Initial Reactants), and the ones that they intend to produce (Final Products). They also prepare an extensive list of the various known reactions/processes that are used to convert one substance to another.

    One major issue that they find is that the Initiation of many reactions needs absurdly large amounts of energy. They wish to keep low the activation energies used in the new procedures.

    Knowing all this, they now attempt to find out such methods of preparing the target substances :
    (1) in which the highest value of activation energy needed by any of the reactions that make up the path, in any of the methods, does not exceed a given upper value,
    (2) which minimizes the Total reactions/procedures performed in All the (Initial Reactant) --> (Final Product) conversions.

    Each substance, on being given a specific amount of energy, converts into some other substance. The formed substance is unique for a particular value of Energy. The process of creating each successive Target Substance (Final Product) starts from one of the Source Substances Only, and leaves no by-products.

    Your task is to find the minimum value of upper bound such that all final products are obtainable with that upper bound and for this minimum value, find out the minimum number of conversions to get all the final products.

    Note: None of the procedures are Reversible, unless explicity stated. Also, if a procedure Is reversible, the Energy requirement may or may not be same. You may assume that there is a limitless supply of the Initial Reactants.

    Input

    The first line contains an integer t which is the number of test cases. Each test case begins with a line containing three integers : number of Initial eactants(S), Final Products(D) and the total number of elements (N). Then S+D lines follow, first S lines contain IDs of Initial reactant ( 0 based ) and next D lines contain ID's of Final products ( 0 based). Then follows a line containing an integer R which is number of reactions possible. Then follow R lines, each containing three integers, the Substance(S), the converted substance(C) and the activation energy(A) units required for the reaction. 0 ≤ S,C < n.

    Output

    For each test case , output in a different line ,2 integers (a,b) separated by spaces where a is the minimum upper value and b is the minimum number of conversions required for corresponding a. In case that all final products are not obtainable for any value of upper bound, Print a single line with message "Excessive Energy.".

    Example

    Input:
    1
    2 2 6
    1
    3
    0
    3
    6
    1 2 2
    2 4 3
    4 5 1
    4 2 2
    3 0 4
    5 0 1
    
    
    Output:
    3 4
    

    Constraints and Limits

    N ≤ 10000, S ≤ N,D ≤ N,R < 100000 0 < A < 1000000000


    Added by:Ajay Somani
    Date:2008-02-05
    Time limit:4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:CodeCraft 08 Aryan-Gaurav









    SPOJ Problem Set (classical)

    2423. Minimal Triangulations of Graphs

    Problem code: MINTRIAN


    Check whether the given graph is chordal.

    Input

    The first line contains an integer 1<=t<=200 denoting the number of test cases. Then t graphs are given (not necessarily connected). Each graph is described by two lines. The first line contains a string of the form: n=nodes,m=edges: The second line gives the edges of the graph separated by commas. Each edge is given as a pair of vertices: {u,v}. Vertices of the graph are denoted with integers 0...,n-1.

    Output

    For each test case print YES if the graph is chordal, or NO if it isn't.

    Example

    Input:
    2
    n=6,m=4
    {0,1} {2,3} {3,4} {3,5} 
    n=6,m=7
    {0,3} {1,2} {1,3} {2,4} {2,5} {3,4} {3,5} 
    
    Output:
    YES
    NO
    

    Added by:Tomasz Goluch
    Date:2008-02-05
    Time limit:60s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6









    SPOJ Problem Set (classical)

    2426. Palindromes

    Problem code: PLD

    A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction, e.g. 'racecar', 'solos'.

    Task

    You are given a number k (2≤k≤30000) and a non-empty string S whose length does not exceed 30000 lowercase letters.
    We say two palindromes are different when they start from different positions. How many different palindromes of the length k does S contains?

    Input

    The first line contains K. The second line contains S. K does not exceed the length of S.

    Output

    The first and only line should consist of a single number - the number of palindromes found.

    Example

    Input:
    5
    ababab
    Output:
    2
    

    Added by:Chinh Nguyen
    Date:2008-02-07
    Time limit:0.5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6









    SPOJ Problem Set (classical)

    2450. Counting Rabbits

    Problem code: RABBIT1

    Rabbits are incredible animals. One of their more interesting characteristics is related with their reproduction. If we keep a couple of adult rabbits in optimal conditions of life, it is scientifically proved that, each month, that couple is capable of procreating a new couple of young rabbits. You should know that only the adult couples may procreate and that the time taken by a young couple of rabbits to grow (that is, to become adult) is of 1 month. For the convenience of this task, we will be dealing with immortal rabbits.

    Farmer Luis (FL) is a great admirer of rabbits. FL bought in the market 1 couple of adult rabbits (alive, of course) and know wants to raise as many rabbits as he can. Unfortunately, there is a little problem, FL has boxes where he can only put exactly 2^M (1 <= M <= 20) couples of rabbits (neither more nor less). FL can use as many boxes as he wishes as long as he fulfils the condition above. FL would like to know how many couples of rabbits he will not be able to put inside boxes if he raises rabbits for N (1 <= N <= 2147483647) months and then tries to ‘box’ them (put them inside boxes). You should help FL with these calculations. You must consider that FL starts with 1 adult couple of rabbits the 1st month, and that couples of rabbits reproduce and grow as stated in the 1st paragraph.

    Input

    Line 1: C (1 <= C <= 100), the number of calculations your program will be requested to do

    Lines 2-C+1: two integers N and M (in that order)

    Output

    Lines 1-C: on each lines print S, which is the number of rabbits FL will not be able to ‘box’ for calculation # i

    Example

    Input:
    1
    5 2
    
    Output:
    0
    
    
    Output explanation:

    After growing couples of rabbits during 5 months, FL has 5 adult couples and 3 young couples (8 couples in total). FL has boxes where can put 2^2 = 4 couples of rabbits, so he can use 2 boxes to ‘box’ all the 8 couples. If FL had instead grown couples of rabbits for 4 months, he would have 5 couples in total; thus 1 couple would have remained un-‘boxed’ (the answer would have been 1).


    Added by:Abel Nieto Rodriguez
    Date:2008-02-14
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Mindbend 2002 Programming Contest









    SPOJ Problem Set (classical)

    2485. Phone Lines

    Problem code: PHONELIN


    There are several cities and towers on a straight line. Towers can be set to connection-accepting by paying a cost. We are given the location (on the X-axis), of the towers and the cities. Our job is to set up certain towers as connection-accepting. Now every city, pays you an amount equal to D - distance_travelled_by_data, for every unit of data (for every tower) it can send. (distance_travelled_by_data = cityX - towerX); Our job here is to setup connections on differrent towers to get maximal profit.
    Each city when it wants to route some data to a tower works with the following algorithm:
    (1) Find the nearest tower to the left of the city.
    (2) If it is within the range 'D', it sends the data to that tower. If this tower exceeds the range D, or if the tower doesnt accept connections, the city cant send the data and stops immediately. (Doesnt check the next available tower);
    (3) If the data is sent sucessfully: Then the city
    (3.1) Skips three towers. (Doesnt care if these three towers are connection-accepting or not);
    (3.2) Tries to send data to the next tower (the fouth one after the skipping), by using step (2);

    Input format:
    Input consists of multiple testcases.
    First line of each test case, contains two integers: D C T; The range, the number of cities and the number of towers, respectively.
    Second line contains exactly C integers saying the location of the cities (on the X-axis).
    The next T lines contain exactly two integers: location[i] connection-cost[i]; which is the position of tower i, and the cost to setup tower i as connection-accepting;
    The input ends with a line: "-1 -1 -1"

    Output format:
    For each test case, output a single line saying the maximum amount of profit you can make.

    Constraints:
    Now two points (towers or cities), will have the same X-coordinate. T,C <= 100.

    Sample Input:
    4 9 6
    23
    43
    18
    15
    29
    50
    41
    31
    40
    32 2
    26 0
    46 7
    48 0
    50 3
    38 1
    -1 -1 -1
    

    Sample Output:
    5


    Added by:Prasanna
    Date:2008-02-25
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ByteCode 2008









    SPOJ Problem Set (classical)

    2511. Magic Program IV

    Problem code: MAGIC4

    Click here to get the solution(TLE)


    Added by:Bin Jin
    Date:2008-03-05
    Time limit:1s
    Source limit:2000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:own problem









    SPOJ Problem Set (classical)

    2525. Encoding

    Problem code: GNY07C

    Chip and Dale have devised an encryption method to hide their (written) text messages. They first agree secretly on two numbers that will be used as the number of rows (R) and columns (C) in a matrix. The sender encodes an intermediate format using the following rules:

    1. The text is formed with uppercase letters [A-Z] and <space>.
    2. Each text character will be represented by decimal values as follows:

      <space> = 0, A = 1, B = 2, C = 3, ..., Y = 25, Z = 26

    The sender enters the 5 digit binary representation of the characters’ values in a spiral pattern along the matrix as shown below. The matrix is padded out with zeroes (0) to fill the matrix completely. For example, if the text to encode is: "ACM" and R=4 and C=4, the matrix would be filled in as follows:

    A = 00001, C = 00011, M = 01101
             (one extra 0)

    The bits in the matrix are then concatenated together in row major order and sent to the receiver. The example above would be encoded as: 0000110100101100

    Input

    The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.

    Each dataset consists of a single line of input containing R (1<=R<=20), a space, C (1<=C<=20), a space, and a text string consisting of uppercase letters [A-Z] and <space>. The length of the text string is guaranteed to be <= (R*C)/5.

    Output

    For each dataset, you should generate one line of output with the following values: The dataset number as a decimal integer (start counting at one), a space, and a string of binary digits (R*C) long describing the encoded text. The binary string represents the values used to fill in the matrix in row- major order. You may have to fill out the matrix with zeroes (0) to complete the matrix.

    Example

    Input:
    4
    4 4 ACM
    5 2 HI
    2 6 HI
    5 5 HI HO
    
    Output:
    1 0000110100101100
    2 0110000010
    3 010000001001
    4 0100001000011010110000010
    

    Added by:Marco Gallotta
    Date:2008-03-11
    Time limit:60s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM Greater New York Regionals 2007









    SPOJ Problem Set (classical)

    2526. Decoding

    Problem code: GNY07D

    Chip and Dale have devised an encryption method to hide their (written) text messages. They first agree secretly on two numbers that will be used as the number of rows (R) and columns (C) in a matrix. The sender encodes an intermediate format using the following rules:

    1. The text is formed with uppercase letters [A-Z] and <space>.
    2. Each text character will be represented by decimal values as follows:

      <space> = 0, A = 1, B = 2, C = 3, ..., Y = 25, Z = 26

    The sender enters the 5 digit binary representation of the characters’ values in a spiral pattern along the matrix as shown below. The matrix is padded out with zeroes (0) to fill the matrix completely. For example, if the text to encode is: "ACM" and R=4 and C=4, the matrix would be filled in as follows:

    A = 00001, C = 00011, M = 01101
             (one extra 0)

    The bits in the matrix are then concatenated together in row major order and sent to the receiver. The example above would be encoded as: 0000110100101100

    Input

    The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.

    Each dataset consists of a single line of input containing R (1<=R<=20), a space, C (1<=C<=20), a space, and a string of binary digits that represents the contents of the matrix (R * C binary digits). The binary digits are in row major order.

    Output

    For each dataset, you should generate one line of output with the following values: The dataset number as a decimal integer (start counting at one), a space, and the decoded text message. You should throw away any trailing spaces and/or partial characters found while decoding.

    Example

    Input:
    4
    4 4 0000110100101100
    5 2 0110000010
    2 6 010000001001
    5 5 0100001000011010110000010
    
    Output:
    1 ACM
    2 HI
    3 HI
    4 HI HO
    

    Added by:Marco Gallotta
    Date:2008-03-11
    Time limit:60s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM Greater New York Regionals 2007









    SPOJ Problem Set (classical)

    2527. Flipping Burned Pancakes

    Problem code: GNY07E


    The cook at the Frobbozz Magic Pancake House sometimes falls asleep on the job while cooking pancakes. As a result, one side of a stack of pancakes is often burned. Clearly, it is bad business to serve visibly burned pancakes to the patrons. Before serving, the waitress will arrange the stacks of pancakes so that the burned sides are facing down. You must write a program to aid the waitress in stacking the pancakes correctly.

    We start with a stack of N pancakes of distinct sizes, each of which is burned on one side. The problem is to convert the stack to one in which the pancakes are in size order with the smallest on the top and the largest on the bottom and burned side down for each pancake. To do this, we are allowed to flip the top k pancakes over as a unit (so the k-th pancake is now on top and the pancake previously on top is now in the k-th position and the burned side goes from top to bottom and vice versa).

    For example (+ indicates burned bottom, - a burned top):

                   +1 -3 -2 [flip 2] ⇒ +3 -1 -2 [flip 1] ⇒ -3 -1 -2 [flip 3] ⇒
             +2 +1 +3 [flip 1] ⇒ -2 +1 +3 [flip 2] ⇒ -1 +2 +3 [flip 1] ⇒ +1 +2 +3
    You must write a program which finds a sequence of at most (3n – 2) flips, which converts a given stack of pancakes to a sorted stack with burned sides down.

    Input

    The first line of the input contains a single decimal integer, N, the number of problem instances to follow. Each of the following N lines gives a separate dataset as a sequence of numbers separated by spaces. The first number on each line gives the number, M, of pancakes in the data set. The remainder of the data set is the numbers 1 through M in some order, each with a plus or minus sign, giving the initial pancake stack. The numbers indicate the relative sizes of the pancakes and the signs indicate whether the burned side is up (-) or down (+). M will be, at most, 30.

    Output

    For each dataset, you should generate one line of output with the following values: The dataset number as a decimal integer (start counting at one), a space, the number of flips (K, where K >= 0) required to sort the pancakes and a sequence of K numbers, each of which gives the number of pancakes to flip on the corresponding sorting step. There may be several correct solutions for some datasets. For instance 3 2 3 is also a solution to the first problem below.

    Example

    Input:
    3
    3 +1 –3 –2
    4 –3 +1 –2 –4
    5 +1 +2 +3 +4 -5
    
    Output:
    1 6 2 1 3 1 2 1
    2 6 4 1 4 3 1 2
    3 3 5 1 5
    

    Added by:Marco Gallotta
    Date:2008-03-11
    Time limit:60s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM Greater New York Regionals 2007









    SPOJ Problem Set (classical)

    2528. Monkey Vines

    Problem code: GNY07F


    Deep in the Amazon jungle, exceptionally tall trees grow that support a rich biosphere of figs and juniper bugs, which happen to be the culinary delight of brown monkeys.

    Reaching the canopy of these trees requires the monkeys to perform careful navigation through the tall tree’s fragile vine system. These vines operate like a see-saw: an unbalancing of weight at any vine junction would snap the vine from the tree, and the monkeys would plummet to the ground below. The monkeys have figured out that if they work together to keep the vines properly balanced, they can all feast on the figs and juniper bugs in the canopy of the trees.

    A vine junction supports exactly two sub-vines, each of which must contain the same number of monkeys, or else the vine will break, leaving a pile of dead monkeys on the jungle ground. For purposes of this problem, a vine junction is denoted by a pair of matching square brackets [ ], which may contain nested information about junctions further down its sub-vines. The nesting of vines will go no further than 25 levels deep.

    You will write a program that calculates the minimum number of monkeys required to balance a particular vine configuration. There is always at least one monkey needed, and, multiple monkeys may hang from the same vine.

    Input

    The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.

    Each dataset consists of a single line of input containing a vine configuration consisting of a string of [ and ] characters as described above. The length of the string of [ and ] will be greater than or equal to zero, and less than or equal to 150.

    Output

    For each dataset, you should generate one line of output with the following values: The dataset number as a decimal integer (start counting at one), a space, and the minimum number of monkeys required to reach the canopy successfully. Assume that all the hanging vines are reachable from the jungle floor, and that all monkeys jump on the vines at the same time.

    Example

    Input:
    3
    []
    
    [[][[]]]
    
    Output:
    1 2
    2 1
    3 8
    

    Added by:Marco Gallotta
    Date:2008-03-11
    Time limit:60s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM Greater New York Regionals 2007









    SPOJ Problem Set (classical)

    2529. Model Rocket Height

    Problem code: GNY07G

    Just when you thought we had run out of model rocket height problems...

    Yet another method used to determine the height achieved by a model rocket is the vertical line method. Two observers A and B are spaced D feet apart along a base line along one edge of the flat test field. The launch platform is equidistant from observers A and B and L feet from the base line. Each observer has a theodolite or some other device for measuring angle above the horizontal (elevation angle) of a distant object and the azimuth angle (the angle the vertical plane of the sight line makes with the line from A through B measured counter-clockwise). Each measuring device is on a stand. A’s device is HA feet above the level of the launch platform and B’s device is HB feet above the level of the launch platform. When a rocket is fired, near the top of its flight, it deploys a parachute and emits a puff of smoke. Each observer measures the elevation angle and azimuth angle of the puff of smoke from their location. If the peak location is on the wrong side of the baseline or outside the lines determined by A and B perpendicular to the base line, it is out of bounds and disqualified. From this information, the height of the rocket may be determined as follows:

    Each sight line determines a vertical plane. These two planes intersect in a vertical line (thus the name of the method). Each sight line intersects this vertical line in a point. If these points are more than ERRDIST feet apart, an error is assumed and the flight is rejected. Otherwise, the point halfway between the two points where a sight line intersects the vertical line is computed. The rocket height is the distance of this midpoint above the launch platform.

    You must write a program which, given the parameters D (the distance in feet between observers A and B), L (the distance in feet from the base line to the launch platform), HA (the distance of the measuring device A above the launch platform in feet), HB (the distance of the measuring device B above the launch platform in feet), ERRDIST (the maximum distance between the intersection points of a sight line with the vertical line), α (the elevation angle of the rocket in degrees measured by the left observer A), β (the elevation angle of the rocket in degrees observed by the right observer B), γ (the azimuth angle in degrees measured by the left observer A) and δ (the azimuth angle in degrees measured by the right observer B), computes the height of the rocket above the launch platform in feet to the nearest foot.

    Input

    The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.

    The second line contains the parameters D, L, HA, HB and ERRDIST in that order as (floating point) decimal values. These values would be measured once at the beginning of the day and remain fixed through all rocket shots.

    Each succeeding line of input represents a single dataset. Each dataset will contain the angles α, β, γ and δ in that order (measured in degrees) as (floating point) decimal values for a rocket shot.

    Output

    For each dataset of four angles, the output consists of a single line . If angles α, β and γ are not strictly between 0 and 90 degrees or δ is not strictly between 90 degrees and 180 degrees, the line should contain the dataset number, a space and the word “DISQUALIFIED” (without the quotes). Otherwise, if the distance between the intersection points of a sight line with the vertical line is more that ERRDIST feet, the line should contain the dataset number, a space and the word “ERROR” (without the quotes). Otherwise, the line should contain the dataset number, a space and the height above the launch platform in feet to the nearest foot.

    Example

    Input:
    4
    100.0 300.0 5.25 2.92 5.00
    40.1 36.2 35.3 151.6
    64.9 71.1 15.7 160.1
    44.9 41.2 33.1 152.5
    44.9 41.2 33.1 52.5
    
    Output:
    1 50
    2 ERROR
    3 58
    4 DISQUALIFIED
    

    Added by:Marco Gallotta
    Date:2008-03-11
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM Greater New York Regionals 2007









    SPOJ Problem Set (classical)

    2530. Tiling a Grid With Dominoes

    Problem code: GNY07H

    We wish to tile a grid 4 units high and N units long with rectangles (dominoes) 2 units by one unit (in either orientation). For example, the figure shows the five different ways that a grid 4 units high and 2 units wide may be tiled.

    Write a program that takes as input the width, W, of the grid and outputs the number of different ways to tile a 4-by-W grid.

    Input

    The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.

    Each dataset contains a single decimal integer, the width, W, of the grid for this problem instance.

    Output

    For each problem instance, there is one line of output: The problem instance number as a decimal integer (start counting at one), a single space and the number of tilings of a 4-by-W grid. The values of W will be chosen so the count will fit in a 32-bit integer.

    Example

    Input:
    3
    2
    3
    7
    
    Output:
    1 5
    2 11
    3 781
    

    Added by:Marco Gallotta
    Date:2008-03-12
    Time limit:60s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM Greater New York Regionals 2007









    SPOJ Problem Set (classical)

    2531. Spatial Concepts Test

    Problem code: GNY07I

    The Flathead Testing Corporation (FTC) supplies various tests for Human Resources departments at many companies. One type of test they supply includes spatial concepts questions such as:

    When the following figure is folded back on the interior lines it forms a cube.

    Which of the following could be an image of one corner of the resulting cube?

    Unfortunately, FTC was recently embarrassed when one such question on a test had no solution among the choices and another (given in the example) had two solutions among the choices (1 and 3).

    FTC needs a routine which will read in a specification of the unfolded cube and specifications of corner views and determine, for each corner view, whether it is a view of a corner of the cube specified in the unfolded part.

    FTC uses the following images as faces of each cube. Each image is symmetrical about the vertical axis and has a distinguished end (up in each image).

    The unfolded cube is specified by a string of six pairs of a letter indicating the image on the face and a number indicating the orientation of the distinguished end of the face: 1 is up, 2 is right, 3 is down and 4 is left. The faces are specified in the order given in the following figure with the orientations indicated in the square to the right:

    So the unfolded cube in the example is specified as “F3E4E2D3C2F3”. FTC has a routine which reads this specification and generates the unfolded image for the question.

    The answer images are specified by three pairs of a letter and a digit indicating a face image and an orientation as indicated in the following diagram. The faces are specified in the order top, right, left (indicated by numbers in brackets in the figures), that is clockwise around the center vertex starting at the top. The orientation of the distinguished end of each face is indicated by the numbers on the edges in the diagram. They circle each face clockwise, starting at the center vertex.

    For the example, the answer figures are specified as “C2D2F2”, “E3F3C4”, “F2C2D2”, “D1E1F3” and “E1C1E1”. Again, FTC has a routine which reads this specification and generates each answer image for the question. They just need your routine to make sure there is exactly one correct answer to each question.

    Input

    The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.

    Each dataset consists of six lines of input. The first line of input is the specification for the folded out cube as described above. This line is followed by five lines, each of which gives the specification of one answer image as described above.

    Output

    For each dataset, output on a single line the dataset number, (1 through N), a blank, the number of answers which are solutions of the problem (corners of the cube specified in the folded out line), a blank and five ‘Y’ or ‘N’ characters separated by a blank indicating which of the answer images was a solution (‘Y’ for a solution, ‘N’ for not a solution).

    Example

    Input:
    2
    F3E4E2D3C2F3
    C2D2F2
    E3F3C4
    F2C2D2
    D1E1F3
    E1C1E1
    A2F4F1A3A3C4
    C3A4A2
    F3F4A1
    F3C4A1
    A2C3A2
    A4A4F1
    
    Output:
    1 2 Y N Y N N
    2 0 N N N N N
    

    Added by:Marco Gallotta
    Date:2008-03-12
    Time limit:60s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM Greater New York Regionals 2007









    SPOJ Problem Set (classical)

    2565. Another Permutation Problem

    Problem code: PERMUT3


    Given a permutation of n elements (1, 2, ..., n): A = (a1, a2, ..., an). We define a sequence P(A)=(p1, p2, …, pn-1) where pi = 0 if ai > ai+1 and pi = 1 if ai < ai+1. Given a permutation B, find the number of all permutations C where P(C)=P(B) including the permutation B itself.

    The length of your solution should not be more than 0.5kB.

    Input

    Multiple test cases. For each test case:

    The first line contains an integer n(1<= n <=100).The second line contains n integers representing the permutation, all of which are separated by single spaces.

    Input terminates by a single zero.

    Output

    For each test case:

    The output contains a single line with a single integer - the number of the permutations having the same value for P(A) when given the permutation A.

    Example

    Input:
    2
    1 2
    4
    1 3 2 4
    0
    
    Output:
    1
    5
    
    

    Added by:[Trichromatic] XilinX
    Date:2008-03-21
    Time limit:6s
    Source limit:512B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Southeastern European Regional Contest 2001









    SPOJ Problem Set (classical)

    2631. Chomp

    Problem code: CLK

    In Martin Gardner's book «Mathematical Games» the game of «Chomp!» is described as follows.

    For the game of «Chomp!» you need some pieces which are initially placed on a rectangular playing field and removed from it during the game. (If you are playing on paper then you can use a grid with zeros and cross them out during the game instead.) The game is played by 2 players, and moves are made in turns.

    Each turn is played as follows. The player chooses one piece, and removes all pieces which lie in the top-right rectangle, i.e., the rectangle having the chosen piece as the bottom-left corner. Thus, turn by turn, the players bite off pieces of the rectangular cookie, biting into it from the north-east (and the game takes its name from the chomp of their jaws). The winner is the player who forces his/her opponent to chomp the last, poisoned piece in the bottom left corner of the initial field.

    Game Chomp
    Fig 1. Example of one particular game in "Chomp!". In the initial state the pieces make up a 5х6 rectangle

    Those are the rules. And now imagine the following situation. Two players begin to play the game of «Chomp!» on a 10x10 rectangular field. You can see an intermediate position which was obtained after some turn. The opponents are thinking deeply. How the game will end is not clear, because it's humans who are playing, not computers… By the way, talking of computers: write a program, which for the given position output its outcome. Is the player whose turn it is to move able to win, even if his/her opponent uses the best possible strategy?

    Input

    The first line of input contains the total number of tests M, followed by M lines, with ten numbers on each of them (describing a single position on the playing field). These ten numbers are separated by spaces and describe the number of pieces in each column (columns are enumerated from left to right).

    Output

    You must output exactly M lines, containing the letter W if it is possible for the player who takes the next turn to win (even in case of the best possible strategy for the other player), or L otherwise.

    Example

    Input:
    3
    2 2 0 0 0 0 0 0 0 0
    2 1 0 0 0 0 0 0 0 0
    10 10 10 10 10 10 10 10 10 10
    
    Output:
    W
    L
    W
    

    Problem author: Filimonenkov D.O.


    Added by:Roman Sol
    Date:2008-03-10
    Time limit:10s-60s
    Source limit:10000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:ZCon 2008









    SPOJ Problem Set (classical)

    2643. Starcraft I

    Problem code: SC1

    Background

    You may play the game Starcraft I first before you do this problem ^_^.

    Description

    Suppose you are using Protoss. At the beginning of the game, you have n probes, a nexus and almost unlimited number of pylons. You can build a probe in the nexus per 3 Starcraft time units(STs), and this will cost you z units of minerals. A probe can gather x units of minerals or y units of gas per ST. What's the minimum time to get A units of minerals and B units of gas, if you build probes at nexus only and don't build any buildings?

    Assume that in the current map there are almost unlimited mineral fields and unlimited vespene geysers, and on each vespene geyser, a Protoss Assimilator has been built successfully.

    Input

    Multiple test cases, the number of them is given in the very first line.

    Each test case contains one line with 6 positive integers n, x, y, z, A, B separated by one space. All numbers in the input file will be less than 21.

    Output

    For each test case, output one line, which contains a single integer, the minimum time in ST.

    Example

    Input:
    1
    1 2 3 4 5 6
    
    Output:
    5
    

    Added by:[Trichromatic] XilinX
    Date:2008-04-09
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:www.blizzard.com









    SPOJ Problem Set (classical)

    2648. Archiver

    Problem code: KPARCH


    One of your friends wants to write his own archiver. He is going to replace neighboring equal substrings with only one copy. For example, he is going to change substring "AA" with something like "2(A)" and if "A" is long enough it will reduce the file size.

    But, before performing any coding stuff he wants to know how many such double substrings are there in the input file.

    He asks you to help him, because this task is very difficult for him.

    Input

    Input file contains the text to be archived. It will only contain Latin letters (big and small). Its size will not exceed 200000 symbols. Letters are case sensitive, i.e. "X" is not equal to "x".

    Output

    Write a number of substrings of input text which can be written as "AA", i.e. consist of two equal concatenated parts.

    Example

    Input:
    abcdefg
    
    Output:
    0
    
    Input:
    blabla
    
    Output:
    1
    
    Input:
    aCacaacaa
    
    Output:
    4
    

    Added by:Pavel Kuznetsov
    Date:2008-04-11
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:IT Festival Arkhangelsk 2007









    SPOJ Problem Set (classical)

    2649. Weird sorting

    Problem code: KPSORT

    You are given N integer numbers a1, a2, ..., aN. All you need to do is to sort them in non-decreasing order.

    The bad thing is you are only allowed to perform one action. You can pick any number in the sequence and then reverse all elements to the left and to the right of it.

    For example, suppose you were given the sequence (7, 1, 3, 9, 8) then, depending on the picked number you'll get the following results:

    Picked number Resulting sequence
    7(7, 8, 9, 3, 1)
    1(7, 1, 8, 9, 3)
    3(1, 7, 3, 8, 9)
    9(3, 1, 7, 9, 8)
    8(9, 3, 1, 7, 8)

    In this problem you are to figure out whether the given sequence can be sorted or not, applying allowed action zero or more times.

    Input

    Input will contain multiple test cases (not more than 100). Each case will start with the number of elements in the sequence N (1 ≤ N ≤ 100), followed by the N integers not exceeding 1000 by the absolute value. Input ends with the value N = 0.

    Output

    For each test case write "1" if corresponding sequence can be sorted and "0" otherwise. Output must not contain spaces or line breaks.

    Example

    Input:
    5
    7 1 3 9 8
    2
    2 1
    0
    
    Output:
    10
    

    Added by:Pavel Kuznetsov
    Date:2008-04-12
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:IT Festival Arkhangelsk 2007









    SPOJ Problem Set (classical)

    2658. Art of War

    Problem code: WAR


    The Warring States Period (473-22l BC) refers to the centuries of turmoil following the Spring and Autumn Period. China was divided into many little kingdoms that were constantly fighting with each other. Unlike in previous ages, when chivalry played an important role in battles and the states fought mostly for balance of power or to resolve disputes, in this period the aim of battle was to conquer and completely annihilate the other states. Eventually seven states, known as the ``Seven Great Powers'' rose to prominence: Qi, Chu, Yan, Han, Zhao, Wei, and Qin. After numerous alliances and counter-alliances, Qin defeated all the other states one by one, putting an end to the Warring States Period.

    You are given a map that shows the position of the capital for each state, and the borders between the states as a series of line segments. Your job is to determine which states were fighting with each other. This is pretty easy to determine - if two states had a common border, then they were fighting.

    Input

    The input contains several blocks of test cases. Each case begins with a line containing two integers: the number 1<= n <=600 of states, and the number 1<= m <= 4000 of border segments. The next n lines describe the coordinates of capitals, there are two integers in each line. The next m lines after that describe the m border segments. Each line contains four integers x1, y1, x2 and y2 meaning that there is a border segment from (x1, y1) to (x2, y2).(It is not given in the input what the two states on the two sides of the border are, but it can be deduced from the way the borders go.)

    Each state is enclosed by a continuous borderline. The states are surrounded by an infinite wasteland, thus a border segment either separates two states, or a state from the wasteland. It is not possible that the same state is on both sides of a border segment, or the wasteland is on both sides of a border segment. There is exactly one capital in each state, and there is no capital in the wasteland. The border segments do not cross each other, they can meet only at the end points.

    The input is terminated by a block with n = m = 0.

    Output

    For each test case, you have to output n lines that describe the enemies of the n states (recall that if two states share a border, then they are enemies). Each line begins with an integer, the number x of enemies the given state has. This number is followed by x numbers identifying the enemies of the state. These numbers are between 1 and n and number 1 refers to the first capital appearing in the input, number n refers to the last.

    Example

    Input:
    4 12
    3 2
    11 8
    12 17
    1 19
    0 0 10 0
    10 0 20 0
    20 0 20 10
    20 10 20 20
    20 20 10 20
    10 20 0 20
    0 20 0 10
    0 10 0 0
    10 0 10 10
    0 10 10 10
    20 10 10 10
    10 20 10 10
    4 16
    170 13
    24 88
    152 49
    110 130
    60 60 140 60
    140 60 140 140
    140 140 60 140
    60 140 60 60
    0 0 200 0
    200 0 200 200
    200 200 0 200
    0 200 0 0
    40 40 160 40
    160 40 160 160
    160 160 40 160
    40 160 40 40
    20 20 180 20
    180 20 180 180
    180 180 20 180
    20 180 20 20
    0 0
    
    Output:
    2 2 4
    2 1 3
    2 2 4
    2 1 3
    1 2
    2 1 3
    2 2 4
    1 3
    

    Added by:[Trichromatic] XilinX
    Date:2008-04-19
    Time limit:25s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Central European Programming Contest 2004(unofficial test data)









    SPOJ Problem Set (classical)

    2660. Example

    Problem code: EXAMPLE

    As you may have probably noticed a problem statement in a programming contest consists of several sections. The most important section is, of course, the "Example" section. Some seasoned contestants even start reading the problem statement from the examples. And, unfortunately, the least read section is the problem description section. It is quite disappointing for the problem authors because they feel that their writing skills are largely wasted.

    So the authors decided to describe examples in the same language, as the rest of the problem statement using the following rules.

    • Natural integer numbers shall be written in plain English. The numbers shall be less than one hundred. The designator number shall be written before numbers, except when the corresponding number is used as a repetition factor. For example, number zero, number sixteen, or number sixty one.
    • Sequences of characters (strings) shall be written either in quotes, or in apostrophes, for example "John's pen", or '5" tall'. Note, that ' may be used in strings enclosed in " and vice versa. The designator string shall be written before strings, for example string 'Hello'.
    • The designator space denotes one space character.
    • A number, string or space may be prefixed with a repetition factor. The repetition factor is a number greater than one. The designator after the repetition factor is written in plural form. For example, four numbers five, or six strings 'A'. If the repetition factor is used for numbers, the numbers are separated with one space character. So, the former example means 5 5 5 5, but the latter example AAAAAA.
    • Let the numbers, strings and spaces with possible repetition factors be called fragments. Fragments may be organized into sequences using the followed by copulative. For example, number five followed by number six. One implicit space character is assumed between numbers, a number and a string, and a string and a number so the example above means 5 6.
    • An example is described line by line. The first line is always described as The first line.... The following lines are described either as The next line... or as The next # lines..., where # is a number greater than one. Empty lines are described as is empty or are empty. Other lines are described as contains or contain followed by sequences. The first letter of a sentence is capitalized. The sentence is terminated by a full stop (.). The full stop is not separated by space from the preceding word, but is separated by at least one space from the next word.

    Input

    The input contains a free-flow text describing an example. Words are separated by an arbitrary number of spaces and newlines. There are no whitespace characters after the last full stop. The total size of the input will be no greater than 1 MB.

    Output

    The output should contain the decoded example. The total size of the output shall be no greater than 1 MB.

    Example

    Input:
    The first line contains four
    numbers twenty eight. The next
    line is empty. The next two
    lines contain six strings '-'.
    The next line contains number
    four followed by number seventy
    seven followed by string 'meat'
    followed by three strings "!".
    
    Output:
    28 28 28 28
    
    ------
    ------
    4 77 meat!!!
    
    

    Added by:[Trichromatic] XilinX
    Date:2008-04-19
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC NEERC Moscow Subregional Contest 2007









    SPOJ Problem Set (classical)

    2661. Illumination

    Problem code: ILLUM

    Two cubes and a light bulb are placed in a three-dimensional euclidean space. You are expected to find out if one of them casts shadow on the other one and if so, calculate the area of this shadow.

    Input

    Multiple test cases. For each test case:

    The first line of the input contains the coordinates of the bulb. It is followed by two groups of four lines each that describe the cubes. Each line of the cube description contains the coordinates of a vertex (see the figure where the vertices are marked and labeled in the same order as they are given in the input).

    All the coordinates are given with 5 digits after decimal point. It is guaranteed that the cubes do not intersect, the light bulb is outside both of them, and doesn’t lie on any of the planes that contain their faces. A light bulb should be regarded as a point light source.

    Input terminates by EOF.

    Output

    For each test case:

    The output should contain a single line with two numbers separated with a space character. The first one is the number of the cube that has a shadow on it (1 or 2). The second is the area of the shadow. If none of the given cubes casts shadow on the other the output should contain a single number -1.

    Note: if your output has an error with absolute value less than 10-2, it will be judged as Accepted. i.e. You may output any number of digits after decimal point.

    Example

    Input:
    -1.00000 1.00000 1.00000
    0.00000 0.00000 0.00000
    2.00000 0.00000 0.00000
    0.00000 2.00000 0.00000
    0.00000 0.00000 2.00000
    5.00000 0.00000 0.00000
    7.00000 0.00000 0.00000
    5.00000 2.00000 0.00000
    5.00000 0.00000 2.00000
    0.00000 0.00000 0.00000
    1.00000 1.00000 1.00000
    2.00000 1.00000 1.00000
    1.00000 2.00000 1.00000
    1.00000 1.00000 2.00000
    -1.00000 -1.00000 -1.00000
    -1.00000 -2.00000 -1.00000
    -2.00000 -1.00000 -1.00000
    -1.00000 -1.00000 -2.00000
    
    Output:
    2 4.000
    -1
    

    Added by:[Trichromatic] XilinX
    Date:2008-04-19
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC NEERC Moscow Subregional Contest 2007









    SPOJ Problem Set (classical)

    2662. Put a Point in a Hyperspace

    Problem code: PUTIN


    Input

    Multiple test cases, the number of them is given in the very first line.

    For each test case:

    The first line contains 3 space-separated integers K(2<=K<=30), S(2<=S<=10000), M(0<=M<=20). M lines follow, each contains K non-negative integers aij(1<=i<=M, 1<=j<=K), which shows that there is one point (ai1, ai2, ... aik) in the K-D hyperspace. No two point will be the same, and none of them lies on any (coordinate) axis.

    Output

    For each test case:

    Output a single integer which shows the number of the points B(b1, b2, ... bk) in the hyperspace satiesfied the following constraints:

    • B is not on any (coordinate) axis.
    • For each 1<= i <= M, there exist j, 1<=j<=k, such that bj < aij.
    • For each 1<=j<=k, bj is a non-negative integer.
    • The sum of bj doesn't exceed S.

    Example

    Input:
    1
    2 4 2
    1 3
    2 1
    
    Output:
    2
    
    Hint
    

    The two points are (1,1) and (1,2).


    Added by:[Trichromatic] XilinX
    Date:2008-04-19
    Time limit:90s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC NEERC Northern Subregion Contest 2003; description by Blue Mary









    SPOJ Problem Set (classical)

    2666. Query on a tree IV

    Problem code: QTREE4


    You are given a tree (an acyclic undirected connected graph) with N nodes, and nodes numbered 1,2,3...,N. Each edge has an integer value assigned to it(note that the value can be negative). Each node has a color, white or black. We define dist(a, b) as the sum of the value of the edges on the path from node a to node b.

    All the nodes are white initially.

    We will ask you to perfrom some instructions of the following form:

    • C a : change the color of node a.(from black to white or from white to black)
    • A : ask for the maximum dist(a, b), both of node a and node b must be white(a can be equal to b). Obviously, as long as there is a white node, the result will alway be non negative.

    Input

    • In the first line there is an integer N (N <= 100000)
    • In the next N-1 lines, the i-th line describes the i-th edge: a line with three integers a b c denotes an edge between a, b of value c (-1000 <= c <= 1000)
    • In the next line, there is an integer Q denotes the number of instructions (Q <= 100000)
    • In the next Q lines, each line contains an instruction "C a" or "A"

    Output

    For each "A" operation, write one integer representing its result. If there is no white node in the tree, you should write "They have disappeared.".

    Example

    Input:
    3
    1 2 1
    1 3 1
    7
    A
    C 1
    A
    C 2
    A
    C 3
    A
    
    Output:
    2
    2
    0
    They have disappeared.
    
    

    Some new test data cases were added on Apr.29.2008, all the solutions have been rejudged.


    Added by:Qu Jun
    Date:2008-04-25
    Time limit:1s-6s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:william









    SPOJ Problem Set (classical)

    2668. Polygon

    Problem code: POLYSSQ

    You are given N different points in the plane. No any 3 of them are collinear. Write a program that finds out the smallest area of a convex polygon with K vertices which are taken from the given points.

    Input

    Two integers, N and K, are written on the first line in the standard input. It follows N lines, each containing a pair of coordinates for the corresponding given point. Every two numbers on a line in the input are separated by a space. Constraints: 0 < N < 50, 0 < K < 11. The coordinates of the given points are nonnegative integers, less than 9999.

    Output

    Your program has to output an integer that is equal to the integer part of minimal area. If there does not exist any convex polygon as is described above, your program has to output 0.

    Example

    Input:
    4 3
    0 0
    1 1
    0 10
    10 0
    
    Output:
    5
    

    Added by:Chinh Nguyen
    Date:2008-04-26
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Bulgarian OI









    SPOJ Problem Set (classical)

    2670. Count Minimum Spanning Trees

    Problem code: MSTS

    Your task is simple in this problem: count the number of minimum spanning tree (Wikipedia) in a simple undirected graph. The number of minimum spanning trees mean in how many ways you can select a subset of the edges of the graphs which forms a minimum spanning tree.

    Input

    The first line of input contains two integers N (1 ≤ N ≤ 100), M (1 ≤ M ≤ 1000). Nodes are labeled from 1 to N. In the following M lines, every line contains three integers ai, bi, ci, representing an undirected edge from node ai to node bi, with weight ci. (1 ≤ aibiN, 1 ≤ ci ≤ 1,000,000,000). You can assume there is at most one edge between two nodes, and the graph described by input is connected.

    Output

    Print the answer % 31011.

    Example

    Input:
    4 6
    1 2 1
    1 3 1
    1 4 1
    2 3 2
    2 4 1
    3 4 1
    
    Output:
    8
    

    Added by:Bin Jin
    Date:2008-04-29
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:Jiangsu TSC for Chinese NOI 08, day 2









    SPOJ Problem Set (classical)

    2699. Recursive Sequence (Version II)

    Problem code: SPP


    Sequence (ai) of natural numbers is defined as follows:

    ai = bi (for i <= k)
    ai = c1ai-1 + c2ai-2 + ... + ckai-k (for i > k)

    where bj and cj are given natural numbers for 1<=j<=k. Your task is to compute am + am+1 + am+2 + ... + an for given m <= n and output it modulo a given positive integer p.

    Input

    On the first row there is the number C of test cases (equal to about 50).
    Each test contains four lines:
    k - number of elements of (c) and (b) (1 <= k <= 15)
    b1,...,bk - k natural numbers where 0 <= bj <= 109 separated by spaces
    c1,...,ck - k natural numbers where 0 <= cj <= 109 separated by spaces
    m, n, p - natural numbers separated by spaces (1 <= m <= n <= 1018, 1<= p <= 108)

    Output

    Exactly C lines, one for each test case: (am + am+1 + am+2 + ... + an) modulo p.

    Example

    Input:
    1
    2
    1 1
    1 1
    2 10 1000003
    
    Output:
    142
    

    Added by:[Trichromatic] XilinX
    Date:2008-05-15
    Time limit:7s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:Problem SEQ









    SPOJ Problem Set (classical)

    2709. Untitled Problem

    Problem code: UNTITLED

    We consider a sequence S1 is equal to a sequence S2, if and only if they satisfy the following conditions:

    • The length of them are equal.
    • Let Len be the length of them. For each i,j(1 <= i, j <= Len, i != j):If S1[i] is smaller than S1[j], S2[i] must be smaller than S2[j]; If S1[i] is greater than S1[j], S2[i] must greater than S2[j].

    Now you are given a sequence S and another N sequences T1, T2 …. TN.

    We say position i is OK, if and only if S[1..i] contains a suffix which is equal to a sequence from { T1, T2 ... TN }. You need to print the positions which is OK in increasing order.

    Input

    Multiple test cases, the number of them(no more than 3) is given in the very first line.

    For each test case:

    • The first line contains an integer M (M > 1) which denote the number of sequences. i.e. M = N + 1.
    • M * 2 lines follow, each two lines describe one sequence.For each two lines, the first line contains an integer L which denote the length of this sequence. The second line contains L integers(all the integers don't exceed 231-1) that represent this sequence. The first sequence described is S, the next N sequences represent T1 ... TN.
    • You can assume that there are no same integer in any one sequence.
    • The length of S is no more than 400000, and the total length of T is no more than 100000.

    Output

    For each test case: Print the positions which is OK in increasing order.

    Example

    Input:
    2
    2
    1
    1
    1
    2
    3
    3
    3 1 2
    2
    4 5
    2
    10 1
    
    Output:
    1
    2
    3
    

    Added by:Qu Jun
    Date:2008-05-19
    Time limit:8s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:Based on a problem from USACO 2005 Dec Gold Division









    SPOJ Problem Set (classical)

    2713. Can you answer these queries IV

    Problem code: GSS4

    You are given a sequence A of N(N <= 100,000) positive integers. There sum will be less than 1018. On this sequence you have to apply M (M <= 100,000) operations:

    (A) For given x,y, for each elements between the x-th and the y-th ones (inclusively, counting from 1), modify it to its positive square root (rounded down to the nearest integer).

    (B) For given x,y, query the sum of all the elements between the x-th and the y-th ones (inclusively, counting from 1) in the sequence.

    Input

    Multiple test cases, please proceed them one by one. Input terminates by EOF.

    For each test case:

    The first line contains an integer N. The following line contains N integers, representing the sequence A1..AN.
    The third line contains an integer M. The next M lines contain the operations in the form "i x y".i=0 denotes the modify operation, i=1 denotes the query operation.

    Output

    For each test case:

    Output the case number (counting from 1) in the first line of output. Then for each query, print an integer as the problem required.

    Print an blank line after each test case.

    See the sample output for more details.

    Example

    Input:
    5
    1 2 3 4 5
    5
    1 2 4
    0 2 4
    1 2 4
    0 4 5
    1 1 5
    4
    10 10 10 10
    3
    1 1 4
    0 2 3
    1 1 4
    
    Output:
    Case #1:
    9
    4
    6
    
    Case #2:
    40
    26
    
    

    Added by:[Trichromatic] XilinX
    Date:2008-05-21
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS PERL 6
    Resource:Own problem, used in ACM/ICPC Regional Contest, Shanghai 2011 preliminary









    SPOJ Problem Set (classical)

    2714. Cow Cars

    Problem code: COWCAR

    N (1 ≤ N ≤ 50,000) cows conveniently numbered 1, ..., N are driving in separate cars along a highway in Cowtopia. Cow i can drive in any of M different high lanes (1 ≤ M ≤ N) and can travel at a maximum speed of Si (1 ≤ Si ≤ 1,000,000) km/hour.

    After their other bad driving experience, the cows hate collisions and take extraordinary measures to avoid them. On this highway, cow i reduces its speed by D (0 ≤ D ≤ 5,000) km/hour for each cow in front of it on the highway (though never below 0 km/hour). Thus, if there are K cows in front of cow i, the cow will travel at a speed of max(Si - D*K, 0). While a cow might actually travel faster than a cow directly in front of it, the cows are spaced far enough apart so crashes will not occur once cows slow down as described.

    Cowtopia has a minimum speed law which requires everyone on the highway to travel at a a minimum speed of L (1 ≤ L ≤ 1,000,000) km/hour, so sometimes some of the cows will be unable to take the highway if they follow the rules above. Write a program that will find the maximum number of cows that can drive on the highway while obeying the minimum speed limit law.

    Input

    The first line contains the four integers N, M, D, and L. For the next N lines, line i+1 contains the integer Si.

    Output

    Print a single integer denoting the maximum number of cows that can take the highway.

    Example

    Input:
    3 1 1 5
    5
    7
    5
    
    Output:
    2
    

    We can obtain two cows by putting either cow with speed 5 first and the cow with speed 7 second.


    Added by:Neal Wu
    Date:2008-05-22
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:USACO Open 2008









    SPOJ Problem Set (classical)

    2715. Glasnici

    Problem code: GLASNICI

    A long straight road connects two villages. Along the road, N messengers are stationed and, when needed, they exchange messages using mostly their legs, but also their vocal cords and ears. The first messenger (the closest to the first village) has a radio-receiver which he uses to keep track of current ongoings in the country. When he finds out who has been evicted from whichever reality show is currently popular, he starts running as fast as he can to share the unfortunate (or fortunate) news with everyone else. While running, he shouts the name of the evicted person so that any fellow messengers that are close enough can hear him. Meanwhile, the remaining messengers do not merely sit and wait, but also run themselves, all with the selfless goal of sharing the news with everyone as fast as possible. The running and shouting proceeds as follows:

    • Each of the messengers may run whenever, in either direction, at a speed of at most 1 unit per second, or may decide not to run at all and stand still.
    • All messengers that know the news shout it at all times. One messenger can hear another messenger shouting (and learn the news) if the distance between them is at most K units.

    Write a program that, given the initial locations of the messengers, determines the least amount of time (in seconds) needed for all messengers to learn the news. The location of every messenger is given with a positive real number – the distance from the first village. As mentioned above, initially only the first messenger knows the news.

    Input

    The first line contains the integer T (1 ≤ T ≤ 25), the number of test cases. Then for each test case, the first line contains the real number K (0 ≤ K ≤ 1,000,000), the largest distance at which two messengers can hear each other, and the integer N (1 ≤ N ≤ 100,000), the number of messengers. Each of the following N lines contains one real number D (0 ≤ D ≤ 1,000,000,000), the distance of one messenger from the first village. The distances will be sorted in ascending order. It is possible for multiple messengers to be at the same location.

    Output

    For each test case, output a real number, the least time for all messengers to learn the news. Your output needs to be within 0.01 of the official output.

    Example

    Input:
    2
    3.000 2
    0.000
    6.000
    2.000 4
    0.000
    4.000
    4.000
    8.000
    
    Output:
    1.500
    1.000
    
    Warning: large input/output data.
    Added by:Neal Wu
    Date:2008-05-23
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:Croatian Olympiad in Informatics 2008









    SPOJ Problem Set ()

    2716. Maximal Quadrilateral Area

    Problem code: QUADAREA

    You are trying to build a house, but unfortunately you currently have only four available walls with side lengths a, b, c, and d. You want your house to be as big as possible, so you would like to know the largest possible area of any quadrilateral you can construct with these four side lengths.

    Input

    The first line contains the integer T (1 ≤ T ≤ 2,000), the number of tests. Each test contains a single line with four real numbers: a, b, c, and d (0 < a, b, c, d < 1,000). Note that it will always be possible to form a valid quadrilateral with these lengths; that is, the sum of any three side lengths will be strictly larger than the other one.

    Output

    For each test case, print a single line containing the largest possible area. Your output will be accepted if it is within 0.01 of the official answer.

    Example

    Input:
    2
    1 2 1 2
    0.5 0.5 0.5 0.5
    
    Output:
    2.00
    0.25
    

    For the first test case, it is optimal to construct a rectangle, and for the second, a square is optimal.


    Added by:Neal Wu
    Date:2008-05-24
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS









    SPOJ Problem Set (classical)

    2727. Army Strength

    Problem code: ARMY

    The next MechaGodzilla invasion is on its way to Earth. And once again, Earth will be the battleground for an epic war.

    MechaGodzilla's army consists of many nasty alien monsters, such as Space Godzilla, King Gidorah, and MechaGodzilla herself.

    To stop them and defend Earth, Godzilla and her friends are preparing for the battle.

    Problem specification

    Each army consists of many different monsters. Each monster has a strength that can be described by a positive integer. (The larger the value, the stronger the monster.)

    The war will consist of a series of battles. In each battle, the weakest of all the monsters that are still alive is killed.

    If there are several weakest monsters, but all of them in the same army, one of them is killed at random. If both armies have at least one of the weakest monsters, a random weakest monster of MechaGodzilla's army is killed.

    The war is over if in one of the armies all monsters are dead. The dead army lost, the other one won.

    You are given the strengths of all the monsters. Find out who wins the war.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case starts with line containing two positive integers NG and NM – the number of monsters in Godzilla's and in MechaGodzilla's army. Two lines follow. The first one contains NG positive integers – the strengths of the monsters in Godzilla's army. Similarly, the second one contains NM positive integers – the strengths of the monsters in MechaGodzilla's army.

    Output specification

    For each test case, output a single line with a string that describes the outcome of the battle.

    If it is sure that Godzilla's army wins, output the string "Godzilla".

    If it is sure that MechaGodzilla's army wins, output the string "MechaGodzilla".

    Otherwise, output the string "uncertain".

    Example

    input:
    2
    
    1 1
    1
    1
    
    3 2
    1 3 2
    5 5
    
    output:
    Godzilla
    MechaGodzilla
    

    Hint

    In the first test case, there are only two monsters, and they are equally strong. In this situation, MechaGodzilla's monster is killed and the war ends.

    In the second test case, the war will consist of three battles, and in each of them one of Godzilla's monsters dies.

    For all the test cases, int in C/C++/Java or longint in Pascal is enough.


    Added by:[Trichromatic] XilinX
    Date:2008-05-24
    Time limit:1s-2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:IPSC 2008









    SPOJ Problem Set (classical)

    2728. Breaking in

    Problem code: BREAK

    Mayco has recently been hired as a security consultant for a well-known software company. At the moment, he's working on his first assignment – trying to determine which of the company's servers would be the best targets for potential attackers. It is a bit difficult, though, because some of the servers "trust" some of the others. If an attacker compromises a server, he or she can also freely access all servers that trust it (and servers that trust them, and so on).

    By definition, the importance of a server S is the number of servers the attacker would be able to access if he compromised S. The most important servers are those with the highest importance. (Note that there can be more than one most important server. This is also illustrated in the example below.)

    Problem specification

    The network consists of N computers, numbered 1 to N, inclusive. The trust between computers is described by M ordered pairs (A,B) of numbers, denoting that computer A trusts computer B. The trust is not assumed to be mutual – i.e., if a computer A trusts computer B, it does not necessarily imply that computer B trusts computer A.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case starts with a line containing the numbers N and M(1<= N <=9000, 1<= M <= 52000). Each of the following M lines contains two integers, A and B, denoting that computer A trusts computer B.

    Output specification

    For each test case, the output shall contain one line with the numbers of all of the most important servers. The numbers must be listed in increasing order and separated by single spaces.

    Example

    input:
    2
    
    5 4
    3 1
    3 2
    4 3
    5 3
    
    6 5
    1 2
    2 3
    3 1
    1 4
    5 6
    
    output:
    1 2
    4
    

    Note

    Blue Mary has found a pruning which will make the program very efficient. So the time limit of the hard test case is changed from 60 seconds to 15 seconds. If you have some even harder test case, please send it to me, and I'll add it to the standard input file.


    Added by:[Trichromatic] XilinX
    Date:2008-05-24
    Time limit:1s-15s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:IPSC 2008









    SPOJ Problem Set (classical)

    2731. Inventing Test Data

    Problem code: INVENT


    Preparing a problem set is a very hard task. There are always issues with clarity of problem statements, bugs in our solutions, input or output data, and so on. Sometimes, despite our best efforts, these issues are only found during the contest, and this can really spoil it.

    To prevent this from happening in the future, we already started to prepare data for IPSC 2009, and we decided to use your help in doing so. Currently we are working on a simple textbook problem: "Given a weighted undirected complete graph, find its minimum spanning tree." (See the Definitions below if you are not sure what a spanning tree is.)

    Almost everythig is already prepared for this problem: the problem statement, our solution, and also the desired output data. The only (and quite important) thing left is the input data. But creating it is not as simple as it looks.

    The bad thing that can happen is that a graph can have more than one minimum spanning tree. If we used such a graph in the input data, we would have to write a complicated checker. And we are too lazy to do this. Therefore we want to find an input data that avoids such cases.

    Moreover, we want the test data to be good. If all the other edges were much more expensive, the minimum spanning tree would be obvious, and many incorrect algorithms would be able to find it. Therefore we want all the edge weights to be as small as possible.

    Definitions

    A graph is a set of nodes, and a set of links. Each link connects two nodes. Each pair of nodes is connected by at most one link. Each link is assigned a positive integer (its weight). The sum of the weights of all links in a graph is the weight of that graph.

    If every two nodes are connected by a link we say that the graph is complete.

    A sequence of nodes v0, …, vn such that for each i the nodes vi and vi+1 are connected by a link, is called a path.

    If every two nodes in a graph are connected by a path, we say that the graph is connected.

    If there is exactly one path between any two nodes we say that graph is a tree.

    A spanning subgraph of a connected graph G is a connected graph that contains all nodes of G and some (not necessarily all) of its links.

    A spanning subgraph T of a graph G is called the minimum spanning tree of G if and only if no other spanning subgraph has a smaller weight.

    Note that a given graph can have more than one spanning tree. Also note that a spanning tree is always a tree.

    Problem specification

    Given a weighted tree T, you are to find the minimum possible weight of a complete graph G such that T is the only minimum spanning tree of G.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    First line of each test case contains an integer N(N <= 15000) – number of nodes in the tree. The nodes are numbered from 1 to N, inclusive. The following N - 1 lines contain a description of the tree. Each of these lines contains three integers ai, bi, wi(1<= ai, bi <=N, 1<= wi <=10000) meaning that node ai is connected with node bi by a link with weight wi.

    Output specification

    For each test case, the output shall contain one line containing one integer – the minimum possible weight of a complete graph such that the given tree is its unique minimal spanning tree.

    Example

    Input:
    2
    
    3
    1 2 4
    2 3 7
    
    4
    1 2 1
    1 3 1
    1 4 2
    
    output:
    19
    12
    

    Hint

    In the first test case, we have to add a link between nodes 1 and 3 with weight at least 8.

    In the second test case, the optimal graph contains the link 2 - 3 with weight 2, and links 2 - 4 and 3 - 4 with weigths 3 each.


    Added by:[Trichromatic] XilinX
    Date:2008-05-24
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:IPSC 2008









    SPOJ Problem Set (classical)

    2733. K Equal Digits

    Problem code: KEQ

    Every once in a while, Mishka Jabereen sends an interesting mathematical puzzle to his friends. This week's puzzle will be about so-called "repetitive" numbers – the ones whose decimal expansion has just one kind of digit in it. (Examples of such numbers include 7, 11, and 5555.) The puzzle is about finding the largest repetitive number subject to two additional restrictions:

    (A) It must be divisible by at least one number from a given set. 
    (B) It can not have more than a given number of digits.
    

    A concrete example of such a problem statement would be: Find the largest repetitive number with at most 47 digits, which is divisible by 42 or 47! Mishka is currently playing around with a few such problem statements and he'd like to know all the answers, so that he can choose the nicest one.

    Problem specification

    A puzzle is described by a number K, the maximal number of digits allowed in the repetitive number, and a set of numbers d1, d2, …, dR. Your task is to find the greatest repetitive number X that has at most K digits when written in decimal notation, and it is divisible by at least one of the di.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case starts with a line containing the numbers K(1<= K <=109) and R(1<= R <=7). The next R lines contain the numbers di(1<= di <=1014).

    Output specification

    We can describe a repetitive number by specifying its number of digits N and the digit D it contains.

    For each test case, the output shall contain one line containing two integers N and D that describe the largest repetitive number that satisfies the conditions from the problem statement.

    Example

    input:
    3
    
    47 2
    42
    47
    
    99 4
    123
    234
    345
    456
    
    3 1
    4700
    
    output:
    46 9
    96 6
    1 0
    

    Note that in the third test case "3 0" would not be a correct answer, as "000" is not a valid integer.

    Blue Mary's Note: This problem can be solved in a very short time but a naive solution may not terminate within 5 hours. Thanks to Robert Gerbicz's help.

    Another note: some new test case are added on Jun.6, 2010.


    Added by:[Trichromatic] XilinX
    Date:2008-05-24
    Time limit:17s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:IPSC 2008









    SPOJ Problem Set (classical)

    2734. Large party

    Problem code: LARGE


    Irena and Sirup are organizing their engagement party next weekend. They want to invite almost everybody. They have just bought a very big round table for this occasion. But they are now wondering how should they distribute people around the table. Irena claimed that when there are more than K women next to each other, this group will chat together for the whole night and won't talk to anybody else.

    Sirup had no other choice but to agree with her. However, being a mathematician, he quickly became fascinated by all the possible patterns of men and women around the table.

    Problem specification

    There will be N people sitting at the round table. Some of them will be men and the rest will be women.

    Your task is to count in how many ways it is possible to assign the places to men and women in such a way that there will not be more than K women sitting next to each other.

    If one assignment can be made from another one by rotating all the people around the table, we consider them equal (and thus count this assignment only once).

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    The input for each test case consists of a single line that contains the two integers N(1<= N <1000) and K.

    Output specification

    For each test case output a single line with one integer – the number of ways how to distribute people around the table, modulo 100000007.

    Example

    input:
    3
    
    3 1
    
    3 3
    
    4 1
    
    output:
    2
    4
    3
    
    Hint:

    In the first test case there are two possibilities: MMM or MMW (M is a man, W is a woman).

    In the second test case there are two more possibilities: MWW and WWW.

    In the third test case the three possibilities are: MMMM, MMMW, and MWMW.

    A Note: There are almost 1000 test cases, most of which are randomly generated (huge) ones.


    Added by:[Trichromatic] XilinX
    Date:2008-05-24
    Time limit:8s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:IPSC 2008









    SPOJ Problem Set (classical)

    2735. Simplify the Railroad System

    Problem code: RAIL

    The Slovak national railroad company has recently built new tracks. They want to update their railroad map according to these changes. But they want the map to be as simple as possible. So they decided to remove from the map all the stations that have exactly two other direct connections to other stations (i.e., a single railroad passing through the station).

    Problem specification

    You will be given the complete map of Slovak railroads. It consists of railway stations numbered from 1 to N, and railroad segments between some pairs of these stations. For each railroad segment we are given its length.

    Your task is to remove all such stations that are directly connected with exactly two other stations, and output the new map. The new map must contain correct distances between the remaining stations.

    Input specification

    The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

    Each test case begins with a line with two integers N(1<= N <=2000) and M(1<= M <=3000). The number N denotes the number of stations and M is the number of railroad segments. M lines follow, each with 3 integers a, b, and c (1 <= a,b <= N) specifying that there is a railroad segment of length c connecting stations a and b.

    You can assume that in each test case there is a path between every two stations, and there is at most one railroad between any pair of cities directly. Also, there will always be at least 2 stations that are not directly connected to exactly two other stations.

    Output specification

    For each test case, the output shall consist of multiple lines. The first line shall contain a positive integer K – the number of railroads on the simplified map. Each of the next K lines shall contain three integers a, b (a must be no more than b), and c stating that there is a railroad of length c between stations a and b on the simplified map.

    The railroads should be listed in lexicographic order, i.e. the railroad with less a should be listed first,if two railroads have the same a, then the one with less b should be listed first. If two railroad have the same a and b, the one with less c should be listed first.

    Print a blank line between outputs for different test cases.

    Example

    input:
    2
    
    3 2
    1 2 1
    2 3 1
    
    4 4
    1 2 1
    2 3 2
    3 4 3
    4 2 1
    
    output:
    1
    1 3 2
    
    2
    1 2 1
    2 2 6
    

    Hint

    In the first case we removed station 2 beacuse it had exactly 2 direct connections.

    In the second case we removed stations 3 and 4. We see that there is now a railroad from station 2 back to itself.

    For all the test cases, int in C/C++/Java or longint in Pascal is enough.


    Added by:[Trichromatic] XilinX
    Date:2008-05-24
    Time limit:1s-2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:IPSC 2008









    SPOJ Problem Set (classical)

    2737. Perfect Rhyme

    Problem code: PRHYME


    A perfect rhyme is not a crime,
    it is something that exceeds time, 
    a bit of science, a piece of art, 
    soft as a pillow, sharp as a dart.

    Everyone tried it, but only few chosen ones succeeded. It is a hard task with an unclear path, but a famous end – should you reach it. Many compare it to finding the Holy Grail, or even to finding Waldo. The task is to find a perfect rhyme.

    Problem specification

    Given is a wordlist L, and a word w. Your task is to find a word in L that forms a perfect rhyme with w. This word u is uniquely determined by these properties:

    • It is in L.
    • It is different from w.
    • Their common suffix is as long as possible.
    • Out of all words that satisfy the previous points, u is the lexicographically smallest one.

    Notes

    A prefix of a word is any string that can be obtained by repeatedly deleting the last letter of the word. Similarly, a suffix of a word is any string that can be obtained by repeatedly deleting the first letter of the word.

    For example, consider the word different.

    This word is both its own prefix and suffix. Its longest other prefix is differen, and its longest other suffix is ifferent. The string rent is its yet another, even shorter suffix. The strings eent and iffe are neither prefixes nor suffixes of the word different.

    Let u and v be two different words. We say that u is lexicographically smaller than v if either u is a prefix of v, or if i is the first position where they differ, and the i-th letter of u is earlier in the alphabet than the i-th letter of v.

    For example, dog is smaller than dogs, which is smaller than dragon (because o is less than r).

    Input specification

    The input file consists of two parts. The first part contains the wordlist L, one word per line. Each word consists of lowercase English letters only, and no two words are equal.

    The first part is terminated by an empty line.

    The second part follows, with one query word w per line.

    You may assume that in either part of the input, the length of a word will be no more than 30. And the number of words in each part of the input will be no more than 250000. The input file will be less than 5MB.

    Output specification

    For each query in the input file output a single line with its perfect rhyme. The output must be in lowercase.

    Example

    input:
    perfect
    rhyme
    crime
    time
    
    crime
    rhyme
    
    output:
    time
    crime
    

    In the second test case, there were two candidates that had an equally long common suffix (crime and time), the lexicographically smaller one was chosen.

    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2008-05-26
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:IPSC 2008









    SPOJ Problem Set (classical)

    2742. Summing Sums

    Problem code: SUMSUMS

    The N (1 ≤ N ≤ 50,000) cows, conveniently numbered 1, 2, ..., N, are trying to learn some encryption algorithms. After studying a few examples, they have decided to make one of their own! However, they are not very experienced at this, so their algorithm is very simple:

    Each cow i is given a starting number Ci (0 ≤ Ci < 90,000,000), and then all the cows perform the following process in parallel:

    • First, each cow finds the sum of the numbers of the other N-1 cows.
    • After all cows are finished, each cow replaces her number with the sum she computed. To avoid very large numbers, the cows will keep track of their numbers modulo 98,765,431.

    They told Canmuu the moose about it in November; he was quite impressed. Then one foggy Christmas Eve, Canmuu came to say:

    "Your algorithm is too easy to break! You should repeat it T (1 ≤ T ≤ 1,414,213,562) times instead."

    Obviously, the cows were very frustrated with having to perform so many repetitions of the same boring algorithm, so after many hours of arguing, Canmuu and the cows reached a compromise: You are to calculate the numbers after the encryption is performed!

    Input

    • Line 1: Two space-separated integers: N and T.
    • Lines 2..N+1: Line i+1 contains a single integer: Ci.

    Output

    • Lines 1..N: Line i contains a single integer representing the number of cow i (modulo 98,765,431) at the end of the encryption.

    Example

    Input:
    3 4
    1
    0
    4
    
    Output:
    26
    25
    29
    

    The following is a table of the cows' numbers for each turn:

              Cows' numbers
    Turn    Cow1  Cow2  Cow3
     0        1     0     4
     1        4     5     1
     2        6     5     9
     3       14    15    11
     4       26    25    29
    
    Warning: large input/output data.
    Added by:Neal Wu
    Date:2008-05-28
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:USACO Chn 2007









    SPOJ Problem Set ()

    2743. Prefix Tiling

    Problem code: PRETILE

    You are given a string S with N (1 ≤ N ≤ 100,000) characters from 'A' to 'Z', inclusive. For an integer L between 1 and N, inclusive, we define match (L) as the length of the longest prefix of S that can be tiled by the length-L prefix of S; more specifically, match (L) is the smallest 0-based index k such that S [k] ≠ S [k mod L], or N if no such k exists. For example, when S = "ABCAB", match (1) = 1, match (3) = 5, and match (4) = 4. Compute the sum match (1) + match (2) + ... + match (N).

    Input

    The first line contains the integer T (1 ≤ T ≤ 10), the number of tests. For each test, there is a single line containing the string S.

    Output

    For each test case, print a single line containing one integer: the value of match (1) + match (2) + ... + match (N).

    Example

    Input:
    2
    ABCAB
    ZZZZZZ
    
    Output:
    17
    36
    

    For the first test case, match (1) + match (2) + match (3) + match (4) + match (5) = 1 + 2 + 5 + 4 + 5 = 17. For the second, the sum is equal to 6 * 6 = 36.

    Warning: large input/output data.
    Added by:Neal Wu
    Date:2008-05-28
    Time limit:1s-2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL









    SPOJ Problem Set (classical)

    2815. Increasing Subsequences

    Problem code: INCSEQ

    Given a sequence of N (1 ≤ N ≤ 10,000) integers S1, ..., SN (0 ≤ Si < 100,000), compute the number of increasing subsequences of S with length K (1 ≤ K ≤ 50 and K ≤ N); that is, the number of K-tuples i1, ..., iK such that 1 ≤ i1 < ... < iK ≤ N and Si1 < ... < SiK.

    Input

    The first line contains the two integers N and K. The following N lines contain the integers of the sequence in order.

    Output

    Print a single integer representing the number of increasing subsequences of S of length K, modulo 5,000,000.

    Example

    Input:
    4 3
    1
    2
    2
    10
    
    Output:
    2
    

    The two 3-tuples are (1, 2, 4) and (1, 3, 4), both corresponding to the subsequence 1, 2, 10.


    Added by:Neal Wu
    Date:2008-06-20
    Time limit:1s-2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:









    SPOJ Problem Set (classical)

    2816. Common Subsequences

    Problem code: CSUBSEQS

    You are given four strings, each consisting of at most 50 lower case letters ('a'-'z'). Count the number of non-empty common subsequences of them (the number of distinct non-empty strings which are subsequences of all four strings). Note that a subsequence does not have to be contiguous.

    Input

    Four lines: each line consists of a single string.

    Output

    An integer representing the answer.

    Example

    Input:
    aabb
    abab
    baba
    acba
    
    Output:
    4
    

    The four sequences are "a", "b", "aa", and "ab".


    Added by:Bin Jin
    Date:2008-06-22
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:co-author: Neal Wu









    SPOJ Problem Set (classical)

    2817. Distinct Increasing Subsequences

    Problem code: INCDSEQ

    Given a sequence of N (1 ≤ N ≤ 10,000) integers S1, ..., SN (0 ≤ Si < 1,000,000,000), compute the number of distinct increasing subsequences of S with length K (1 ≤ K ≤ 50 and K ≤ N).

    Input

    The first line contains the two integers N and K. The following N lines contain the integers of the sequence in order.

    Output

    Print a single integer representing the number of distinct increasing subsequences of S of length K, modulo 5,000,000.

    Example

    Input:
    4 3
    1
    2
    2
    10
    
    Output:
    1
    

    The only increasing subsequence of length 3 is 1, 2, 10.


    Added by:Bin Jin
    Date:2008-06-22
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:co-author: Neal Wu









    SPOJ Problem Set (classical)

    2826. Round-Robin Scheduling

    Problem code: RRSCHED

    A computer processor is given N tasks to perform (1 ≤ N ≤ 50,000). The i-th task requires Ti seconds of processing time (1 ≤ Ti ≤ 1,000,000,000). The processor runs the tasks as follows: each task is run in order, from 1 to N, for 1 second, and then the processor repeats this again starting from task 1. Once a task has been completed, it will not be run in later iterations. Determine, for each task, the total running time elapsed once the task has been completed.

    Input

    The first line of the input contains the integer N, and the next N lines contain the integers T1 through TN.

    Output

    Output N lines, the i-th of which contains an integer representing the time elapsed when task i has been processed.

    Example

    Input:
    5
    8
    1
    3
    3
    8
    
    Output:
    22
    2
    11
    12
    23
    

    The second task is completed during the first iteration, finishing 2 seconds in. On the third iteration, the third and fourth tasks complete at 11 seconds and 12 seconds, respectively. Finally, on the eighth iteration, the first and last tasks complete at 22 seconds and 23 seconds, respectively.

    Warning: large input/output data.

    Note: This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2006, TopCoder, Inc. All rights reserved.

    (See this post for more information.)


    Added by:Neal Wu
    Date:2008-07-02
    Time limit:1s-2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:TopCoder High School SRM 52 (with raised constraints)









    SPOJ Problem Set ()

    2829. Time Limit Exceeded

    Problem code: TLE

    Given integers N (1 ≤ N ≤ 50) and M (1 ≤ M ≤ 15), compute the number of sequences a1, ..., aN such that:

    • 0 ≤ ai < 2M
    • ai is not divisible by ci (0 < ci ≤ 2M)
    • ai & ai+1 = 0 (that is, ai and ai+1 have no common bits in their binary representation)

    Input

    The first line contains the number of test cases, T (1 ≤ T ≤ 10). For each test case, the first line contains the integers N and M, and the second line contains the integers c1, ..., cN.

    Output

    For each test case, output a single integer: the number of sequences described above, modulo 1,000,000,000.

    Example

    Input:
    1
    2 2
    3 2
    
    Output:
    1
    

    The only possible sequence is 2, 1.

    time limit has been doubled, enjoy :D


    Added by:Bin Jin
    Date:2008-07-04
    Time limit:1s-10s
    Source limit:5000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.0.0-8 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
    Resource:co-author: Neal Wu









    SPOJ Problem Set (classical)

    2832. Find The Determinant III

    Problem code: DETER3

    Given a NxN matrix A, find the Determinant of A % P.

    Input

    Multiple test cases (the size of input file is about 3MB, all numbers in each matrix are generated randomly).

    The first line of every test case contains two integers , representing N (0 < N < 201) and P (0 < P < 1,000,000,001). The following N lines each contain N integers, the j-th number in i-th line represents A[i][j] (- 1,000,000,001 < A[i][j] < 1,000,000,001).

    Output

    For each test case, print a single line contains the answer.

    Example

    Input:
    1 10
    -528261590
    2 2
    595698392 -398355861
    603279964 -232703411
    3 4
    -840419217 -895520213 -303215897
    537496093 181887787 -957451145
    -305184545 584351123 -257712188
    
    Output:
    0
    0
    2
    

    Added by:Bin Jin
    Date:2008-07-05
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C++ 4.0.0-8
    Resource:own problem









    SPOJ Problem Set (classical)

    2833. Super Dice Game

    Problem code: SDGAME


    Alice and Bob are playing a game. The game consists of a circular track of M (2 <= M <= 1,000,000,000) cells labeled 0 through M - 1. Initially both players start at cell 0. The game progresses by having each player take turns rolling one of N (1 <= N <= 10,000) 'super-dice' labeled 0 through N - 1. The actual mechanics of the 'super-dice' is not very well understood; however, it is known that they will only ever turn up a number between 0 and 1,000,000,000 inclusive after a roll. After rolling the super-dice the number of spaces a player moves is determined by the product of a contiguous subsequence of the values shown on the dice (There are special rules for determining the range that vary each move that will not be discussed).

    To make matters more complicated, after any turn if Alice and Bob land on the same cell the value shown on all dice is multiplied by the label of the cell they are on. Note in this way it is possible for some dice to show numbers greater than 1,000,000,000. This multiplier does not apply to future rolls.

    After playing this game for a while, Alice and Bob have grown frustrated because the calculations became too difficult. Given the series of R (1 <= R <= 100,000) dice rolls and ranges, help Alice and Bob determine their position after each move. Assume that all dice start out showing 1.

    Input

    The first line contains R, N, and M each separated by a space. R lines follow. Each line will contain d v a b separated by a space. d indicates the label of the dice rolled. v indicates the value shown on the dice. a and b indicate the range of dice used to determine the move distance.

    Output

    R lines containing the position of the player that just rolled after their roll.

    Example

    Input:
    6 4 20
    1 5 1 1
    3 10 2 3
    2 3 0 3
    1 2 0 3
    1 5 1 2
    0 7 0 1
    
    Output:
    5
    10
    15
    10
    10
    0
    
    Output Explanation:
    
    For your assistance, here is the state of the dice after each turn:
    [1, 5, 1, 1]
    [1, 5, 1, 10]
    [1, 5, 3, 10]
    [1, 2, 3, 10]
    [10, 50, 30, 100]
    [7, 50, 30, 100]
    
    Warning: large Input/Output data, be careful with certain languages
    Added by:Mark Gordon
    Date:2008-07-05
    Time limit:2s-10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:own problem









    SPOJ Problem Set (classical)

    2835. Memory Limit Exceeded

    Problem code: MLE


    Given n points on X-Y plane. To each point, you are to find the other point who is closest to it with respect to the Euclidean distance.

    Input

    T (<= 15) test cases. Each starts with an integer n (2<= n <=100000). Then n lines follow. Each contains two space-seperated integers, the X and Y coordinate of the corresponding point, respectively. No two points in one test case will coincide.

    Output

    For each test case, output n lines. The i-th of them should contain the squared distance between the i-th point from the input and its nearest neighbour.

    Example

    Input:
    2
    10
    17 41
    0 34
    24 19
    8 28
    14 12
    45 5
    27 31
    41 11
    42 45
    36 27
    15
    0 0
    1 2
    2 3
    3 2
    4 0
    8 4
    7 4
    6 3
    6 1
    8 0
    11 0
    12 2
    13 1
    14 2
    15 0
    
    Output:
    200
    100
    149
    100
    149
    52
    97
    52
    360
    97
    5
    2
    2
    2
    5
    1
    1
    2
    4
    5
    5
    2
    2
    2
    5
    
    Warning: enormous input/output data, be careful with certain languages

    Note: In Sphere Online Judge system, "Memory Limit Exceeded" will be shown as "Runtime Error(other)", with the 0.00 second run-time & 92-200k memory used, or "Runtime Error(SIGSEGV)" with 250M memory used.


    Added by:[Trichromatic] XilinX
    Date:2008-07-08
    Time limit:23s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Central European Programming Contest, Wroc³aw 2008









    SPOJ Problem Set ()

    2852. Broken Keyboard

    Problem code: BROKEN

    Bruce Force's keyboard is broken, only a few keys are still working. Bruce has figured out he can still type texts by switching the keyboard layout whenever he needs to type a letter which is currently not mapped to any of the m working keys of the keyboard.

    You are given a text that Bruce wishes to type, and he asks you if you can tell him the maximum number of consecutive characters in the text which can be typed without having to switch the keyboard layout. For simplicity, we assume that each key of the keyboard will be mapped to exactly one character, and it is not possible to type other characters by combination of different keys. This means that Bruce wants to know the length of the largest substring of the text which consists of at most m different characters.

    Input

    The input contains several test cases, each test case consisting of two lines. The first line of each test case contains the number m (1 ≤ m ≤ 128), which specifies how many keys on the keyboard are still working. The second line of each test case contains the text which Bruce wants to type. You may assume that the length of this text does not exceed 1 million characters. Note that the input may contain space characters, which should be handled like any other character.

    The last test case is followed by a line containing one zero.

    Output

    For each test case, print one line with the length of the largest substring of the text which consists of at most m different characters.

    Example

    Input:
    5
    This can't be solved by brute force.
    1
    Mississippi
    0
    
    Output:
    7
    2
    

    Added by:Adrian Kuegel
    Date:2008-07-12
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:University of Ulm Local Contest 2008









    SPOJ Problem Set (classical)

    2853. Decode the Strings

    Problem code: PDECODE


    Bruce Force has had an interesting idea how to encode strings. The following is the description of how the encoding is done:

    Let x1,x2,...,xn be the sequence of characters of the string to be encoded.

    1. Choose an integer m and n pairwise distinct numbers p1,p2,...,pn from the set {1, 2, ..., n} (a permutation of the numbers 1 to n).
    2. Repeat the following step m times.
    3. For 1 ≤ i ≤ n set yi to xpi, and then for 1 ≤ i ≤ n replace xi by yi.

    For example, when we want to encode the string "hello", and we choose the value m = 3 and the permutation 2, 3, 1, 5, 4, the data would be encoded in 3 steps: "hello" -> "elhol" -> "lhelo" -> "helol".

    Bruce gives you the encoded strings, and the numbers m and p1, ..., pn used to encode these strings. He claims that because he used huge numbers m for encoding, you will need a lot of time to decode the strings. Can you disprove this claim by quickly decoding the strings?

    Input

    The input contains several test cases. Each test case starts with a line containing two numbers n and m (1 ≤ n ≤ 80, 1 ≤ m ≤ 109). The following line consists of n pairwise different numbers p1,...,pn (1 ≤ pin). The third line of each test case consists of exactly n characters, and represent the encoded string. The last test case is followed by a line containing two zeros.

    Output

    For each test case, print one line with the decoded string.

    Example

    Input:
    5 3
    2 3 1 5 4
    helol
    16 804289384
    13 10 2 7 8 1 16 12 15 6 5 14 3 4 11 9
    scssoet tcaede n
    8 12
    5 3 4 2 1 8 6 7
    encoded?
    0 0
    
    Output:
    hello
    second test case
    encoded?
    

    Added by:Adrian Kuegel
    Date:2008-07-12
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:University of Ulm Local Contest 2008









    SPOJ Problem Set (classical)

    2855. Forest

    Problem code: FOREST2

    Bruce Force is standing in the forest. He wonders what is the tree trunk the farthest away which is not blocked from his view by other tree trunks.

    Bruce has made a map of the trees in the forest. The map shows his current position as the origin of a cartesian coordinate system. Tree i is shown on the map as a circle with the center (xi, yi) and radius ri. You may assume that a tree trunk is visible if and only if there exists a line segment on the map from the origin (0,0) to a point on the border of the circle representing the tree trunk, where the line segment does not intersect or touch another circle.

    Input

    The input contains several test cases. The first line of each test case contains one number n (1 ≤ n ≤ 1000), where n specifies how many trees are on the map. The following n lines contain 3 integers xi, yi, ri each, (-10000 ≤ xi, yi ≤ 10000 , 1 ≤ ri ≤ 1000 ) where (xi, yi) is the center of the circle representing tree trunk i, and ri is the radius of the circle. You may assume that no two circles in the input intersect, i.e., for any two circles, the distance between their centers is more than the sum of their radii. Moreover, you may assume that no circle contains the origin.

    The last test case is followed by a line containing one zero.

    Output

    For each test case, print one line with the maximum euclidean distance from the origin to a visible tree. The distance to a tree should be measured using the point of the tree closest to the origin, no matter if this point is in fact visible or not.

    Round the answer to 3 digits after the decimal point.

    Example

    Input:
    3
    10 10 11
    1 1 1
    -20 -10 20
    5
    1 2 2
    -2 1 1
    2 -1 1
    -1 -2 2
    10000 -10000 1000
    0
    Output:
    3.142
    1.236
    

    Added by:Adrian Kuegel
    Date:2008-07-12
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:University of Ulm Local Contest 2008









    SPOJ Problem Set (classical)

    2856. Help Bob

    Problem code: HELPBOB


    Bob loves Pizza but is always out of money. One day he reads in the newspapers that his favorite pizza restaurant, Alfredo's Pizza Restaurant, is running a competition: they will donate a big pizza to the first person who will tell them the lowest price per area that can be achieved by buying any of the pizzas at most once. "That task is easy!", thinks Bob, "For each pizza I just calculate the average price and the lowest quotient will be the answer.".

    Unfortunately the problem is a bit more complicated: with some pizzas Alberto gives out discount coupons for getting another pizza cheaper and even worse, those coupons can be combined. The pizzas have to be bought one after the other, and it is not possible to use a coupon to get a discount retrospectively for a pizza which has already been bought. Can you help Bob to become the first to solve this task and to get a pizza for free?

    Input

    The input file contains several test cases. Each test case starts with a number m, the number of pizzas Alfredo offers. Input is terminated by m=0. Otherwise, 1 ≤ m ≤ 15. Then follow m lines describing the pizzas. Each of those following lines describes pizza i (1 ≤ i ≤ m) and starts with 3 integer numbers pi, ai and ni specifying the price of the pizza, its area and the number of discount coupons you get when buying it, 1 ≤ pi ≤ 10000, 1 ≤ ai ≤ 10000 and 0 ≤ ni < m. Then follow ni pairs of integer numbers xi,j and yi,j specifying the index xi,j (1 ≤ xi,j ≤ m, xi,j ≠ i) of the pizza you get a discount coupon for and the discount in percentage terms yi,j (1 ≤ yi,j ≤ 50) you get when buying pizza xi,j. You may assume that for each i the values xi,j are pairwise distinct.

    Output

    For each test case print one line containing the lowest price per area that can be achieved by buying any of the pizzas at most once. Round this number to 4 places after the decimal point. Note that you can combine an arbitrary number of discount coupons: for a pizza with price 10 and two rabatt coupons for that pizza with a 50 and a 20 on it, you would only have to pay 10 * 0.8 * 0.5 = 4 monetary units.

    Example

    Input:
    1
    80 30 0
    2
    200 100 1 2 50
    200 100 0
    5
    100 100 2 3 50 2 50
    100 100 1 4 50
    100 100 1 2 40
    600 600 1 5 10
    1000 10 1 1 50
    0
    Output:
    2.6667
    1.5000
    0.5333
    

    Added by:Adrian Kuegel
    Date:2008-07-12
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:University of Ulm Local Contest 2008









    SPOJ Problem Set (classical)

    2877. Another understanding of Super Dice Game

    Problem code: SDGAME2

    When we were trying to solve the problem SDGAME, we got a misunderstanding of it.We didn't get AC until we were told the original meaning.But we think our kind of understanding is also interesting and is worthy of doing.So enjoy the problem.

    Alice and Bob are playing a game. The game consists of a circular track of M (2 <= M <= 1,000,000,000) cells labeled 0 through M - 1. Initially both players start at cell 0. The game progresses by having each player take turns rolling one of N (1 <= N <= 10,000) 'super-dice' labeled 0 through N - 1. The actual mechanics of the 'super-dice' is not very well understood; however, it is known that they will only ever turn up a number between 0 and 1,000,000,000 inclusive after a roll. After rolling the super-dice the number of spaces a player moves is determined by the product of a contiguous subsequence of the values shown on the dice (which are available)(There are special rules for determining the range that vary each move that will not be discussed).If all the values are unavailable,the player moves one space.Iff the number on the dice is more than 1,000,000,000 or less than 0, the dice is unavailable.

    To make matters more complicated, after any turn if Alice and Bob land on the same cell the value shown on all dice(neither available nor unavailable) is multiplied by the label of the cell they are on. Note in this way it is possible for some dice to show numbers greater than 1,000,000,000.

    After playing this game for a while, Alice and Bob have grown frustrated because the calculations became too difficult. Given the series of R (1 <= R <= 100,000) dice rolls and ranges, help Alice and Bob determine their position after each move. Assume that all dices start out showing 1 and all dices are available.

    Input

    The first line contains R, N, and M each separated by a space. R lines follow. Each line will contain d v a b separated by a space. d indicates the label of the dice rolled. v indicates the value shown on the dice. a and b indicate the range of dice used to determine the move distance.

    Output

    R lines containing the position of the player that just rolled after their roll.

    Example

    Input:
    6 4 4
    0 1000000000 1 1
    1 999999998 1 1
    2 500000000 3 3
    0 1 2 2
    3 1 0 3
    0 6 0 3
    
    Output:
    1
    2
    2
    2
    0
    0
    
    Output Explanation:
    
    For your assistance, here is the state of the dice after each turn:(* means unavailable)
    Before all rolls:
    [1,1,1,1](0,0)
    After first roll:
    [1000000000,1,1,1](1,0)
    After second roll:
    [1000000000,999999998,1,1](1,2)
    After third roll:
    [1000000000,999999998,500000000,1](2,2)
    All dices multiply 2:
    [*,*,1000000000,2](2,2)
    After forth roll:
    [1,*,1000000000,2](2,2)
    All dices multiply 2:
    [2,*,*,4](2,2)
    After fifth roll:
    [2,*,*,1](0,2)
    After sixth roll:
    [6,*,*,1](0,0)
    All dices multiply 0:
    [0,0,0,0](0,0)
    
    

    Test data has been updated, all submissions have been rejudged


    Added by:Zhang Taizhi
    Date:2008-07-24
    Time limit:2s-4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:Based on 2833. Super Dice Game









    SPOJ Problem Set (classical)

    2878. Knights of the Round Table

    Problem code: KNIGHTS

    Being a knight is a very attractive career: searching for the Holy Grail, saving damsels in distress, and drinking with the other knights are fun things to do. Therefore, it is not very surprising that in recent years the kingdom of King Arthur has experienced an unprecedented increase in the number of knights. There are so many knights now, that it is very rare that every Knight of the Round Table can come at the same time to Camelot and sit around the round table; usually only a small group of the knights is there, while the rest are busy doing heroic deeds around the country.

    Knights can easily get over-excited during discussions-especially after a couple of drinks. After some unfortunate accidents, King Arthur asked the famous wizard Merlin to make sure that in the future no fights break out between the knights. After studying the problem carefully, Merlin realized that the fights can only be prevented if the knights are seated according to the following two rules:

    * The knights should be seated such that two knights who hate each other should not be neighbors at the table. (Merlin has a list that says who hates whom.) The knights are sitting around a round table, thus every knight has exactly two neighbors.

    * An odd number of knights should sit around the table. This ensures that if the knights cannot agree on something, then they can settle the issue by voting. (If the number of knights is even, then it can happen that "yes" and "no" have the same number of votes, and the argument goes on.)

    Merlin will let the knights sit down only if these two rules are satisfied, otherwise he cancels the meeting. (If only one knight shows up, then the meeting is canceled as well, as one person cannot sit around a table.) Merlin realized that this means that there can be knights who cannot be part of any seating arrangements that respect these rules, and these knights will never be able to sit at the Round Table (one such case is if a knight hates every other knight, but there are many other possible reasons). If a knight cannot sit at the Round Table, then he cannot be a member of the Knights of the Round Table and must be expelled from the order. These knights have to be transferred to a less-prestigious order, such as the Knights of the Square Table, the Knights of the Octagonal Table, or the Knights of the Banana-Shaped Table. To help Merlin, you have to write a program that will determine the number of knights that must be expelled.

    Input

    The input contains several blocks of test cases. Each case begins with a line containing two integers 1 <= n <= 1000 and 1 <= m <= 1000000. The number n is the number of knights. The next m lines describe which knight hates which knight. Each of these m lines contains two integers k1 and k2 , which means that knight number k1 and knight number k2 hate each other (the numbers k1 and k2 are between 1 and n).

    The input is terminated by a block with n = m = 0.

    Output

    For each test case you have to output a single integer on a separate line: the number of knights that have to be expelled.

    Example

    Input:
    5 5
    1 4
    1 5
    2 5
    3 4
    4 5
    0 0
    
    Output:
    2
    
    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2008-07-24
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set (classical)

    2879. The Cow Doctor

    Problem code: DOCTOR

    Texas is the state having the largest number of cows in the US: according to the 2005 report of the NationalAgricultural Statistics Service, the bovine population of Texas is 13.8 million. This is higher than thepopulation of the two runner-up states combined: there are only 6.65 million cows in Kansas and 6.35millions cows in Nebraska.

    There are several diseases that can threaten a herd of cows, the most feared being "Mad Cow Disease" or Bovine Spongiform Encephalopathy (BSE); therefore, it is very important to be able to diagnose certain illnesses. Fortunately, there are many tests available that can be used to detect these diseases.

    A test is performed as follows. First a blood sample is taken from the cow, then the sample is mixed with a test material. Each test material detects a certain number of diseases. If the test material is mixed with a blood sample having any of these diseases, then a reaction takes place that is easy to observe. However, if a test material can detect several diseases, then we have no way to decide which of these diseases is present in the blood sample as all of them produce the same reaction. There are materials that detect many diseases (such tests can be used to rule out several diseases at once) and there are tests thatdetect only a few diseases (they can be used to make an accurate diagnosis of the problem).

    The test materials can be mixed to create new tests. If we have a test material that detects diseases A and B; and there is another test material that detects diseases B and C, then they can be mixed toobtain a test that detects diseases A, B, and C. This means that if we have these two test materials, then there is no need for a test material that tests diseases A, B, and C-such a material can be obtained bymixing these two.

    Producing, distributing, and storing many different types of test materials is very expensive, and inmost cases, unnecessary. Your task is to eliminate as many unnecessary test materials as possible. Ithas to be done in such a way that if a test material is eliminated, then it should be possible to mix an equivalent test from the remaining materials. ("Equivalent" means that the mix tests exactly the samediseases as the eliminated material, not more, not less).

    Input

    The input contains several blocks of test cases. Each case begins with a line containing two integers: the number 1 <= n <= 300 of diseases, and the number 1 <= m <= 200 of test materials. The next m lines correspond to the m test materials. Each line begins with an integer, the number 1 <= k <= 300 of diseases that the material can detect. This is followed by k integers describing the k diseases. These integers are between 1 and n .

    The input is terminated by a block with n = m = 0 .

    Output

    For each test case, you have to output a line containing a single integer: the maximum number of test materials that can be eliminated.

    Example

    Input:
    10 5
    2 1 2
    2 2 3
    3 1 2 3
    4 1 2 3 4
    1 4
    3 7
    1 1
    1 2 
    1 3
    2 1 2
    2 1 3
    2 3 2
    3 1 2 3
    0 0
    
    Output:
    2
    4
    
    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2008-07-24
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set ()

    2880. Wild West

    Problem code: WILD

    Once upon a time in the west... The quiet life of the villages on the western frontier are often stirred up by the appearance of mysterious strangers. A stranger might be a bounty hunter looking for a notorious villain, or he might be a dangerous criminal escaping the hand of justice. The number of strangers has become so large that they formed the Mysterious Strangers' Union. If you want to be a mysterious stranger, then you have to apply to the Union, and you have to pass three exams that test the three most important skills: shooting, fist-fighting, and harmonica playing. For each skill, the Admission Committeegives a score between 1 (worst) and m (best). Interestingly enough, there are no two members in the Union having exactly the same skills: for every two member, there is always at least one skill for which they have diofferent scores. Furthermore, it turns out that for every possible combination of scores there is exactly one member having these scores. This means that there are exactly m3 strangers in the union.

    Recently, some members left the Union and they formed the Society of Evil Mysterious Strangers. The aim of this group is to commit as many evil crimes as possible, and they are quite successful at it. Therefore, the Steering Committee of the Union decided that a Hero is needed who will destroy this evil society. A Hero is a mysterious stranger who can defeat every member of the Society of Evil Mysterious Strangers. A Hero can defeat a member if the Hero has a higher score in at least one skill. For example, if the evil society has two members, Colonel Bill, with a score of 7 for shooting, 5 for knife throwing and 3 for harmonica playing, and Rabid Jack, with a score 10 for shooting, 6 for knife throwing and 8 for harmonica playing, then a Hero with score 8 for shooting, 7 for knife throwing and 3 for harmonica playing can defeat both ofthem. However, someone with a score of 8 for shooting 6 for knife throwing and 8 for harmonica playing cannot be the Hero. Moreover, the Hero cannot be a member of the evil society.

    Your task is to determine whether there is a member in the Union who can be the Hero. If so, thenyou have to count how many members are potential heroes.

    Input

    The input contains several blocks of test cases. Each block begins with a line containing two integers: the number 1 <= n <= 100000 of members in the Society of Evil Mysterious Strangers and the maximum value 2 <= m <= 100000 of the scores. The next n lines describe these members. Each line contains three integers between 1 and m: the scores for the three skills.

    The input is terminated by a block with n = m = 0.

    Output

    For each test case, you have to output a single line containing the number of members in the Union who satisfy the requirements for becoming a Hero. If there is no such member, then output 0. It can be assumed that the output is always at most 1018.

    Example

    Input:
    3 10
    2 8 5
    6 3 5
    1 3 9
    1 3
    2 2 2
    1 10000
    2 2 2
    0 0
    
    Output:
    848
    19
    999999999992
    

    Warning: enormous input/output data, be careful with certain languages

    Note: The input is too large, so we have 4 input files and the total time limit is 17s.


    Added by:[Trichromatic] XilinX
    Date:2008-07-24
    Time limit:17s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set (classical)

    2881. Find the Clones

    Problem code: CLONE

    Doubleville, a small town in Texas, was attacked by the aliens. They have abducted some of the residents and taken them to the a spaceship orbiting around earth. After some (quite unpleasant) human experiments, the aliens cloned the victims, and released multiple copies of them back in Doubleville. So now it might happen that there are 6 identical person named Hugh F. Bumblebee: the original person and its 5 copies. The Federal Bureau of Unauthorized Cloning (FBUC) charged you with the task of determining how many copies were made from each person. To help you in your task, FBUC have collected a DNA sample from each person. All copies of the same person have the same DNA sequence, and different people have different sequences (we know that there are no identical twins in the town, this is not an issue).

    Input

    The input contains several blocks of test cases. Each case begins with a line containing two integers: the number 1 <= n <= 20000 people, and the length 1 <= m <= 20 of the DNA sequences. The next n lines contain the DNA sequences: each line contains a sequence of m characters, where each character is either 'A', 'C', 'G' or 'T'.

    The input is terminated by a block with n = m = 0 .

    Output

    For each test case, you have to output n lines, each line containing a single integer. The first line contains the number of different people that were not copied. The second line contains the number of people that were copied only once (i.e., there are two identical copies for each such person.) The third line contains the number of people that are present in three identical copies, and so on: the i -th line contains the number of persons that are present in i identical copies. For example, if there are 11 samples, one of them is from John Smith, and all the others are from copies of Joe Foobar, then you have to print '1' in the first andthe tenth lines, and '0' in all the other lines.

    Example

    Input:
    9 6
    AAAAAA
    ACACAC
    GTTTTG
    ACACAC
    GTTTTG
    ACACAC
    ACACAC
    TCCCCC
    TCCCCC
    0 0
    
    Output:
    1
    2
    0
    1
    0
    0
    0
    0
    0
    
    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2008-07-24
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set (classical)

    2882. The Warehouse

    Problem code: WARE


    Secret Agent OmeGa-7 has found the secret weapon warehouse of the mad scientist Dr. Matroid. The warehouse is full of large boxes (possibly with deadly weapons inside the boxes). While inspecting the warehouse, OmeGa-7 accidentally triggered the alarm system. The warehouse has a very effective protection against intruders: if the alarm is triggered, then the floor is filled with deadly acid. Therefore, the only way OmeGa-7 can escape is to climb onto the boxes and somehow reach the exit on top of them. The exit is a hole in the ceiling,if OmeGa-7 can climb through this hole then he can escape using the helicopter parked on the roof. There is a ladder and a box below the hole, thus the goal is to reach this box.

    The floor of the warehouse can be divided into a grid containing n * n cells, the size of each cell is 1 meter * 1 meter. Each cell is either fully occupied by one box or unoccupied. Each box is rectangular: the size of the base is 1 meter * 1 meter, and the height is either 2, 3, or 4 meters. In figure (a), you can see an example warehouse, where the numbers show the height of the boxes, E shows the exit, and the circle shows that Secret Agent OmeGa-7 is currently on the top of that box.

    OmeGa-7 can do two things:

    If he is standing on top of a box, and in an adjacent cell there is another box, then he can move to the top of this other box. For example, in the situation depicted in figure (a), he can move either to north or east, but not to west or south. Note that only these four directions are allowed, diagonal moves are not possible. The height difference between the two boxes does not matter.

    The second thing OmeGa-7 can do is that he can topple the box he is standing on in one of the four directions. The effect of toppling is best shown by an example: in the situation shown in figure (b), he can topple the box west (figure (c)) or north (figure (d)). If a box of height h is toppled north (west, south, etc.) then it will occupy h consecutive cells to the north (west, south, etc.) of its original position. The original position will be unoccupied (but can be later occupied again by toppling another box). A box can only be toppled if the cells where it will fall are unoccupied. For example, in figure (a), the box where OmeGa-7 is standing cannot be toppled in any of the four directions.

    By toppling a box, OmeGa-7 jumps one step in the direction that the box is toppled (see figures (c) and(d)). If a box is toppled, then it cannot be toppled again later. Recall that there is a box below the exit (at the cell marked with E in the figure), thus it is not possible to topple a box over this cell. The alarm system will soon release mutant poisonous biting bats, so OmeGa-7 has to leave the warehouse as quickly as possible. You have to help him by writing a program that will determine the minimum number of steps required to reach the exit. Moving to an adjacent box, or toppling a box is counted as one step.

    Input

    The input contains several blocks of test cases. The first line of each block contains three integers: the size 1 <= n <= 8 of the warehouse, and two integers i , j that describe the starting position of the secret agent. These numbers are between 1 and n ; the row number is given by i , the column number is given by j . The next n lines describe the warehouse. Each line contains a string of n characters. Each character corresponds to a cell of the warehouse. If the character is '.', then the cell is unoccupied. The characters '2', '3' and '4' correspond to boxes of height 2, 3 and 4, respectively. Finally, the character 'E' shows the location of the exit.

    The input is terminated by a block with n = i = j = 0.

    Output

    For each test case, you have to output a single line containing an integer: the minimum number of steps required to reach the exit. If it is not possible to reach the exit, then output the text 'Impossible.'(without quotes).

    Example

    Input:
    5 5 3
    .2..E
    ...2.
    4....
    ....4
    ..2..
    0 0 0
    
    Output:
    18
    

    Added by:[Trichromatic] XilinX
    Date:2008-07-24
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set ()

    2883. Widget Factory

    Problem code: WIDGET

    The widget factory produces several different kinds of widgets. Each widget is carefully built by a skilled widgeteer. The time required to build a widget depends on its type: the simple widgets need only 3 days, but the most complex ones may need as many as 9 days.

    The factory is currently in a state of complete chaos: recently, the factory has been bought by a new owner, and the new director has fired almost everyone. The new staff know almost nothing about building widgets, and it seems that no one remembers how many days are required to build each diofferent type of widget. This is very embarrassing when a client orders widgets and the factory cannot tell the client how many days are needed to produce the required goods. Fortunately, there are records that say for each widgeteer the date when he started working at the factory, the date when he was fired and what types of widgets he built. The problem is that the record does not say the exact date of starting and leaving the job, only the day of the week. Nevertheless, even this information might be helpful in certain cases: for example, if a widgeteer started working on a Tuesday, built a Type 41 widget, and was fired on a Friday,then we know that it takes 4 days to build a Type 41 widget. Your task is to figure out from these records (if possible) the number of days that are required to build the different types of widgets.

    Input

    The input contains several blocks of test cases. Each case begins with a line containing two integers: the number 1 <= n <= 300 of the different types, and the number 1 <= m <= 300 of the records. This line is followed by a description of the m records. Each record is described by two lines. The first line contains the total number 1 <= k <= 10000 of widgets built by this widgeteer, followed by the day of week when he/she started working and the day of the week he/she was fired. The days of the week are given bythe strings 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT' and 'SUN'. The second line contains k integers separated by spaces. These numbers are between 1 and n , and they describe the diofferent types of widgets that the widgeteer built. For example, the following two lines mean that the widgeteer started working on a Wednesday, built a Type 13 widget, a Type 18 widget, a Type 1 widget, again a Type 13 widget,and was fired on a Sunday.

    4 WED SUN 
    13 18 1 13 
    

    Note that the widgeteers work 7 days a week, and they were working on every day between their first and last day at the factory (if you like weekends and holidays, then do not become a widgeteer!).

    The input is terminated by a test case with n = m = 0 .

    Output

    For each test case, you have to output a single line containing n integers separated by spaces: the number of days required to build the different types of widgets. There should be no space before the first number or after the last number, and there should be exactly one space between two numbers. If there is more than one possible solution for the problem, then write 'Multiple solutions.' (without the quotes). If you are sure that there is no solution consistent with the input, then write 'Inconsistent data.'(without the quotes).

    Example

    Input:
    2 3
    2 MON THU
    1 2
    3 MON FRI
    1 1 2
    3 MON SUN
    1 2 2
    10 2
    1 MON TUE 
    3
    1 MON WED
    3
    0 0
    
    Output:
    8 3
    Inconsistent data.
    
    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2008-07-24
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set (classical)

    2884. Martian Mining

    Problem code: MARTIAN

    The NASA Space Center, Houston, is less than 200 miles from San Antonio, Texas (the site of the ACM Finals this year). This is the place where the astronauts are trained for Mission Seven Dwarfs, the next giant leap in space exploration. The Mars Odyssey program revealed that the surface of Mars is very rich in yeyenum and bloggium. These minerals are important ingredients for certain revolutionary new medicines, but they are extremely rare on Earth. The aim of Mission Seven Dwarfs is to mine these minerals on Mars and bring them back to Earth.

    The Mars Odyssey orbiter identified a rectangular area on the surface of Mars that is rich in minerals. The area is divided into cells that form a matrix of n rows and m columns, where the rows go from east to west and the columns go from north to south. The orbiter determined the amount of yeyenum and bloggium in each cell. The astronauts will build a yeyenum refinement factory west of the rectangular area and a bloggium factory to the north. Your task is to design the conveyor belt system that will allow them to mine the largest amount of minerals.

    There are two types of conveyor belts: the first moves minerals from east to west, the second moves minerals from south to north. In each cell you can build either type of conveyor belt, but you cannot build both of them in the same cell. If two conveyor belts of the same type are next to each other, then they can be connected. For example, the bloggium mined at a cell can be transported to the bloggium refinement factory via a series of south-north conveyor belts.

    The minerals are very unstable, thus they have to be brought to the factories on a straight path without any turns. This means that if there is a south-north conveyor belt in a cell, but the cell north of it contains an east-west conveyor belt, then any mineral transported on the south-north conveyor beltwill be lost. The minerals mined in a particular cell have to be put on a conveyor belt immediately, in the same cell (thus they cannot start the transportation in an adjacent cell). Furthermore, any bloggium transported to the yeyenum refinement factory will be lost, and vice versa.

    Your program has to design a conveyor belt system that maximizes the total amount of minerals mined,i.e., the sum of the amount of yeyenum transported to the yeyenum refinery and the amount of bloggium transported to the bloggium refinery.

    Input

    The input contains several blocks of test cases. Each case begins with a line containing two integers: the number 1 <= n <= 500 of rows, and the number 1 <= m <= 500 of columns. The next n lines describe the amount of yeyenum that can be found in the cells. Each of these n lines contains m integers. The first line corresponds to the northernmost row; the first integer of each line corresponds to the westernmost cell of the row. The integers are between 0 and 1000. The next n lines describe in a similar fashion theamount of bloggium found in the cells.

    The input is terminated by a block with n = m = 0.

    Output

    For each test case, you have to output a single integer on a separate line: the maximum amount of mineralsthat can be mined.

    Example

    Input:
    4 4
    0 0 10 9
    1 3 10 0
    4 2 1 3 
    1 1 20 0
    10 0 0 0
    1 1 1 30
    0 0 5 5
    5 10 10 10
    0 0
    
    Output
    98
    
    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2008-07-24
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set (classical)

    2885. Word Rings

    Problem code: WORDRING


    A word ring is a sequence of words where the last two letters of each word are the same as the first two letters of the next word (and the last two letters of the last word are the same as the first two letters of the first word). For example, the following sequence is a word ring:

    intercommunicational
    alkylbenzenesulfonate
    tetraiodophenolphthalein
    

    Your task is to write a program that, given a list of words, finds a word ring. You have to make the word ring as impressive as possible: the average length of the words in the ring has to be as large as possible. In the above example, the average length is (20 + 21 + 24)/3 = 21.6666 , which makes it somewhat impressive. Note that each word can be used at most once in the ring, and the ring can consist of a single word.

    Input

    The input contains several blocks of test cases. Each case begins with a line containing a single integer 1 <= n <= 100000 , the number of possible words that can be used. The next n lines contain these words. The words contain only the characters 'a'-'z' and the length of each word is at most 1000.

    The input is terminated by a block with n = 0.

    Output

    For each test case in the input, you have to output a single number on a separate line: the maximum average length of a ring composed from (a subset of) the words given in the input. The average length should be presented as a real number with two digits of precision. If it is not possible to compose a ring from these words, then output 'No solution.' (without quotes). To avoid rounding problems, we accept solutions with a maximum of 0.01(positive or negative) error.

    Example

    Input:
    3
    intercommunicational
    alkylbenzenesulfonate
    tetraiodophenolphthalein
    0
    
    Output:
    21.66
    
    Warning: large input/output data, be careful with certain languages
    Added by:[Trichromatic] XilinX
    Date:2008-07-24
    Time limit:13s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM Central European Programming Contest, Budapest 2005









    SPOJ Problem Set (classical)

    2898. Party of Cloaked Killers

    Problem code: PARTY2

    N (1<= N <=100000) perfect killers (we number them 1, 2, 3, ..., N) meet at Blue Mary's house. Every killer has a kind of skill - cloak. No one can see them when they are cloaked - except only a small group of people, which will be discussed later.

    We can group these killers into M (M >=3) groups, called group No.1, group No.2, group No.3, etc. If killer A is in group No. x and killer B is in group No. (X%M+1), A can see B even if B is cloaked. This prevent killers from doing some bad things without the risk of being punished.

    To keep their identity secret, every killer keep cloaked during the party. After the party, Blue Mary asked everyone a question, "Which killers can you see in the party?" Although some killers forget some person they have ever seen during the party, Blue Mary collects extremely much information. Now she needs you help to determine the value of M, because no killer is willing to share this value with her.

    Input

    Ten test cases(given one after another, you have to process all!). For each test case:

    The first line contains two integers N and E(1<= E<= 180000). E lines follow, each line contains two space-seperated integers A and B - killer No. A can see killer No.B even if he is cloaked.

    Output

    For each test case, output one line:

    If the information given is contradictory, output one line "-1 -1". Otherwise output the largest and the smallest possible value of M, seperated by a single space.

    Example

    Input:
    6 5
    1 2
    2 3
    3 4
    4 1
    3 5
    3 3
    1 2
    2 1
    2 3
    [and 8 test cases more]
    
    Output:
    4 4
    -1 -1
    [and 8 test cases more]

    Warning: large input/output data, be careful with certain languages


    Added by:[Trichromatic] XilinX
    Date:2008-07-30
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:Chinese National Olympiad in Informatics 2008, Day 1; Translate by Blue Mary









    SPOJ Problem Set (classical)

    2899. Volunteers

    Problem code: VOL

    ACM ICPC World Finals 2009, sponsored by IBM and hosted by KTH, Royal Institute of Technology will be held in Stockholm, Sweden. This contest will last for N(1<= N <= 1000) days. We need at least Ai volunteers in the i-th day. Now there are M(1<= M <=10000) kind of volunteers. The i-th type of volunteers will work from Si-th day to Ti-th day, we will pay them $Ci. Now your task is to minimize the money KTH pay for all the volunteers.

    Input

    Ten test cases(given one after another, you have to process all!). For each test case:

    The first line contains two space-seperated integers N and M. The second line contains N nonnegative integers Ai. M lines follow, each contains three integers Si, Ti and Ci. You may assume you can hire almost unlimited number of every type of volunteers.

    Tip: During your calculation, int in C/C++/Java or longint in Pascal is enough.

    Output

    For each test case:

    Output one line with an integer - the minimum cost.

    Example

    Input:
    3 3
    2 3 4
    1 2 2
    2 3 5
    3 3 2
    [and 9 test cases more]
    
    Output:
    14
    [and 9 test cases more]
    

    Added by:[Trichromatic] XilinX
    Date:2008-07-30
    Time limit:13s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:Chinese National Olympiad in Informatics 2008, Day 1









    SPOJ Problem Set (classical)

    2901. One Geometry Problem

    Problem code: GEOPROB

    This is a problem of Euclidean Geometry. See the figure below.

    Your task is as follows: given the lengths of segments b, c, and d, calculate the length of segment a.

    Input

    The input begins with the number t of test cases in a single line (t<=300). In each of the next t lines there are three integers b, c and d (0 <= b, c and d <= 10200 ; b,d < c) separated by a space.

    Output

    For every test case print the length of the segment a, one number per line.

    Example

    Input:
    2
    3 8 5
    10 18 12
    
    Output:
    8
    14
    

    Added by:Frank Rafael Arteaga
    Date:2008-07-30
    Time limit:0.5s-1s
    Source limit:4000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
    Resource:My own Resource









    SPOJ Problem Set (classical)

    2902. Candy IV

    Problem code: CANDY4

    Lazy Child is a lazy child who likes candy very much. Despite being very young, he has two large candy boxes, each initially containing n candies. Everyday he picks one box and open it, if there still are candies, he would eat one. If not, he would be quite sad and open the other box. He will pick the first box with probability p and the second box with probability 1-p. He might cry if the other box contains few candies.

    He opens a box and finds it's not empty, then takes out 1 candy from it and eats it for several days, while he can't remember how many days are there exactly. One day, he opens a box, only to find no candy left. Before opening the other box, he wants to know the expected number of candies left in the other box. Can you help him?

    Input

    There are several test cases (about 100), please process till EOF.

    Each of the following lines contains an integer n (1<= n <= 20000) and a real number p (0 <= p <= 1, with 6 digits after the decimal).

    Output

    Please print one line per case containing the desired answer. Any answer with an absolute error less than or equal to 10-2 would be accepted. Please see the sample output for detailed format.

    Example

    Input:
    10 0.400000
    100 0.500000
    124 0.432650
    325 0.325100
    532 0.487520
    2276 0.720000
    
    Output:
    Case 1: 3.528175
    Case 2: 10.326044
    Case 3: 28.861945
    Case 4: 167.965476
    Case 5: 32.601816
    Case 6: 1390.500000
    

    Added by:[Trichromatic] XilinX
    Date:2008-08-01
    Time limit:2s
    Source limit:50000B
    Cluster: Cube (Intel Pentium G860 3GHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:ACM/ICPC Regional Contest, Chengdu 2012









    SPOJ Problem Set (classical)

    2903. Transportation

    Problem code: TRANSP1


    Blue Mary, the queen of Protoss, is planning a war against Zerg. Before the war she plans to make her base as safe as possible. Now there are N (1<= N <= 60) nexuses available in the region controlled by Protoss, numbered 1, 2, ..., N. (Those who don't know what nexus is, please visit Blizzard Entertainment.) All the mineral and vespene gas stored in nexus i can be transported directly to nexus Si.(i and Si won't be the same.) Blue Mary's base is nexus 1, So all the mineral and vespene gas can be transported to base 1 directly or indirectly.

    Blue Mary defines the safety of nexus i, R(i), as the following:

    Ci and k are numeral constants which will be given in the input file.

    Suppose for a fixed i, set T={P1, P2, P3, ..., Pw}, then x is a member of T if and only if Sx is i. Any two Pjs must be different.

    Now Blue Mary wants to modify at most M (0<= M <= N) Si s, so that the safety of her base R(1) is maximized. To be a terran captive, also a great programmer, you must help her to solve this problem. Price is your life. Be careful! Blue Mary tells you that S1 can't be modified. Don't ask your queen about the reason please.

    Input

    Ten test cases(given one after another, you have to process all!). For each test case:

    The first line contains N, M and a real number k (0.3<= k <1). The second line contains N space seperated integers Si. The third line contains N positive real numbers Ci.

    There is a single blank line between consecutive test cases.

    Output

    For each test case:

    A single line - the maximized safety of nexus 1, rounded to two decimal places.

    Example

    Input:
    4 1 0.5
    2 3 1 3
    10.0 10.0 10.0 10.0
    [and 9 test cases more]
    
    Output:
    30.00
    [and 9 test cases more]
    

    Hint

    Before modifying, the safety of the 4 bases are 22.8571, 21.4286,25.7143,10, respectively.

    After modifying S2 to 1, the safety of the 4 bases are 30, 25, 15, 10, respectively.


    Added by:[Trichromatic] XilinX
    Date:2008-08-01
    Time limit:13s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:Chinese National Olympiad in Informatics 2008, Day 2









    SPOJ Problem Set ()

    2905. Not a Triangle

    Problem code: NOTATRI

    You have N (3 ≤ N ≤ 2,000) wooden sticks, which are labeled from 1 to N. The i-th stick has a length of Li (1 ≤ Li ≤ 1,000,000). Your friend has challenged you to a simple game: you will pick three sticks at random, and if your friend can form a triangle with them (degenerate triangles included), he wins; otherwise, you win. You are not sure if your friend is trying to trick you, so you would like to determine your chances of winning by computing the number of ways you could choose three sticks (regardless of order) such that it is impossible to form a triangle with them.

    Input

    The input file consists of multiple test cases. Each test case starts with the single integer N, followed by a line with the integers L1, ..., LN. The input is terminated with N = 0, which should not be processed.

    Output

    For each test case, output a single line containing the number of triples.

    Example

    Input:
    3
    4 2 10
    3
    1 2 3
    4
    5 2 9 6
    0
    
    Output:
    1
    0
    2
    
    

    For the first test case, 4 + 2 < 10, so you will win with the one available triple. For the second case, 1 + 2 is equal to 3; since degenerate triangles are allowed, the answer is 0.


    Added by:Neal Wu
    Date:2008-08-03
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL









    SPOJ Problem Set (classical)

    2906. GCD2

    Problem code: GCD2

    Frank explained its friend Felman the algorithm of Euclides to calculate the GCD of two numbers. Then Felman implements it algorithm

    int gcd(int a, int b)
    {
    	if (b==0)
    		return a;
    	else
    		return gcd(b,a%b);
    }
    
    and it proposes to Frank that makes it but with a little integer and another integer that has up to 250 digits.

    Your task is to help Frank programming an efficient code for the challenge of Felman.

    Input

    The first line of the input file contains a number representing the number of lines to follow. Each line consists of two number A and B (0 <= A <= 40000 and A <= B < 10^250).

    Output

    Print for each pair (A,B) in the input one integer representing the GCD of A and B.

    Example

    Input:
    2
    2 6
    10 11
    
    
    Output:
    2
    1
    
    

    Added by:Frank Rafael Arteaga
    Date:2008-08-04
    Time limit:0.5s
    Source limit:1000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict LISP sbcl LISP clisp ERL JAVA JS NODEJS PERL PERL 6 PHP PYTH 2.7 RUBY
    Resource:My own Resource









    SPOJ Problem Set (classical)

    2916. Can you answer these queries V

    Problem code: GSS5


    You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| <= 10000 , 1 <= N <= 10000 ). A query is defined as follows: Query(x1,y1,x2,y2) = Max { A[i]+A[i+1]+...+A[j] ; x1 <= i <= y1 , x2 j <= y2 and x1 <= x2 , y1 <= y2 }. Given M queries (1 <= M <= 10000), your program must output the results of these queries.

    Input

    The first line of the input consist of the number of tests cases <= 5. Each case consist of the integer N and the sequence A. Then the integer M. M lines follow, contains 4 numbers x1, y1, x2 y2.

    Output

    Your program should output the results of the M queries for each test case, one query per line.

    Example

    Input:
    2
    6 3 -2 1 -4 5 2
    2
    1 1 2 3
    1 3 2 5
    1 1
    1
    1 1 1 1
    
    Output:
    2
    3
    1
    
    
    

    Added by:Frank Rafael Arteaga
    Date:2008-08-06
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:K.-Y. Chen and K.-M. Chao, On the Range Maximum-Sum Segment Query Problem, 2007.









    SPOJ Problem Set (classical)

    2939. Query on a tree V

    Problem code: QTREE5

    You are given a tree (an acyclic undirected connected graph) with N nodes. The tree nodes are numbered from 1 to N. We define dist(a, b) as the number of edges on the path from node a to node b.

    Each node has a color, white or black. All the nodes are black initially.

    We will ask you to perfrom some instructions of the following form:

    • 0 i : change the color of i-th node(from black to white, or from white to black).
    • 1 v : ask for the minimum dist(u, v), node u must be white(u can be equal to v). Obviously, as long as node v is white, the result will alway be 0.

    Input

    • In the first line there is an integer N (N <= 100000)
    • In the next N-1 lines, the i-th line describes the i-th edge: a line with two integers a b denotes an edge between a and b.
    • In the next line, there is an integer Q denotes the number of instructions (Q <= 100000)
    • In the next Q lines, each line contains an instruction "0 i" or "1 v"

    Output

    For each "1 v" operation, print one integer representing its result. If there is no white node in the tree, you should write "-1".

    Example

    Input:
    10
    1 2
    1 3
    2 4
    1 5
    1 6
    4 7
    7 8
    5 9
    1 10
    10
    0 6
    0 6
    0 6
    1 3
    0 1
    0 1
    1 3
    1 10
    1 4
    1 6
    
    Output:
    2
    2
    2
    3
    0
    
    

    Added by:Qu Jun
    Date:2008-08-13
    Time limit:6s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:XunYunbo, modified from ZJOI07









    SPOJ Problem Set (classical)

    2940. Untitled Problem II

    Problem code: UNTITLE1


    You are given a sequence of N integers A1, A2 .. AN. (-10000 <= Ai <= 10000, N <= 50000)

    Let Si denote the sum of A1..Ai. You need to apply M (M <= 50000) operations:

    • 0 x y k: increase all integers from Ax to Ay by k(1 <= x <= y <= N, -10000 <= k <= 10000).
    • 1 x y: ask for max{ Si | x <= i <= y }.(1 <= x <= y <= N)

    Input

    • In the first line there is an integer N.
    • The following line contains N integers that represent the sequence.
    • The third line contains an integer M denotes the number of operations.
    • In the next M lines, each line contains an operation "0 x y k" or "1 x y".

    Output

    For each "1 x y" operation, print one integer representing its result.

    Example

    Input:
    5
    238 -9622 5181 202 -6943
    5
    1 3 4
    0 5 5 4846
    1 3 5
    0 3 5 -7471
    1 3 3
    
    Output:
    -4001
    -4001
    -11674
    
    

    Use signed 64-bit integer :)


    Added by:Qu Jun
    Date:2008-08-14
    Time limit:4s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Not an own problem









    SPOJ Problem Set (classical)

    2944. Emmons

    Problem code: SHOOTING


    After the end of all the shooting competitions in XXIX Olympic Games in Beijing, Matthew Emmons will be known to more and more people because of his last - which is also his worst - shooting in the 50m Rifle 3*40 Men competitions. Four years before in Athens, he shot a wrong target and lost the gold metal which is almost at hands in the 50m Rifle 3*40 Men competition.

    The following is Blue Mary's imagination :P

    Emmons decides to practise shooting more assiduously. Because he is an excellent shooter, only 1 year later, he can even shoot precisely without collimation! To him, getting the gold metal of 50m Rifle 3*40 Men in XXX Olympic Games doesn't have any difficulty now.

    His wife - Katerina Emmons, also a well-known excellent shooter - make a game to keep his interests with shot. The player has n (1<= n <=2000) bullets, each one has a value (a integer whose absolute value is less than 10000). There are m (1<= m <= n) targets, each with a point counter next to it. In the beginning of the game, all the counter are set to integer 1.

    During the game, the player must choose a bullet and shoot any target. He must use all the bullet, each with at least(of course, at most) 1 time. And each target must be shot at least one time.

    If the player shoot a target with a bullet valued X, the counter of the target will multiplied by X.

    The final score of the game is sum of all the m counters.

    Now Matthew needs your help to make his final score as high as possible. After that, he will show you his excellent shooting skills to get this score.

    P.S. Even the things above is my imagination, I hope Matthew Emmons has good luck and wins the gold metal of 50m Rifle 3*40 Men in XXX Olympics in London.

    Input

    Multiple test cases, the number of them (<=50) is given in the very first line.

    For each test case:

    The first line contains two integers n and m. The second line contains n integers, the value for each bullet.

    Output

    For each test case:

    The first and the only line contains a single integer - the highest possible final score.

    Example

    Input:
    3
    10 2
    0 -1 -2 0 1 2 3 2 10 1
    10 3
    0 -1 -2 0 1 2 3 2 10 1
    5 3
    10 0 0 -1 -1
    
    Output:
    240
    241
    11
    
    Hint:
    For the first example, a possible solution is (0,0)(-1,-2,1,2,3,2,10,1).
    For the second example, a possible solution is (0,0)(1,1)(-1,-2,2,3,2,10).
    

    Added by:[Trichromatic] XilinX
    Date:2008-08-21
    Time limit:60s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS
    Resource:Chinese Team Selection Contest for IOI 2006, with description modified









    SPOJ Problem Set (classical)

    2946. Eclipse

    Problem code: ECLIPSE

    Every so often we hear on the news that there is going to be either a solar or lunar eclipse. Eclipses have a long history dating back well into the BC’s. Astronomers study total solar eclipses very closely as they provide the rare opportunity to observe the corona.

    An eclipse occurs when two celestial bodies and a star are (nearly) linearly aligned and the shadow cast by the one body intersects the other body, creating darkness on the latter body.

    We are interested in determining when a solar eclipse will next occur. In Figure 1 you can see two labelled regions. The umbra is the area of total darkness — a body in this region will experience a total solar eclipse. The penumbra is the area of partial darkness — a body in this region will experience a partial solar eclipse.

    You will be given the size and location of a star and two celestial bodies. Your task is to determine if the first celestial body creates a solar eclipse on the second celestial body. If it does then you are to determine whether it is a total or partial eclipse and whether the entire body is in eclipse. If part of the body is experiencing total eclipse while the entire body is experiencing at least a partial eclipse, we are only interested in the part that is in total eclipse.

    Consider a scaled model of our solar system with the sun at the origin (0, 0, 0) with radius 700, the moon at position (49900, 1000, 149700) with radius 2 and Earth at position (50000, 1000, 150000) with radius 7. In Figure 1, the sun would be the star on the left and the moon would be the smaller body on the right. Part of Earth would then fall in the black umbra region and hence partly experience a total solar eclipse.

    For any body:

  • 1 ≤ r ≤ 106
  • 0 ≤ x, y, z ≤ 109

    It is guaranteed that any two bodies will be at least 1 unit apart, and that moving any one of the bodies by 1 unit (in any direction) will not change the answer.

    Input

    A test case is described by three lines, each describing the size and location of a single body. The first line contains four space-separated integers xs , ys , zs and rs , describing the center (xs , ys , zs ) and radius rs of the star. The following two lines define the two celestial bodies in the same manner.

    Test cases follow directly after one another with a −1 representing the end of the test cases.

    Output

    Each test case has a single line of output describing the type of eclipse for that case. If the second celestial body listed in the test case is experiencing an eclipse, then one of the following lines must be output:

  • Entire total solar eclipse
  • Part total solar eclipse
  • Entire partial solar eclipse
  • Part partial solar eclipse

    If there is no solar eclipse, the line “No solar eclipse” must be output.

    Example

    Input:
    0 0 0 700
    49900 1000 149700 2
    50000 1000 150000 7
    0 0 0 10
    50 0 100 40
    60 0 200 1
    -1
    
    Output:
    Part total solar eclipse
    Entire total solar eclipse

    Added by:Marco Gallotta
    Date:2008-08-27
    Time limit:30s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:ACM Southern African Regionals 2007









    SPOJ Problem Set (classical)

    2962. Painting Blocks (Act I)

    Problem code: PAINTBLK

    n blocks are put in a line. You have k(1<=k<=15) kinds of dope, the i-th dope is enough to paint ci (1<=ci<=5) blocks. You may assume the sum of all the ci equals to n. Your task is to calculate the number of ways to paint the blocks with these kinds of dope, such that no two adjacent blocks are painted with the same kind of dope.

    Input

    Ten test cases(given one after another, you have to process all!). For each test case, the first line contains an integer k, the second line contains k integers, c1, c2, ...ck.

    Output

    Ten lines, each contains an integer, the number of ways modulo 1000000007.

    Example

    Input:
    3
    1 2 3
    5
    2 2 2 2 2
    10
    1 1 2 2 3 3 4 4 5 5
    [and 7 test cases more]
    
    Output:
    10
    39480
    85937576
    [and 7 test cases more]
    

    Added by:[Trichromatic] XilinX
    Date:2008-09-01
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource::P









    SPOJ Problem Set (classical)

    2963. Painting Blocks (Act II)

    Problem code: PAINTBLC


    n blocks are put in a line. You have k(1<=k<=15) kinds of dope, the i-th dope is enough to paint ci (1<=ci<=6) blocks. You may assume the sum of all the ci equals to n. Your task is to calculate the number of ways to paint the blocks with these kinds of dope, such that no two adjacent blocks are painted with the same kind of dope.

    Input

    Input consists of multiple test cases, the number of them (<=2000) is given in the very first line. For each test case, the first line contains an integer k, the second line contains k integers, c1, c2, ...ck.

    Output

    For each test case, output one line with an integer, the number of ways modulo 1000000007.

    Example

    Input:
    3
    3
    1 2 3
    5
    2 2 2 2 2
    10
    1 1 2 2 3 3 4 4 5 5
    
    Output:
    10
    39480
    85937576
    

    Added by:[Trichromatic] XilinX
    Date:2008-09-01
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:g201513









    SPOJ Problem Set (classical)

    3002. Electrophoretic

    Problem code: ELECTRO

    Scientist Frank, majoring in electrochemistry, has developed line-shaped strange electrodes called F-electrodes. During being activated, each F-electrode causes a special potential on and between the two lines touching the F-electrode's endpoints at a right angle. Then electrically-charged particles located inside the potential area get to move in the direction parallel to the potential boundary (i.e. perpendicular to the F-electrode), either toward or against F-electrode. The moving direction can be easily controlled between the two possibles; it is also possible to get particles to pass through F-electrodes. In addition, unlike ordinary electrodes, F-electrodes can affect particles even infinitely far away, as long as those particles are located inside the potential area. On the other hand, two different F-electrodes cannot be activated at a time, since their potentials conflict strongly.

    We can move particles on our will by controlling F-electrodes. However, in some cases, we cannot lead them to the desired positions due to the potential areas being limited. To evaluate usefulness of F-electrodes from some aspect, Frank has asked you the following task: to write a program that finds the shortest distances from the particles' initial positions to their destinations with the given sets of F-electrodes.

    Input

    The input consists of multiple test cases. The first line of each case contains N(1 ≤ N ≤ 100) which represents the number of F-electrodes. The second line contains four integers xs, ys, xt and yt, where (xs, ys) and (xt , yt) indicate the particle’s initial position and destination. Then the description of N F-electrodes follow. Each line contains four integers Fxs, Fys, Fxt and Fyt, where (Fxs, Fys) and (Fxt , Fyt) indicate the two endpoints of an F-electrode. All coordinate values range from 0 to 100 inclusive.

    The input is terminated by a case with N = 0.

    Output

    Your program must output the case number followed by the shortest distance between the initial position to the destination. Output "Impossible" (without quotes) as the distance if it is impossible to lead the elementary particle to the destination. Your answers must be printed with five digits after the decimal point.

    Example

    Input:
    2
    2 1 2 2
    0 0 1 0
    0 1 0 2
    0
    
    Output:
    Case 1: 3.00000
    

    Added by:Bin Jin
    Date:2008-09-08
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:JAG wintercamp 08, day2









    SPOJ Problem Set (classical)

    3003. Median Filter

    Problem code: FILTER

    The median filter is a nonlinear digital filter used to reduce noise in images, sounds, and other kinds of signals. It examines each sample of the input through a window and then emits the median of the samples in the window. Roughly speaking, a window is an interval that contains a target sample and its preceding and succeeding samples; the median of a series of values is given by the middle value of the series arranged in ascending (or descending) order.

    Let us focus on a typical median filter for black-and-white raster images. The typical filter uses a 3 × 3 window, which contains a target pixel and the eight adjacent pixels. The filter examines each pixel in turn through this 3 × 3 window, and outputs the median of the nine pixel values, i.e. the fifth lowest (or highest) pixel value, to the corresponding pixel. We should note that the output is just given by the pixel value in majority for black-andwhite images, since there are only two possible pixel values (i.e. black and white). The figure below illustrates how the filter works.

    The edges of images need to be specially processed due to lack of the adjacent pixels. In this problem, we extends the original images by repeating pixels on the edges as shown in the figure below. In other words, the lacked pixels take the same values as the nearest available pixels in the original images.

    You are requested to write a program that reads images to which the filter is applied, then finds the original images containing the greatest and smallest number of black pixels among all possible ones, and reports the difference in the numbers of black pixels.

    Input

    The input contains a series of test cases.

    The first line of each test case contains two integers W and H (1 ≤ W, H ≤ 8), which indicates the width and height of the image respectively. Then H lines follow to describe the filtered image. The i-th line represents the i-th scan line and contains exactly W characters, each of which is either '#' (representing black) or '.' (representing white).

    The input is terminated by a line with two zeros.

    Output

    For each test case, print a line that contains the case number followed by the difference of black pixels. If there are no original images possible for the given filtered image, print "Impossible" instead.

    Obey the format as shown in the sample output.

    Example

    Input:
    5 5
    #####
    #####
    #####
    #####
    #####
    4 4
    ####
    ####
    ####
    ####
    4 4
    #...
    ....
    ....
    ...#
    4 4
    .#.#
    #.#.
    .#.#
    #.#.
    0 0
    
    Output:
    Case 1: 10
    Case 2: 6
    Case 3: 2
    Case 4: Impossible
    

    Added by:Bin Jin
    Date:2008-09-08
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:JAG wintercamp 08, day2









    SPOJ Problem Set (classical)

    3004. Life Game

    Problem code: LIFEGAME

    You are working at a production plant of biological weapons. You are a maintainer of a terrible virus weapon with very high reproductive power. The virus has a tendency to build up regular hexagonal colonies. So as a whole, the virus weapon forms a hexagonal grid, each hexagon being a colony of the virus. The grid itself is in the regular hexagonal form with N colonies on each edge.

    The virus self-propagates at a constant speed. Self-propagation is performed simultaneously at all colonies. When it is done, for each colony, the same number of viruses are born at every neighboring colony. Note that, after the self-propagation, if the number of viruses in one colony is more than or equal to the limit density M, then the viruses in the colony start self-attacking, and the number reduces modulo M.

    Your task is to calculate the total number of viruses after L periods, given the size N of the hexagonal grid and the initial number of viruses in each of the colonies.

    Input

    The input consists of multiple test cases.

    Each case begins with a line containing three integers N (1 ≤ N ≤ 6), M (2 ≤ M ≤ 109), and L (1 ≤ L ≤ 109). The following 2N - 1 lines are the description of the initial state. Each non-negative integer (smaller than M) indicates the initial number of viruses in the colony. The first line contains the number of viruses in the N colonies on the topmost row from left to right, and the second line contains those of N + 1 colonies in the next row, and so on.

    The end of the input is indicated by a line "0 0 0".

    Output

    For each test case, output the test case number followed by the total number of viruses in all colonies after L periods.

    Example

    Input:
    3 3 1
    1 0 0
    0 0 0 0
    0 0 0 0 0
    0 0 0 0
    0 0 1
    3 3 2
    1 0 0
    0 0 0 0
    0 0 0 0 0
    0 0 0 0
    0 0 1
    0 0 0
    
    Output:
    Case 1: 8
    Case 2: 18
    

    Added by:Bin Jin
    Date:2008-09-08
    Time limit:20s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:JAG wintercamp 08, day2









    SPOJ Problem Set (classical)

    3005. Subdividing a Land

    Problem code: LAND

    Indigo Real-estate Company is now planning to develop a new housing complex. The entire complex is a square, all of whose edges are equally a meters. The complex contains n subdivided blocks, each of which is a b-meter square. Here both a and b are positive integers.

    However the project is facing a big problem. In this country, a percentage limit applies to the subdivision of a land, under the pretext of environmental protection. When developing a complex, the total area of the subdivided blocks must not exceed 50% of the area of the complex; in other words, more than or equal to 50% of the newly developed housing complex must be kept for green space. As a business, a green space exceeding 50% of the total area is a dead space. The primary concern of the project is to minimize it.

    Of course purchasing and developing a land costs in proportion to its area, so the company also wants to minimize the land area to develop as the secondary concern. You, a member of the project, were assigned this task, but can no longer stand struggling against the problem with your pencil and paper. So you decided to write a program to find the pair of minimum a and b among those which produce the minimum dead space for given n.

    Input

    The input consists of multiple test cases. Each test case comes in a line, which contains an integer n. You may assume 1 ≤ n ≤ 10000.

    The end of input is indicated by a line containing a single zero. This line is not a part of the input and should not be processed.

    Output

    For each test case, output the case number starting from 1 and the pair of minimum a and b as in the sample output.

    You may assume both a and b fit into 64-bit signed integers.

    Example

    Input:
    1
    2
    0
    
    Output:
    Case 1: 3 2
    Case 2: 2 1
    
    

    Added by:Bin Jin
    Date:2008-09-08
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:JAG wintercamp 08, day2









    SPOJ Problem Set (classical)

    3006. Connect Line Segments

    Problem code: LINE


    Your dear son Arnie is addicted to a puzzle named Connect Line Segments.

    In this puzzle, you are given several line segments placed on a two-dimensional area. You are allowed to add some new line segments each connecting the end points of two existing line segments. The objective is to form a single polyline, by connecting all given line segments, as short as possible. The resulting polyline is allowed to intersect itself.

    Arnie has solved many instances by his own way, but he is wondering if his solutions are the best one. He knows you are a good programmer, so he asked you to write a computer program with which he can verify his solutions.

    Please respond to your dear Arnie’s request.

    Input

    The input consists of multiple test cases.

    Each test case begins with a line containing a single integer n (2 ≤ n ≤ 14), which is the number of the initial line segments. The following n lines are the description of the line segments. The i-th line consists of four real numbers: xi,1, yi,1, xi,2, and yi,2 (-100 ≤ xi,1, yi,1, xi,2, yi,2 ≤ 100). (xi,1, yi,1) and (xi,2, yi,2) are the coordinates of the end points of the i-th line segment.

    The end of the input is indicated by a line with single "0".

    Output

    For each test case, output the case number followed by the minimum length in a line.

    The output value should be printed with five digits after the decimal point.

    Example

    Input:
    4
    0 1 0 9
    10 1 10 9
    1 0 9 0
    1 10 9 10
    2
    1.2 3.4 5.6 7.8
    5.6 3.4 1.2 7.8
    0
    
    Output:
    Case 1: 36.24264
    Case 2: 16.84508
    

    Added by:Bin Jin
    Date:2008-09-08
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:JAG wintercamp 08, day2









    SPOJ Problem Set (classical)

    3007. Oil Company

    Problem code: OILCOMP


    Irving & Cohen Petroleum Corporation has decided to develop a new oil field in an area. A preliminary survey has been done and they created a detailed grid map of the area which indicates the reserve of oil.

    They are now planning to construct mining plants on several grid blocks according this map, but they decided not to place any two plants on adjacent positions to avoid spreading of fire in case of blaze. Two blocks are considered to be adjacent when they have a common edge. You are one of the programmers working for the company and your task is to write a program which calculates the maximum amount of oil they can mine, given the map of the reserve.

    Input

    The first line of the input specifies N, the number of test cases. Then N test cases follow, each of which looks like the following:

    W H
    r1,1 r2,1 ... rW,1
     ... 
    r1,H r2,H ... rW,H

    The first line of a test case contains two integers W and H (1 ≤ W, H ≤ 20). They specifies the dimension of the area. The next H lines, each of which contains W integers, represent the map of the area. Each integer rx,y (0 ≤ rx,y < 10000) indicates the oil reserve at the grid block (x, y).

    Output

    For each test case, output the case number (starting from 1) and the maximum possible amount of mining in a line. Refer to the sample output section about the format.

    Example

    Input:
    2
    2 2
    2 3
    3 5
    3 2
    4 1 1
    2 1 4
    
    Output:
    Case 1: 7
    Case 2: 8
    

    Added by:Bin Jin
    Date:2008-09-08
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:JAG wintercamp 08, day2









    SPOJ Problem Set (classical)

    3008. Finding the Top RPS Player

    Problem code: RPS

    A company "ACM Foods" is preparing for opening its chain shop in a certain area, but another company "ICPC Pizza" is also planning to set up its branch shop in the same area. In general, two competitive shops gain less incomes if they are located so close to each other. Thus, if both "ACM Foods" and "ICPC Pizza" went on opening, they would be damaged financially. So, they had a discussion on this matter and made the following agreement: only one of them can branch its shop in the area. It is determined by Rock-Paper-Scissors (RPS) which to branch the shop.

    ACM Foods is facing financial difficulties and strongly desires to open their new shop in that area. The executives have decided to make every effort for finding out a very strong RPS player. They believes that players who win consecutive victories must be strong players. In order to find such a player for sure, they have decided their simple strategy.

    In this strategy, many players play games of RPS repeatedly, but the games are only played between players with the same number of consecutive wins. At the beginning, all the players have no wins, so any pair of players can play a game. The games can be played by an arbitrary number of pairs simultaneously. Let us call a set of simultaneous games as a turn. After the first turn, some players will have one win, and the other players will remain with no wins. In the second turn, some games will be played among players with one win, and some other games among players with no wins. For the former games, the winners will have two consecutive wins, and the losers will lose their first wins and have no consecutive wins. For the latter games, the winners will have one win, and the losers will remain with no wins. Therefore, after the second turn, the players will be divided into three groups: players with two consecutive wins, players with one win, and players with no wins. Again, in the third turn, games will be played among players with two wins, among with one win, and among with no wins. The following turns will be conducted so forth. After a sufficient number of turns, there should be a player with the desired number of consecutive wins.

    The strategy looks crazy? Oh well, maybe they are confused because of their financial difficulties. Of course, this strategy requires an enormous amount of plays. The executives asked you, as an employee of ACM Foods, to estimate how long the strategy takes. Your task is to write a program to count the minimum number of turns required to find a player with M consecutive wins among N players.

    Input

    The input consists of multiple test cases. Each test case consists of two integers N (2 ≤ N ≤ 20) and M (1 ≤ M < N) in one line.

    The input is terminated by the line containing two zeroes.

    Output

    For each test case, your program must output the case number followed by one integer which indicates the minimum number of turns required to find a person with M consecutive wins.

    Example

    Input:
    2 1
    10 5
    15 10
    0 0
    
    Output:
    Case 1: 1
    Case 2: 11
    Case 3: 210
    

    Added by:Bin Jin
    Date:2008-09-08
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:JAG wintercamp 08, day2









    SPOJ Problem Set (classical)

    3009. Revenge of Voronoi

    Problem code: VORONOI

    A discrete Voronoi diagram is a derivation of a Voronoi diagram. It is represented as a set of pixels. Each of the generatrices lies on the center of some pixel. Each pixel belongs to the generatrix nearest from the center of the pixel in the sense of Manhattan distance. The Manhattan distance d between two points (x1, y1) and (x2, y2) is given by the following formula:

    d = |x1 - x2| + |y1 - y2|

    Your task is to find a set of generatrices which generates a given discrete Voronoi diagram. In the given diagram, each generatrix is given a unique lowercase letter as its identifier, and each pixel is represented by the identifier of the generatrix the pixel belongs to. If a pixel has multiple generatrices at the same distance from its center, it belongs to the generatrix with the most preceding identifier among them (i.e. the smallest character code).

    Input

    The input consists of multiple test cases.

    Each test case begins with a line containing two integers W (1 ≤ W ≤ 32) and H (1 ≤ H ≤ 32), which denote the width and height of the discrete Voronoi diagram.

    The following H lines, each of which consists of W letters, give one discrete Voronoi diagram. Each letter represents one pixel.

    The end of input is indicated by a line with two zeros. This is not a part of any test cases.

    Output

    For each test case, print the case number and the coordinates of generatrices as shown in the sample output. Each generatrix line should consist of its identifier, x-coordinate, and y-coordinate. Generatrices should be printed in alphabetical order of the identifiers. Each coordinate is zero-based where (0, 0) indicates the center of the top-left corner pixel of the diagram.

    You may assume that every test case has at least one solution. If there are multiple solutions, any one is acceptable.

    Print a blank line after every test case including the last one.

    Example

    Input:
    4 3
    ooxx
    ooxx
    ooxx
    4 1
    null
    4 4
    aabb
    aabb
    ccdd
    ccdd
    0 0
    
    Output:
    Case 1:
    o 0 0
    x 2 0
    
    Case 2:
    l 2 0
    n 0 0
    u 1 0
    
    Case 3:
    a 0 0
    b 2 0
    c 0 2
    d 2 2
    
    

    Added by:Bin Jin
    Date:2008-09-08
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:JAG wintercamp 08, day2









    SPOJ Problem Set (classical)

    3010. Castle Wall

    Problem code: WALL

    A new lord assumed the position by the death of the previous lord in a Far Eastern province.

    The new greedy lord hates concave polygons, because he believes they need much wasted area to be drawn on paper. He always wants to modify them to convex ones.

    His castle is currently surrounded by a wall forming a concave polygon, when seen from the above. Of course he hates it. He believes more area could be obtained with a wall of a convex polygon. Thus he has ordered his vassals to have new walls built so they form a convex polygon.

    Unfortunately, there is a limit in the budget. So it might be infeasible to have the new walls built completely. The vassals has found out that only up to r meters of walls in total can be built within the budget. In addition, the new walls must be built in such a way they connect the polygonal vertices of the present castle wall. It is impossible to build both of intersecting walls.

    After long persuasion of the vassals, the new lord has reluctantly accepted that the new walls might not be built completely. However, the vassals still want to maximize the area enclosed with the present and new castle walls, so they can satisfy the lord as much as possible.

    Your job is to write a program to calculate, for a given integer r, the maximum possible area of the castle with the new walls.

    Input

    The input file contains several test cases.

    Each case begins with a line containing two positive integers n and r. n is the number of vertices of the concave polygon that describes the present castle wall, satisfying 5 ≤ n ≤ 64. r is the maximum total length of new castle walls feasible within the budget, satisfying 0 ≤ r ≤ 400.

    The subsequent n lines are the x- and y-coordinates of the n vertices. The line segments (xi, yi)–(xi+1, yi+1) (1 ≤ in - 1) and (xn, yn)–(x1, y1) form the present castle wall of the concave polygon. Those coordinates are given in meters and in the counterclockwise order of the vertices.

    All coordinate values are integers between 0 and 100, inclusive. You can assume that the concave polygon is simple, that is, the present castle wall never crosses or touches itself.

    The last test case is followed by a line containing two zeros.

    Output

    For each test case in the input, print the case number (beginning with 1) and the maximum possible area enclosed with the present and new castle walls. The area should be printed with exactly one fractional digit.

    Example

    Input:
    5 4
    0 0
    4 0
    4 4
    2 2
    0 4
    8 80
    45 41
    70 31
    86 61
    72 64
    80 79
    40 80
    8 94
    28 22
    0 0
    
    Output:
    Case 1: 16.0
    Case 2: 3375.0
    

    Added by:Bin Jin
    Date:2008-09-08
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:JAG wintercamp 08, day2









    SPOJ Problem Set (classical)

    3033. Help the soldier

    Problem code: SOLDIER

    Igor, a famous russian soldier, must go to war in Afghanistan (we are in late 80’s). His superiors allowed him to buy himself his equipment. So, he must buy 6 items: helmet, bulletproof vest, trousers, boots, tunic and a firearm. This items are represented with numbers from 1 to 6. There are N( 6 < N < 101 ) items of this 6 types. Each item is characterized by its price p[i] (in rublas ) and is quality q[i]. Igor has T (0 < T < 1001 ) rublas and he wants to maximize the total quality of his equipment. The total quality is the quality of the item with the lowest quality. Help him.

    Input

    On the first line there are two integers N and T. On the lines 2 ... N+1 there are 3 integers, type[i] (from 1 to 6) p[i] and q[i]. ( 0 < p[ i ], q[ i ] < T )

    Output

    Output the total quality.

    Example

    Input:
    7 53
    5 8 2
    2 4 8
    6 8 13
    1 13 12
    4 5 1
    3 2 7
    3 13 5
    
    Output:
    1
    
    Note:
    If there is no answer, output 0.
    There can be less than 6 types of items.
    

    Added by:Pripoae Toni
    Date:2008-09-14
    Time limit:0.5s
    Source limit:2048B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Original









    SPOJ Problem Set (classical)

    3070. How many subsequences

    Problem code: SEQ5

    Tom has again maths , and the teacher writes countless tables with exercises .... so boring. Then he remembers an old problem of informatics that he thought in a dream . He remembered , he has a number of positive integers and the job was to know how many subsequences that have between L and U distinct elements exist in that range. So the boring hour will pass quicker . But he needs your help , he is to exhausted after two hours of math with the agitated teacher .

    Input

    The first line of input file contains positive N, L, U. following N lines will contain a positive integer, each representing an element of the series.

    Output

    The first line of the output will display the number of sequences containing between L and U distinct elements.

    Example

    Input:
    4 1 2
    231
    19
    7
    19
    
    
    Output:
    8
    
    Notes:
    
    1<= L <= U <= N <= 2^20
    The value of an item number is a positive integers [1,2^32-1];
    A subsequence is a lot of items that appear on consecutive positions in the initial row.
    Be carefull with certain languages.Large imput data.
    Tom thanks you for solving this problem and he awards you with points.
    
    
    
    
    Added by:Pripoae Toni
    Date:2008-09-29
    Time limit:0.200s-2.5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:Mircea Pasoi









    SPOJ Problem Set (classical)

    3105. Power Modulo Inverted

    Problem code: MOD

    Given 3 positive integers x, y and z, you can find k = xy%z easily, by fast power-modulo algorithm. Now your task is the inverse of this algorithm. Given 3 positive integers x, z and k, find the smallest non-negative integer y, such that k%z = xy%z.

    Input

    About 600 test cases.

    Each test case contains one line with 3 integers x, z and k.(1<= x, z, k <=109)

    Input terminates by three zeroes.

    Output

    For each test case, output one line with the answer, or "No Solution"(without quotes) if such an integer doesn't exist.

    Example

    Input:
    5 58 33
    2 4 3
    0 0 0
    
    Output:
    9
    No Solution
    

    Added by:[Trichromatic] XilinX
    Date:2008-10-04
    Time limit:17s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: C99 strict ERL JS NODEJS PERL 6
    Resource:Folklore, description, standard program and test data by Blue Mary









    SPOJ Problem Set (main)

    3106. Dictionary Subsequences

    Problem code: DICTSUB

    You have a dictionary of strings, and you want to perform some queries on the strings. In particular, you're given a single string T, and for each word W in the dictionary, you want to determine if W is a subsequence of T. A string B is a subsequence of a string C if you can remove zero or more of C's letters to form a string equal to B (but the order of remaining letters may not be rearranged).

    Each word W in the dictionary will be described in the input as a run length encoded (RLE) string. That is, W will be described by several pairs of data values, where each pair of data values consists of a positive integer K with no leading zeros and a letter L. A data pair with values K and L represents a string with K occurrences of the character L. To get the uncompressed string, we concatenate all strings represented by the data pairs. For example, the RLE string 2A1B5C12A represents the string AABCCCCCAAAAAAAAAAAA.

    Input

    The first line of the input contains a positive integer C (0<C<10), the number of test cases to follow. Each case begins with a line containing a positive integer D (0<D<10000) representing the number of dictionary words and a string T with length between 1 and 10000. D lines follow, with each line containing a string with length between 1 and 200 in RLE format, which represents a dictionary word with uncompressed length between 1 and 10000. All uncompressed strings (T and dictionary words) will consist only of uppercase letters ('A'-'Z').

    Output

    Output for each case consists of several lines. There should be one line per dictionary word W (in the order of appearance in input) that will say either "YES" if W is a subsequence of T, or "NO" otherwise. Print a blank line after each test case.

    Example

    Input:
    1
    5 EFFERVESCENCE
    2E
    1E1F1V1C1E
    1E2F1C1R
    1S2E
    1P1E2F
    
    
    Output:
    YES
    YES
    NO
    YES
    NO
    

    Added by:John Rizzo
    Date:2008-10-04
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
    Resource:Al-Khawarizm 2008 - Set by eleusive









    SPOJ Problem Set ()

    3107. Odd Numbers of Divisors

    Problem code: ODDDIV

    Given a positive odd integer K and two positive integers low and high, determine how many integers between low and high contain exactly K divisors.

    Input

    The first line of the input contains a positive integer C (0<C<100,000), the number of test cases to follow. Each case consists of a line containing three integers: K, low, and high (1<K<10000, 0<low≤ high<10^10). K will always be an odd integer.

    Output

    Output for each case consists of one line: the number of integers between low and high, inclusive, that contain exactly K divisors.

    Example

    Input:
    3
    3 2 49
    9 1 100
    5 55 235
    
    Output:
    4
    2
    1
    
    

    Added by:John Rizzo
    Date:2008-10-04
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Al-Khawarizm 2008 - Set by eleusive









    SPOJ Problem Set (classical)

    3108. Charlesbert and Merangelou

    Problem code: GRAPHGAM


    Charlesbert and Merangelou are playing a two-player game on a game board. The game board consists of several circles, where some circles are connected to other circles. Charlesbert uses a game piece called the GoalPiece, and Merangelou uses a game piece called the ChasePiece.

    The game is played as follows: at the start of the game, Charlesbert chooses a circle on the board and places the Goalpiece on it, and at the same time Merangelou places the ChasePiece on circle 1. During the next K seconds, Merangelou makes a sequence of moves (at one move per second), where a move consists of either leaving the ChasePiece on its current circle, or moving the ChasePiece from its current circle to a circle that is directly connected to it. If the ChasePiece and the GoalPiece lie on the same circle before or exactly K seconds after Charlesbert last placed the ChasePiece, Merangelou wins. Otherwise, Charlesbert chooses a new circle on the board and places the GoalPiece on it, and Merangelou will make K more moves (Charlesbert moves the GoalPiece before Merangelou makes another move). This process is repeated until the ChasePiece and the GoalPiece lie on the same circle. Note that it is possible for Merangelou to win in fewer than K moves.

    Merangelou wants to win the game as quickly as possible, while Charlesbert wants to keep the game going for as long as possible. Assuming both players play optimally, find the shortest amount of time (in seconds) after which Merangelou is guaranteed to have won the game. If Merangelou cannot win the game (i.e. if Charlesbert can keep the game going forever), then print "INFINITE GAME" instead.

    Input

    The first line of the input contains a positive integer C (0<C<100), the number of test cases to follow. Each case begins with a line containing a two positive integers M and K (1<M<100, 0<K<100), representing the number of circles on the game board and the number of seconds between times that Charlesbert moves the ChasePiece. Each of the following M lines is a string of 'Y' and 'N' characters, with M characters per line. If the jth character of the ith line is 'Y', then circles i and j are connected, otherwise circles i and j are not connected. The jth character of line i will always be the same as the ith character of the jth line, and the kth character of the kth line will always be 'N'. In other words, these M lines form an adjacency matrix for the circles. The ChasePiece always starts on the first circle.

    Output

    For each case, if Merangelou can win then print the shortest amount of time required for her to win. Otherwise, print "INFINITE GAME". The output for each case should appear on its own line.

    Example

    Input:
    3
    5 1
    NNNNY
    NNNNY
    NNNNY
    NNNNY
    YYYYN
    4 2
    NYNN
    YNYN
    NYNY
    NNYN
    4 1
    NYNY
    YNYN
    NYNY
    YNYN
    
    
    Output:
    2
    4
    INFINITE GAME
    
    

    Added by:John Rizzo
    Date:2008-10-04
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Al-Khawarizm 2008 - Set by eleusive









    SPOJ Problem Set (classical)

    3109. Longest Common Prefix

    Problem code: STRLCP

    The LCP (Longest Common Prefix) of two strings A[1..la] and B[1..lb] is defined as follows:

    LCP(A[1..la],B[1..lb]) = max{L | L<=la && L<=lb && A[1..L] == B[1..L]}

    Given an original string and several operations, you should write a program to process all the operations.

    Input

    The first line will be number of test cases T.
    The first line of each test case is a string S with length L (1 <= L <= 100000).
    The second line contains an integer Q(1 <= Q <= 150000), representing the number of operations.

    Each of the following Q lines represents an operation:
    Q i j: print LCP(S[i..L], S[j..L])
    R i char: replace the i-th character of S with char
    I i char: insert character char after the i-th character of S

    Output

    For each "Q i j" operation, print the answer.

    Example

    Input:
    1
    madamimadam
    7
    Q 1 7
    Q 4 8
    Q 10 11
    R 3 a
    Q 1 7
    I 10 a
    Q 2 11
    
    Output:
    5
    1
    0
    2
    1
    

    Added by:John Rizzo
    Date:2008-10-04
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Al-Khawarizm 2008









    SPOJ Problem Set (classical)

    3110. Palindromic Number

    Problem code: PALNUM


    A postive integer A is called a "palindrome number" if the reverse of the decimal representaion is the same as the original one. Ex. 13231 is a palindrome number, but 13333 is not.

    Given a number A(1 <= A <= 1e18), find the number of pairs (a,b) such that a,b are both palindrome numbers, and the sum of a and b is A.

    If A is 391, there are 6 ways: 8 + 383 = 383 + 8 = 391 88 + 303 = 303 + 88 = 391 99 + 292 = 292 + 99 = 391

    Input

    The first Line contains the number of test cases T <= 10. Each test case contains a number A.

    Output

    Output the number of ways.

    Example

    Input:
    1
    391
    
    Output:
    6
    

    Added by:John Rizzo
    Date:2008-10-04
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Al-Khawarizm 2008









    SPOJ Problem Set (classical)

    3111. Stabards

    Problem code: STABARDS


    In a galaxy far far away, there exists a silicon based form of life, who call themselves stabards. Unlike humans, the stabards are multi-gendered. Therefore, when two stabards form a partnership (known as mating in earth parlance), one stabard would be the donor of genetic material and the other would be the combinator of the genetic material. Of course, the combinator had the tougher task, to combine the genetic material and create a new stabard.

    Early on, the wise stabards realized that due to the increased number of genders, every stabard was likely to waste his time trying to find a suitable partner. After that, due to the tremendous opportunity, every stabard would waste some more time trying to cheat on his partner by forming more partnerships (especially the donors since they had nothing much to do). Therefore, the wise ones made the following rules about partnerships:

    1. Each stabard can form at most two partnerships.
    2. In order to maintain a sense of balance, a stabard cannot play the same role (donor/combinator) in both partnerships.
    3. The partnerships shall be formed such that the total number of them is maximized.

    To ensure all rules are being followed, the wise ones send the stabard data every year to earth and wish to know the maximum number of partnerships that can be formed.

    Input

    For each test case, two integers M (the number of stabard genders) and N (the total number of stabards) are given on the first line. M lines follow, each consisting of M characters. The j-th character on the i-th line denotes what would happen if a stabard of gender i formed a partnership with a stabard of gender j. It will be either

    'X' – such a partnership is forbidden.

    'D' – stabard of gender i would be the donor.

    'C' – stabard of gender i would be the combinator.

    After the M lines, N space separated integers are given on a single line. The i-th integer gives the gender of the i-th stabard.

    The end of the test cases is given by a line with M and N both being 0. This test case should not be processed. The total number of test cases will be <= 100.

    Constraints

    0 < M <= 100

    0 < N <= 100

    The gender data for stabards will be symmetric and consistent. (i.e. character i on line j will not conflict with character j on line i). Two stabards of the same gender can never partner each other. (The wise ones fear this will pollute the gene pool. Moreover, big fights would break out as who would be the donor.) The gender given for each stabard will be between 0 and M-1 inclusive.

    Output

    For each test case, a single integer giving the total number of partnerships. Each integer must be on its own line.

    Example

    Input:
    2 4
    XD
    CX
    0 0 1 1
    3 3
    XDC
    CXD
    DCX
    0 1 2
    0 0
    
    Output:
    2
    3
    

    Added by:John Rizzo
    Date:2008-10-04
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Al-Khawarizm 2008 - Set by humblefool









    SPOJ Problem Set (classical)

    3112. Strings

    Problem code: STSTRING

    Given two strings A and B, we define the operator ĉ on {A,B} for string C as C ĉ {A,B}.

    if length(A) < length(C) < length(B), then C satisfies the above operator.
    else
          if length(A)=length(C), then C must be lexicographically greater than A.
          if length(B)=length(C), then C must be lexicographically smaller than B.
    

    Input

    Given two strings A,B with length(A) < = length(B) <= 6. A,B can contain any characters between A and J (capital letters).

    Output

    Print the number of strings satisfying the above criteria. C must also satisfy criteria of A and B. Any two adjacent characters in string C may neither be the same nor consecutve (i.e. the absoulte difference between the ASCII values of adjacent characters is greater than 1).

    Example

    Input:
    A J
    AA BCD
    ABC DEFG
    
    Output:
    8
    129
    1770
    
    

    Added by:John Rizzo
    Date:2008-10-04
    Time limit:2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Al-Khawarizm 2008 - Set by FameofLight and Challenger









    SPOJ Problem Set ()

    3133. Here We Go(relians) Again

    Problem code: GORELIAN


    The Gorelians are a warlike race that travel the universe conquering new worlds as a form of recreation. Given their violent, fun-loving nature, keeping their leaders alive is of serious concern. Part of the Gorelian security plan involves changing the traffic patterns of their cities on a daily basis, and routing all Gorelian Government Officials to the Government Building by the fastest possible route.

    Fortunately for the Gorelian Minister of Traffic (that would be you), all Gorelian cities are laid out as a rectangular grid of blocks, where each block is a square measuring 2520 rels per side (a rel is the Gorelian Official Unit of Distance). The speed limit between two adjacent intersections is always constant, and may range from 1 to 9 rels per blip (a blip, of course, being the Gorelian Official Unit of Time). Since Gorelians have outlawed decimal numbers as unholy (hey, if you're the dominant force in the known universe, you can outlaw whatever you want), speed limits are always integer values. This explains why Gorelian blocks are precisely 2520 rels in length: 2520 is the least common multiple of the integers 1 through 9. Thus, the time required to travel between two adjacent intersections is always an integer number of blips.

    In all Gorelian cities, Government Housing is always at the northwest corner of the city, while the Government Building is always at the southeast corner. Streets between intersections might be one-way or two-way, or possibly even closed for repair (all this tinkering with traffic patterns causes a lot of accidents). Your job, given the details of speed limits, street directions, and street closures for a Gorelian city, is to determine the fastest route from Government Housing to the Government Building. (It is possible, due to street directions and closures, that no route exists, in which case a Gorelian Official Temporary Holiday is declared, and the Gorelian Officials take the day off.)

    Gorelian city

    The picture above shows a Gorelian City marked with speed limits, one way streets, and one closed street. It is assumed that streets are always traveled at the exact posted speed limit, and that turning a corner takes zero time. Under these conditions, you should be able to determine that the fastest route from Government Housing to the Government Building in this city is 1715 blips. And if the next day, the only change is that the closed road is opened to two way traffic at 9 rels per blip, the fastest route becomes 1295 blips. On the other hand, suppose the three one-way streets are switched from southbound to northbound (with the closed road remaining closed). In that case, no route would be possible and the day would be declared a holiday.

    Input

    The input consists of a set of cities for which you must find a fastest route if one exists. The first line of an input case contains two integers, which are the vertical and horizontal number of city blocks, respectively. The smallest city is a single block, or 1 by 1, and the largest city is 20 by 20 blocks. The remainder of the input specifies speed limits and traffic directions for streets between intersections, one row of street segments at a time. The first line of the input (after the dimensions line) contains the data for the northernmost east-west street segments. The next line contains the data for the northernmost row of north-south street segments. Then the next row of east-west streets, then north-south streets, and so on, until the southernmost row of east-west streets. Speed limits and directions of travel are specified in order from west to east, and each consists of an integer from 0 to 9 indicating speed limit, and a symbol indicating which direction traffic may flow. A zero speed limit means the road is closed. All digits and symbols are delimited by a single space. For east-west streets, the symbol will be an asterisk '*' which indicates travel is allowed in both directions, a less-than symbol '<' which indicates travel is allowed only in an east-to-west direction, or a greater-than symbol '>' which indicates travel is allowed only in a west-to-east direction. For north-south streets, an asterisk again indicates travel is allowed in either direction, a lowercase "vee" character 'v' indicates travel is allowed only in a north-to-south directions, and a caret symbol '^' indicates travel is allowed only in a south-to-north direction. A zero speed, indicating a closed road, is always followed by an asterisk. Input cities continue in this manner until a value of zero is specified for both the vertical and horizontal dimensions.

    Output

    For each input scenario, output a line specifying the integer number of blips of the shortest route, a space, and then the word "blips". For scenarios which have no route, output a line with the word "Holiday".

    Example

    Input:
    2 2
    9 * 9 *
    6 v 0 * 8 v
    3 * 7 *
    3 * 6 v 3 *
    4 * 8 *
    2 2
    9 * 9 *
    6 v 9 * 8 v
    3 * 7 *
    3 * 6 v 3 *
    4 * 8 *
    2 2
    9 * 9 *
    6 ^ 0 * 8 ^
    3 * 7 *
    3 * 6 ^ 3 *
    4 * 8 *
    0 0
    
    Output:
    1715 blips
    1295 blips
    Holiday
    

    Added by:Nikola P Borisov
    Date:2008-10-11
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:Mid-Central Regional ACM-ICPC Contest 2007









    SPOJ Problem Set (classical)

    3166. Permutation Exponentiation

    Problem code: PERMSG


    Alice, a permutation aficionado, has thought up a permutation of N (1 <= N <= 100000) integers in the range [0, N-1], P. So impressed with herself she has told her friend Bob about P.

    Normally Alice would call it a day after creating such an impressive permutation but today she decided that she wanted to raise P to the power k (a positive integer) as well! Unfortunately, after working on the problem for a while she gave up because it was taking too long. Not wanting her efforts to go to waste she once again tells Bob about all the elements she has determined so far. Unfortunately, she neglected to tell Bob the value k.

    Bob, very interested in Alice's work, needs your help to try and determine any additional elements of P^k. Bob is suspicious of Alice's work so he also asks you to check it for errors.

    Notes

    For two permutations P, Q, the ith element of the product, (P * Q)[i], can be computed as Q[P[i]] where arrays are all 0-indexed.

    Then P^k is simply P * P * ... k times ... * P.

    Input

    The first line of input contains N (1 <= N <= 100000), the number of elements in the permutation. The next line contains a permutation of the integers 0 through N-1 each separated by a space. The following line will contain the result of applying the permutation k times with the exception that elements that are not known will be -1 instead.

    Output

    Print P^k as a space separated list on its own line with as many elements as possible determined. If an element can't be determined leave it as -1. If there is no k such that P^k has the values given in the input print "Inconsistent" (quotes for clarity) on its own line instead.

    Example

    Input:
    4
    1 2 3 0
    3 -1 -1 -1
    
    Output:
    3 0 1 2
    
    Note: The first four permutations generated are
    
    1 2 3 0
    2 3 0 1
    3 0 1 2
    0 1 2 3

    Example 2

    Input:
    4
    1 2 3 0
    3 -1 2 -1
    
    Output:
    Inconsistent
    

    Added by:Mark Gordon
    Date:2008-10-17
    Time limit:3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS PERL 6
    Resource:Own problem









    SPOJ Problem Set (classical)

    3184. Game of Lines

    Problem code: LINES

    Farmer John has challenged Bessie to the following game: FJ has a board with dots marked at N (2 ≤ N ≤ 200) distinct lattice points. Dot i has the integer coordinates Xi and Yi (-1,000 ≤ Xi, Yi ≤ 1,000).

    Bessie can score a point in the game by picking two of the dots and drawing a straight line between them; however, she is not allowed to draw a line if she has already drawn another line parallel to it. Bessie would like to know her chances of winning, so she has asked you to help find the maximum score she can obtain.

    Input

    There will be multiple test cases. For each case, the first line contains the integer N, and each of the next N lines gives a pair of integers, Xi and Yi. The file ends with the case N = 0, which should not be processed.

    Output

    For each test case, print a single integer representing the maximum number of lines Bessie can draw, no two of which are parallel.

    Example

    Input:
    4
    -1 1
    -2 0
    0 0
    1 1
    0
    
    Output:
    4
    

    Bessie can draw lines of the following four slopes: -1, 0, ⅓, and 1.


    Added by:Neal Wu
    Date:2008-10-19
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:USACO Feb 2008









    SPOJ Problem Set (classical)

    3195. Doors and Penguins

    Problem code: DOORSPEN

    The organizers of the Annual Computing Meeting have invited a number of vendors to set up booths in a large exhibition hall during the meeting to showcase their latest products. As the vendors set up their booths at their assigned locations, they discovered that the organizers did not take into account an important fact — each vendor supports either the Doors operating system or the Penguin operating system, but not both. A vendor supporting one operating system does not want a booth next to one supporting another operating system. Unfortunately the booths have already been assigned and even set up. There is no time to reassign the booths or have them moved. To make matter worse, these vendors in fact do not even want to be in the same room with vendors supporting a different operating system. Luckily, the organizers found some portable partition screens to build a wall that can separate the two groups of vendors. They have enough material to build a wall of any length. The screens can only be used to build a straight wall. The organizers need your help to determine if it is possible to separate the two groups of vendors by a single straight wall built from the portable screens. The wall built must not touch any vendor booth (but it may be arbitrarily close to touching a booth). This will hopefully prevent one of the vendors from knocking the wall over accidentally.

    Input

    The input consists of a number of cases. Each case starts with 2 integers on a line separated by a single space: D and P, the number of vendors supporting the Doors and Penguins operating system, respectively (1 ≤ D, P ≤ 500). The next D lines specify the locations of the vendors supporting Doors. This is followed by P lines specifying the locations of the vendors supporting Penguins. The location of each vendor is specified by four positive integers: x1, y1, x2, y2. (x1, y1) specifies the coordinates of the southwest corner of the booth while (x2, y2) specifies the coordinates of the northeast corner. The coordinates satisfy x1 < x2 and y1 < y2. All booths are rectangular and have sides parallel to one of the compass directions. The coordinates of the southwest corner of the exhibition hall is (0, 0) and the coordinates of the northeast corner is (15000, 15000). You may assume that all vendor booths are completely inside the exhibition hall and do not touch the walls of the hall. The booths do not overlap or touch each other. The end of input is indicated by D = P = 0.

    Output

    For each case, print the case number (starting from 1), followed by a colon and a space. Next, print the sentence: It is possible to separate the two groups of vendors. if it is possible to do so. Otherwise, print the sentence: It is not possible to separate the two groups of vendors. Print a blank line between consecutive cases.

    Example

    Input:
    3 3
    10 40 20 50
    50 80 60 90
    30 60 40 70
    30 30 40 40
    50 50 60 60
    10 10 20 20
    2 1
    10 10 20 20
    40 10 50 20
    25 12 35 40
    0 0
    
    
    Output:
    Case 1: It is possible to separate the two groups of vendors.
    
    Case 2: It is not possible to separate the two groups of vendors.
    
    

    Added by:Daniel Gómez Didier
    Date:2008-10-21
    Time limit:1s-2s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:2007 PUJ - Circuito de Maratones ACIS / REDIS









    SPOJ Problem Set (classical)

    3208. Yet Another Longest Palindrome Problem

    Problem code: PALIM

    A string is called a palindrome if it's the same when read from left to right and from right to left. For example, "abdba" is a palindrome, but "abbaa" is not.

    Given a string, print the length of the longest consecutive sequence of characters occurrences at least once in this string, which is a palindrome.

    Input

    • Line 1: a string consists of at most 100000 characters. The ASCII code of all characters are between 32 and 127, inclusive.
    • Line 2: a magical key(for security purpose).

    Output

    • Line 1: the length of the longest palindrome.
    • Line 2: the magical key.

    Example

    Input:
    abaabbabaaba
    MAGICAL KEY
    
    Output:
    6
    MAGICAL KEY
    

    Restriction

    Only C++ is allowed in this problem now. In addition, you will receive "wrong answer" if your program don't start with this. You can't use macro "#undef" in your solution as well.

    If you want to solve this problem in another language, send me the header file in your language please.

    warning: Don't try to access the memory of tester, or I will reject your solution manually, and you will lose the chance to enjoy this problem as well.

    Hint

    hint of using tester library: you can't read anything from stdin, and you can't print anything as well, your program will be terminated if you called answer().

    hint of viewing feedback: You can click on "wrong answer" link to view the feedback of judge: whether your solution didn't include the testlib, or failed on sample. (if neither, your solution failed on a further test case)

    Notice

    update on Oct.24: I had updated the header file for C++, now you will receive "Runtime Error(NZEC)" if your solution called isSame() illegally. The submissions with old version of header file are still acceptable.

    rejudge on Oct.24: some test cases were added, three submissions were rejudged as TLE instead of AC.


    Added by:Bin Jin
    Date:2008-10-23
    Time limit:1s
    Source limit:10240B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:C++ 4.3.2 C++ 4.0.0-8
    Resource:the (second??) "interactive" problem on SPOJ









    SPOJ Problem Set ()

    3249. Typesettin

    Problem code: TYPESET

    Modern fonts are generally of two varieties: outline fonts, whose glyphs (the individual character shapes) are specified mathematically as a set of curves, and bitmap fonts, whose glyphs are specified as patterns of pixels. Fonts may also include embedded information such as kerning pairs (adjusting the spacing between certain pairs of glyphs, such as "AW", so that they appear spaced correctly), tracking hints (for managing inter-glyph spacing), antialiasing hints (smoothing of pixellated edges), and much more. To be sure, modern fonts are more than a simple collection of shapes, and displaying them properly is a common programming challenge.

    For this problem we will concern ourselves with bitmapped fonts and a simple form of typesetting called glyph packing. Essentially, the idea is to pack the glyphs as tightly as possible while maintaining at least one horizontal pixel of separation between glyphs. For example, consider the glyphs shown to the left below for the Roman characters "P" and "J". The figure to the right shows them after glyph packing. Note that they are as close as possible without touching horizontally.

    PJ

    Here's another example. In this case, notice that the final glyph cannot be packed at all.

    Fiji

    After packing, pixels from distinct glyphs may be adjacent diagonally or vertically, but not horizontally. The following example shows that pixels may be adjacent diagonally. The "Love" test case in the example input section shows that they may be adjacent vertically.

    two slashes

    Glyph packing has the nice property that it's easy to build "fancy" glyphs into the font so that glyph packing creates special effects with no extra work. Look at the "Toy" example below. The same simple packing process has been applied to these glyphs as to the ones above, but the result is more dramatic:

    Toy

    Glyph packing has a few caveats, however, one of which we must concern ourselves with for this problem. Consider the example on the left below where a glyph for a hyphen is followed by a glyph for an underscore. Based on our one horizontal pixel of separation rule, how would this pack? Clearly something more is needed, and that something more is hinting within the glyphs themselves. Recall that in actual practice, fonts contain kerning pairs, tracking hints, etc. For our purposes, our hinting will be limited to "invisible" pixels that count as a pixel for the purpose of packing, but not for display. The center image below represents invisible pixels as open dots instead of closed dots. Now the two glyphs can be properly packed, resulting in the output shown on the right.

    hidden pixels

    Now for the formal definition of a proper packing: (1) Glyphs are packed as close as possible without allowing any pixels from different glyphs to be immediately horizontally adjacent; (2) Given two glyphs, they may not be packed in such a way that any pixel of the leftmost glyph at a given height ends up positioned to the right of any pixel at the same height in the rightmost glyph.

    Condition (2) above is easily understood by visualizing two glyphs sitting side by side, separated by a small space. If you "squeeze" them together, condition (2) says that their pixels are not allowed to "pass through" one another. Consider the example to the left below. The center image is not the proper packing, because it violates condition (2) of the formal definition. The image on the right is the proper packing of these glyphs.

    hooks

    Input

    The input for this problem is sets of glyphs to be packed. In a given test case, all glyphs are the same height, and an integer, N, on the first line of the test case specifies this height. The next N lines contain the glyphs to be packed. Empty pixels in a glyph are represented by a dot '.' character. Non-empty pixels are represented by a hash mark '#' for visible pixels, and a zero '0' for invisible pixels. Glyphs are separated by a single column of space characters. The input will always consist of more than one glyph, at least one of which will always contain at least one visible pixel. A glyph will always have at least one non-empty pixel in its leftmost and rightmost column, and every glyph will have at least one non-empty pixel at the same height as at least one other glyph in the input. The minimum dimension of a glyph is 1 x 1, the maximum dimension is 20 x 20, and the maximum number of glyphs that will appear in any test case is 20. Test cases continue until a value of zero is specified for N.

    Output

    For each test case, first output the number of that test case (starting with 1) on a line by itself. Then output the proper packing of the input glyphs, using the dot '.' character for empty pixels and for invisible pixels, and the hash mark '#' character for visible pixels. Omit leading and trailing empty columns (columns with no visible pixels) so that both the leftmost and rightmost output columns contain at least one visible pixel.

    Example

    Input:
    8
    ###. ...#
    #..# ...#
    #..# ...#
    ###. ...#
    #... ...#
    #... ...#
    #... #..#
    #... ####
    8
    ############# .... .............
    ..#.......... .... .............
    ..#.......... .##. .........#..#
    ..#.......... #..# .........#..#
    ..#.......... #..# .........#..#
    ..#.......... .##. ..........###
    ............. .... ............#
    ............. .... ############.
    8
    ############# .............
    ..#.......... .............
    ..#.......... .........#..#
    ..#.......... .........#..#
    ..#.......... .........#..#
    ..#.......... ..........###
    ............. ............#
    ............. ############.
    5
    0..0 0..0
    0..0 0..0
    #### 0..0
    0..0 0..0
    0..0 ####
    5
    #.... .###.
    #.... #...#
    #...# #...#
    #...# ....#
    .###. ....#
    3
    ### 0.0 ###
    #.# 0.0 #.#
    ### 0.0 ###
    3
    0.0 ### 0.0
    0.0 #.# 0.0
    0.0 ### 0.0
    8
    #.... .... ..... ....
    #.... .... ..... ....
    #.... .##. #...# .##.
    #.... #..# .#.#. #..#
    #.... #..# .#.#. #..#
    #.... #..# .#.#. ###.
    #.... .##. ..#.. #...
    ##### .... ..#.. .###
    0
    
    Output:
    1
    ###..#
    #..#.#
    #..#.#
    ###..#
    #....#
    #....#
    #.#..#
    #.####
    2
    #############
    ..#..........
    ..#..##..#..#
    ..#.#..#.#..#
    ..#.#..#.#..#
    ..#..##...###
    ............#
    ############.
    3
    .....#############
    .......#..........
    .......#.#..#.....
    .......#.#..#.....
    .......#.#..#.....
    .......#..###.....
    ............#.....
    ############......
    4
    .........
    .........
    ####.....
    .........
    .....####
    5
    #......###.
    #.....#...#
    #...#.#...#
    #...#.....#
    .###......#
    6
    ###.....###
    #.#.....#.#
    ###.....###
    7
    ###
    #.#
    ###
    8
    #..............
    #..............
    #..##.#...#.##.
    #.#..#.#.#.#..#
    #.#..#.#.#.#..#
    #.#..#.#.#.###.
    #..##...#..#...
    #####...#...###
    
    

    Added by:Nikola P Borisov
    Date:2008-10-25
    Time limit:10s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Mid-Central Regional ACM-ICPC Contest 2007









    SPOJ Problem Set ()

    3251. Slink

    Problem code: SLINK

    Slitherlink is a puzzle published by Nikoli, the Japanese company that popularized Sudoku. Slitherlink puzzles are gaining momentum, and books of Slitherlink puzzles have started showing up around the world. The puzzles are simple to understand, but can be challenging to solve. The puzzle is simply a rectangular grid of dots that forms a collection of cells, every cell being either blank or containing an integer from zero to three. The challenge is to connect the dots with line segments to form a cycle (a connected path such that every vertex has precisely two incident edges), in such a way that every cell with a value has exactly the number of incident edges as the digit it contains. Cells with no value may have any number of incident edges. A valid Slitherlink puzzle always contains sufficient non-empty cells to guarantee a unique solution. Below is an example from the Nikoli web site of a Slitherlink puzzle and its solution.

    slitherlink example

    It was shown by Takayuki Yato at the University of Tokyo that the general Slitherlink problem is NP-complete. (If you are not familiar with this concept, informally it means there is no "efficient" algorithm to solve the problem.) With a slight modification and some simple heuristics, however, programmatic solutions are possible. Our new puzzle, which we will term Slink, differs from Slitherlink only in that the puzzle may not have empty cells. That is, every cell must specify the number of incident edges. Below is the Slitherlink puzzle above converted to Slink (the added numbers are shown in gray). Note that the solution does not change, only the information given in the puzzle itself.

    slink example

    The heuristics for solving Slink arise from the nature of the puzzle itself. For example, consider a cell containing a zero. There must be no incident edges, therefore all edges incident to all zeros can be immediately removed from consideration as part of the solution path. Consider a three next to a zero. Because all the edges incident to the zero will be eliminated, the common edge shared with the three is also eliminated. But that leaves only three edges around the three, and therefore those three edges must be part of the solution path. The following table specifies the heuristic rules that must be properly applied to solve a Slink puzzle. The "x" characters between vertices mark edges that are not part of the solution path, while line segments between vertices mark edges that form part of the solution. Grey elements are the pattern the rule is based on, black elements indicate the additional edges that should be included or excluded if the rule is matched. Note that the pictured examples are for demonstration purposes only and do not illustrate every possible arrangement of the stated rule!

    Examples Rule Specification
    case 1 The easiest and most obvious of all the rules. Cells containing a zero have no incident edges, so all the edges around a zero should be removed from consideration as part of the solution path.
    case 2

    case 3
    If a cell contains the value n and only n incident edges remain (i.e. have not been eliminated), then the n remaining edges must be part of the solution path. Two examples of this occurring are shown here.
    case 4

    case 5
    If a cell contains the value n and n incident edges have already been included in the path, the remaining edges can be eliminated. Two examples of this occurring are shown here.
    case 6 If two 3's are adjacent to one another, the common edge between the cells as well as the outer edges of both cells are part of the solution path. One example of this arrangement occurring is shown here.
    case 7 If two 3's occur diagonally adjacent, the opposing corners as shown here must be part of the solution path. One example of such an arrangement is shown here.
    case 8 If an edge enters a vertex for which only a single exit remains, that exit must be part of the solution path. One such example is shown here.
    case 9 If a vertex has two incident edges, the other edges can be eliminated from consideration as part of the solution path. One such example is shown here.
    case 10 If any vertex has three incident edges excluded, the fourth incident edge can be excluded as well. One possible arrangement of this occurring is shown here.
    case 11 A 3 for which two of the exits are blocked as shown, such as in a corner of the puzzle, must include the two edges incident to the blocked vertex.
    case 12 If the exits at one corner of a 2 are blocked, and one exit at an adjacent vertex around the 2 is also blocked, then the unblocked exit at that adjacent vertex must be part of the solution path. One example of this arrangement is shown here.
    case 13 A 1 for which the exit paths at one of its incident vertices are both blocked as shown, such as might occur in the corner of the puzzle, must also eliminate the other two edges incident to that vertex as shown.
    case 14 If the solution path enters the corner of a 3, and the exit that goes away from the 3 at that same corner is blocked, then the two edges around the three incident to the opposite corner must be part of the solution path.
    case 15 If a 3 and 1 are diagonally adjacent, and the corner of the 3 furthest from the 1 has the exit segments blocked as shown, then the edges incident to the far corner of the 1 becomes blocked. The opposite is also true; if the far corner of the 1 had been blocked, then the exit segments at the far corner of the 3 would become blocked in the same manner.
    case 16 If the solution path enters the corner of 2 and the path leading away from the 2 at the same corner is blocked, then if one of the paths leading away from the 2 at the diagonally opposite corner is also blocked, the other edge leading away from the 2 at that same corner must be part of the solution path. One example of this arrangement occurring is shown here.
    case 17 If the solution path enters the corner of a 1, and the exit that goes away from the 1 at that same corner is blocked, then the two edges around the three incident to the opposite corner must be eliminated from the solution path.

    Input

    The input for this problem is a set of Slink puzzles to be solved. The first line of a Slink problem's input contains two integers, r and c, separated by a space, the number of rows and the number of columns in the puzzle. The next r rows of the input contain c integers, space delimited, valued from 0 to 3, which specify the content of the puzzle. The minimum dimension of a puzzle is 2 by 2 cells, and the maximum dimension is 20 by 20 cells. It is guaranteed that a unique solution to every input puzzle exists and can be determined with the above rules if a rule is always applied when it can be applied. A line with values of zero for r and c marks the end of the input.

    Output

    The output for this problem is a graphical representation of the Slink puzzle solution. The first data set is 1, the second data set is 2, etc. On a line by itself display the data set number, followed by the solution in exactly the format demonstrated below. Vertical edges are output as the vertical bar '|' character, horizontal edges are output as dash '-' characters, vertices where the path changes direction are output as plus signs '+', and cell numbers are always displayed with a blank to the left and to the right. Further, surround the entire output with a border made up of hash marks '#' such that the number in the upper left cell of the puzzle always occurs four positions to the right of the border and three position below the border, and the number in the lower right cell always occurs four positions to the left of the border and three positions above the border.

    Example

    Input:
    
    8 8
    1 0 1 1 2 2 1 3
    3 3 3 3 2 3 3 2
    2 2 0 1 1 2 2 0
    2 3 1 1 0 1 2 2
    2 1 2 3 1 1 0 2
    1 2 2 2 2 3 2 1
    3 2 1 3 1 1 3 2
    1 0 0 2 3 2 3 2
    6 6
    0 0 1 1 0 0
    0 2 2 2 2 0
    1 2 0 0 2 1
    1 2 0 0 2 1
    0 2 2 2 2 0
    0 0 1 1 0 0
    2 2
    2 2
    2 2
    3 5
    3 3 3 2 3
    1 2 1 3 2
    3 3 2 2 2
    0 0
    
    
    Output:
    
    1
    #####################################
    #                                   #
    #                 +---------------+ #
    #   1   0   1   1 | 2   2   1   3 | #
    # +---+   +---+   |   +---+   +---+ #
    # | 3 | 3 | 3 | 3 | 2 | 3 | 3 | 2   #
    # |   +---+   +---+   |   +---+     #
    # | 2   2   0   1   1 | 2   2   0   #
    # +-------+           +-------+     #
    #   2   3 | 1   1   0   1   2 | 2   #
    # +-------+   +---+           +---+ #
    # | 2   1   2 | 3 | 1   1   0   2 | #
    # |       +---+   |   +---+       | #
    # | 1   2 | 2   2 | 2 | 3 | 2   1 | #
    # |   +---+   +---+   |   +---+   | #
    # | 3 | 2   1 | 3   1 | 1   3 | 2 | #
    # +---+       +---+   |   +---+   | #
    #   1   0   0   2 | 3 | 2 | 3   2 | #
    #                 +---+   +-------+ #
    #                                   #
    #####################################
    2
    #############################
    #                           #
    #                           #
    #   0   0   1   1   0   0   #
    #         +-------+         #
    #   0   2 | 2   2 | 2   0   #
    #     +---+       +---+     #
    #   1 | 2   0   0   2 | 1   #
    #     |               |     #
    #   1 | 2   0   0   2 | 1   #
    #     +---+       +---+     #
    #   0   2 | 2   2 | 2   0   #
    #         +-------+         #
    #   0   0   1   1   0   0   #
    #                           #
    #                           #
    #############################
    3
    #############
    #           #
    # +-------+ #
    # | 2   2 | #
    # |       | #
    # | 2   2 | #
    # +-------+ #
    #           #
    #############
    4
    #########################
    #                       #
    # +---+   +---+   +---+ #
    # | 3 | 3 | 3 | 2 | 3 | #
    # |   +---+   |   |   | #
    # | 1   2   1 | 3 | 2 | #
    # |   +---+   +---+   | #
    # | 3 | 3 | 2   2   2 | #
    # +---+   +-----------+ #
    #                       #
    #########################
    
    

    Added by:Nikola P Borisov
    Date:2008-10-25
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Mid-Central Regional ACM-ICPC Contest 2007









    SPOJ Problem Set (classical)

    3253. Electronic Document Security

    Problem code: EDS


    The Tyrell corporation uses a state-of-the-art electronic document system that controls all aspects of document creation, viewing, editing, and distribution. Document security is handled via access control lists (ACLs). An ACL defines a set of entities that have access to the document, and for each entity defines the set of rights that it has. Entities are denoted by uppercase letters; an entity might be a single individual or an entire division. Rights are denoted by lowercase letters; examples of rights are a for append, d for delete, e for edit, and r for read.

    The ACL for a document is stored along with that document, but there is also a separate ACL log stored on a separate log server. All documents start with an empty ACL, which grants no rights to anyone. Every time the ACL for a document is changed, a new entry is written to the log. An entry is of the form ExR, where E is a nonempty set of entities, R is a nonempty set of rights, and x is either "+", "–", or "=". Entry E+R says to grant all the rights in R to all the entities in E, entry ER says to remove all the rights in R from all the entities in E, and entry E=R says that all the entities in E have exactly the rights in R and no others. An entry might be redundant in the sense that it grants an entity a right it already has and/or denies an entity a right that it doesn't have. A log is simply a list of entries separated by commas, ordered chronologically from oldest to most recent. Entries are cumulative, with newer entries taking precedence over older entries if there is a conflict.

    Periodically the Tyrell corporation will run a security check by using the logs to compute the current ACL for each document and then comparing it with the ACL actually stored with the document. A mismatch indicates a security breach. Your job is to write a program that, given an ACL log, computes the current ACL.

    Input

    The input consists of one or more ACL logs, each 3–79 characters long and on a line by itself, followed by a line containing only "#" that signals the end of the input. Logs will be in the format defined above and will not contain any whitespace.

    Output

    For each log, output a single line containing the log number (logs are numbered sequentially starting with one), then a colon, then the current ACL in the format shown below. Note that (1) spaces do not appear in the output; (2) entities are listed in alphabetical order; (3) the rights for an entity are listed in alphabetical order; (4) entities with no current rights are not listed (even if they appeared in a log entry), so it's possible that an ACL will be empty; and (5) if two or more consecutive entities have exactly the same rights, those rights are only output once, after the list of entities.

    Example

    Input:
    MC-p,SC+c
    YB=rde,B-dq,AYM+e
    GQ+tju,GH-ju,AQ-z,Q=t,QG-t
    JBL=fwa,H+wf,LD-fz,BJ-a,P=aw
    #
    
    Output:
    1:CSc
    2:AeBerMeYder
    3:
    4:BHJfwLPaw
    

    Added by:Nikola P Borisov
    Date:2008-10-25
    Time limit:1s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Mid-Central Regional ACM-ICPC Contest 2007









    SPOJ Problem Set (classical)

    3254. Guard

    Problem code: GUARD

    Guard Placement

    The Bluewater Security Company provides guards for clients with valuable possessions. Bluewater has found that clients are interested in having guards posted where they can see everything that is valuable merely by turning their heads, and also like guards to be posted particularly close to particularly valuable items. A sample site layout is shown above. Ignore the three black dots for now. Various locations are labeled and assigned values. For instance location A at coordinates (0,8) is the position of an item with value 4. Locations showing a value 0, like G, do not have a valuable item. The straight lines indicate corridors. For simplicity, corridors are modeled as line segments with 0 width. A guard at an intersection point of several corridors can see and therefore guard the items on each of the corridors. If Bluewater were contracted to supply 3 guards, they might choose to post them at the positions indicated with the small black dots. The guard not at an already labeled position is at (15.5, 6). To model the desire for guards to be closer to items of higher value, Bluewater calculates the risk to a valuable item to be the value of the item times the minimum distance to a guard that can see the item. Even if a guard is close to an item that is around a corner, that guard does not affect the risk to the item, since the guard cannot see around a corner. In the diagram shown, the risks to the items are A: 4x5=20, C: 4x2.5=10, D: 2x0=0, .... The largest risks are for H: 50x7.5=375 and I: 50x7.5=375, so the maximum risk to any one item is 375. With this site layout, no arrangement of 3 guards would provide a lower maximum risk, so this arrangement of 3 guards minimizes the maximum risk. Bluewater would like to be able to tell any client who requests a particular number of guards for a particular site layout, what the minimized maximum risk will be.

    Input

    The input will consist of one to sixteen data sets, followed by a line containing only 0. On each line the data will consist of blank separated tokens.

    The first line of a dataset contains integers p c g, where p is the number of points specified, c is the number of corridors, and g is the number of guards to be placed. Constraints are 1< p < 12; 0 < c < 12; 0 < g < 5.

    Next in the dataset are a total of p groups of four tokens, each consisting of a capital letter and three nonnegative integers L x y v indicating the point (x, y) with label L contains an item with value v. If p is no greater than 6, these groups will all be on one line. If p is greater than 6, then the seventh and further groups will be on the next line. Labels will be consecutive letters starting from A. All the numbers are less than 1000. Each of the points is unique. A value of 0 for v means there is no item of value there. The number of locations with items of value will be at least as large as the number of guards.

    The last line of a dataset contains c strings of letters, one for each corridor. For each corridor the letters are labels for points along the corridor, in order along the line segment from one end to the other, including both endpoints, all intersection points with other corridors, and all locations on the corridor with a valuable item. Each of the points given in the dataset will lie on at least one of the corridors.

    Output

    There is one line of output for each data set. If there are not enough guards supplied to be able to see all the valuables, the line is "too few guards". Otherwise the line is an unsigned number r rounded to two places beyond the decimal point, where r is the minimum value over all placements of g guards of the maximum "risk" to the valuables.

    The first example dataset matches the illustration above, and the next three examples only vary the number of guards.

    Example

    Input:
    11 5 3
    A 0 8 4 B 5 8 0 C 14 8 4 D 21 8 2 E 25 8 1 F 5 22 1
    G 5 20 0 H 11 12 50 I 20 0 50 J 19 10 5 K 25 4 5
    ABCDE AG FGB GHCI JDK
    11 5 2
    A 0 8 4 B 5 8 0 C 14 8 4 D 21 8 2 E 25 8 1 F 5 22 1
    G 5 20 0 H 11 12 50 I 20 0 50 J 19 10 5 K 25 4 5
    ABCDE AG FGB GHCI JDK
    11 5 1
    A 0 8 4 B 5 8 0 C 14 8 4 D 21 8 2 E 25 8 1 F 5 22 1
    G 5 20 0 H 11 12 50 I 20 0 50 J 19 10 5 K 25 4 5
    ABCDE AG FGB GHCI JDK
    11 5 4
    A 0 8 4 B 5 8 0 C 14 8 4 D 21 8 2 E 25 8 1 F 5 22 1
    G 5 20 0 H 11 12 50 I 20 0 50 J 19 10 5 K 25 4 5
    ABCDE AG FGB GHCI JDK
    3 3 1
    A 0 0 50 B 0 3 60 C 4 0 20
    AB CB CA
    0
    
    Output:
    375.00
    1250.00
    too few guards
    21.21
    150.00
    
    

    Added by:Nikola P Borisov
    Date:2008-10-25
    Time limit:5s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS NODEJS PERL 6
    Resource:Mid-Central Regional ACM-ICPC Contest 2007









    SPOJ Problem Set (classical)

    3261. Race Against Time

    Problem code: RACETIME

    As another one of their crazy antics, the N (1 ≤ N ≤ 100,000) cows want Farmer John to race against the clock to answer some of their pressing questions.

    The cows are lined up in a row from 1 to N, and each one is holding a sign representing a number, Ai (1 ≤ Ai ≤ 1,000,000,000). The cows need FJ to perform Q (1 ≤ Q ≤ 50,000) operations, which can be either of the following:

    • Modify cow i's number to X (1 ≤ X ≤ 1,000,000,000). This will be represented in the input as a line containing the letter M followed by the space-separated numbers i and X.
    • Count how many cows in the range [P, Q] (1 ≤ P ≤ Q ≤ N) have Ai ≤ X (0 ≤ X ≤ 1,000,000,000). This will be represented in the input as a line containing the letter C followed by the space-separated numbers P, Q, and X.

    Of course, FJ would like your help.

    Input

    The first line gives the integers N and Q, and the next N lines give the initial values of Ai. Finally, the next Q lines each contain a query of the form "M i X" or "C P Q X".

    Output

    Print the answer to each 'C' query, one per line.

    Example

    Input:
    4 6
    3
    4
    1
    7
    C 2 4 4
    M 4 1
    C 2 4 4
    C 1 4 5
    M 2 10
    C 1 3 9
    
    Output:
    2
    3
    4
    2
    

    FJ has 4 cows, whose initial numbers are 3, 4, 1, and 7. The cows then give him 6 operations; the first asks him to count the how many of the last three cows have a number at most 4, the second asks him to change the fourth cow's number to 1, etc.

    Warning: large input/output data.
    Added by:Neal Wu
    Date:2008-10-25
    Time limit:1s-8s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS









    SPOJ Problem Set (classical)

    3305. Roman Patrollers

    Problem code: SA04C


    In ancient times, patrollers were used to ensure that all the cities of the Roman Empire were under control. A patroller’s job consisted in continuously visiting the cities of the empire, trying to minimise the interval between two visits to each city. The Military Society (MS) wants to simulate the behavior of one such patroller to see how effective they were.

    Each cycle of the simulation corresponds to one time unit. The instantaneous city idleness (ICI) for a city X after T cycles of the simulation is the number of cycles elapsed since the last visit of the patroller to the city X (i.e. the number of time units the city X remained unvisited). All of the cities have initial instantaneous city idleness equal to zero at the start of the simulation. The instantaneous empire idleness (IEI) after each given cycle is the sum of the instantaneous city idleness of all cities after that given cycle. Finally, the empire idleness (EI) for an N-cycle simulation is the sum of the instantaneous empire idleness after each of the N cycles of simulation.

    After visiting a city X, the patroller always chooses to visit the neighbour city Y with the highest instantaneous city idleness (if more than one city has the highest idleness, the one with the lowest identifier is chosen). Cities X and Y are neighbour if there is a road linking the two cities directly, without going through any intermediate city. In the beginning of the simulation, the patroller is located in one of the cities, and is given a map of the Roman Empire containing a description of all the roads in the empire, indicating the length (in kilometers) and which two cities each road connects. A road between cities X and Y can be used both to go from X to Y and from Y to X.

    Assuming that a patroller travels one kilometer in one time unit (one simulation cycle) and that the time to visit a city is negligible (equal to zero), MS asks you to determine the empire idleness after an N-cycle simulation.

    For clarity, consider the example of an empire which contains 3 cities (1, 2 and 3) and two roads of length 1 km. The first road connects cities 1 and 2, while the second road connects cities 2 and 3. Below you find a trace of a 3-cycle simulation for such a scenario, considering that the patroller starts at city 1.

    Start of the simulation
    Patroller at: 1
    ICI1 = 0, ICI2 = 0, ICI3 = 0
    IEI = 0
    EI = 0

    After cycle 1
    Patroller at: 2
    ICI1 = 1, ICI2 = 0, ICI3 = 1
    IEI = 2
    EI = 2

    After cycle 2
    Patroller at: 1
    ICI1 = 0, ICI2 = 1, ICI3 = 2
    IEI = 3
    EI = 5

    After cycle 3 Patroller at: 2
    ICI1 = 1, ICI2 = 0, ICI3 = 3
    IEI = 4
    EI = 9

    Therefore, for such a scenario, after 3 simulation cycles the empire idleness is 9.

    Input

    The input consists of several test cases. The first line of a test case contains four integers C,R,N, and S, indicating respectively the quantity of cities in the empire (2 · C · 1000), the number of roads (1 · R · C(C − 1)/2), the number of cycles to be simulated (1 · N · 1000) and the identifier of the starting city of the patroller (1 · S · C). Each city is identified by a distinct integer from 1 to C. Each of the following R lines contains three integers X, Y and D describing a road; X and Y represent cities (1 · X 6= Y · C) and D represents the distance (1 · D · 1000), in kilometers, of the road that connects X and Y directly, without passing through any other city. Each pair of cities X and Y will appear at most once in a road description. You can assume that it is always possible to travel from any city to any other city in the empire using the roads available. The end of input is indicated by C = R = N = S = 0.

    Output

    For each test case in the input, your program must produce one line containing the empire idleness after the N-cycle simulation.

    Example

    Input:
    2 1 1 1
    1 2 2
    2 1 2 1
    1 2 2
    2 1 3 1
    1 2 2
    2 1 4 1
    1 2 2
    3 2 3 1
    1 2 1
    2 3 1
    0 0 0 0
    
    Output:
    2
    4
    8
    10
    9
    

    Added by:Daniel Gómez Didier
    Date:2008-11-07
    Time limit:1s-3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:ACM International Collegiate Programming Contest 2004 – Brazil Sub-Regional









    SPOJ Problem Set (classical)

    3306. Very Special Boxes

    Problem code: SA04D

    Special Box Company (SBC) is a small family-owned and family-run business which produces decorated carton boxes for wrapping gifts. The boxes are hand-made, produced individually from fine materials. When accepting an order from a client, they always produce a few more boxes than needed, to keep a stock of boxes to be sold in the future, if needed. Over the years their stock has been growing, with boxes all over the place, and they decided they needed to organize it a bit more. They have therefore made a list registering the dimensions of every box in their stock.
    SBC has just received an order from a client that must be delivered tomorrow, so there is no time to produce new boxes. The client wants a certain number N of boxes all of the same size; each box will be used to pack one item of dimensions X, Y and Z. As the carton used in the boxes is very thin, you may assume that a box of size (X, Y, Z) would fit perfectly the item the client wants to wrap. If there are not at least N boxes that fit perfectly, the client wants N boxes that fit the items as tightly as possible. The box size that fits the items as tightly as possible is the one which minimizes the empty space when the item is put inside the box. An item can be rotated in any direction to be accomodated inside a box; therefore, a box of size(X, Y, Z) is as good as a box of size (Y, Z, X), for example.

    Can you help SBC finding whether they can fulfill the customer order?

    Input

    The input consists of several test cases. The first line of a test case contains two integers N and M, indicating respectively the number of boxes the client needs to buy (1 ≤ N ≤ 1500) and the number of boxes in the stock list (1 ≤ M ≤ 1500). The second line contains three integers X, Y and Z, representing the dimensions of the item the client wants to wrap (0 < X, Y, Z ≤ 50).
    Each of the next M lines contains three integers A, B and C representing the dimensions of a box in the stock list (0 < A, B, C ≤ 50). A test case with N = 0 indicates the end of the input.

    The input must be read from standard input.

    Output

    For each test case in the input your program must produce one line, containing either:

    -> The single word ‘impossible’, in case it is not possible to fulfill the client’s order (because there are not at least N boxes of the same size in stock that can contain the item); or

    -> one integer V , which specifies the volume of empty space left when one of the N items packed in one of the boxes chosen.

    Example

    Input:
    1 1
    2 4 3
    2 3 4
    2 6
    3 1 3
    7 4 7
    10 8 2
    2 8 10
    6 2 9
    7 7 4
    6 2 9
    1 1
    3 3 3
    1 1 1
    0 0
    
    
    Output:
    0
    99
    impossible
    
    

    Added by:Daniel Gómez Didier
    Date:2008-11-07
    Time limit:1s-3s
    Source limit:50000B
    Cluster: Pyramid (Intel Pentium III 733 MHz)
    Languages:All except: ERL JS
    Resource:ACM International Collegiate Programming Contest 2004 – Brazil Sub-Regional









    SPOJ Problem Set (classical)

    3307. Hex Tile Equations

    Problem code: HEXTILE

    An amusing puzzle consists of a collection of hexagonal tiles packed together with each tile showing a digit or '=' or an arithmetic operation '+', '-', '*', or '/'. Consider continuous paths going through each tile exactly once, with each successive tile being an immediate neighbor of the previous tile. The object is to choose such a path so the sequence of characters on the tiles makes an acceptable equation, according to the restrictions listed below. A sequence is illustrated in each figure above. In Figure 1, if you follow the gray path from the top, the character sequence is"6/3=9-7". Similarly, in Figure 2, start from the bottom left 3 to get "3*21+10=73".

    There are a lot of potential paths through a moderate sized hex tile pattern. A puzzle player may get frustrated and want to see the answer. Your task is to automate the solution.

    The arrangement of hex tiles and choices of characters in each puzzle satisfy these rules:

    1. The hex pattern has an odd number of rows greater than 2. The odd numbered rows will all contain the same number of tiles. Even numbered rows will have one more hex tile than the odd numbered rows and these longer even numbered rows will stick out both to the left and the right of the odd numbered rows.
    2. There is exactly one '=' in the hex pattern.
    3. There are no more than two '*' characters in the hex pattern.
    4. There will be fewer than 14 total tiles in the hex pattern.
    5. With the restrictions on allowed character sequences described below, there will be a unique acceptable solution in the hex pattern.

    To have an acceptable solution from the characters in some path, the expressions on each side of the equal sign must be in acceptable form and evaluate to the same numeric value. The following rules define acceptable form of the expressions on each side of the equal sign and the method of expression evaluation:

      1. The operators '+', '-', '*', and '/' are only considered as binary operators, so no character sequences where '+' or '-' would be a unary operator are acceptable. For example "-2*3=-6" and "1 =5+-4" are not acceptable.
      2. The usual precedence of operations is not used. Instead all operations have equal precedence and operations are carried out from left to right. For example "44-4/2=2+3*4" is acceptable and "14=2+3*4" is not acceptable.
      3. If a division operation is included, the equation can only be acceptable if the division operation works out to an exact integer result. For example "10/5=12/6" and "7+3/5=3*4/6" are acceptable. "5/2*4=10" is not acceptable because the sides would only be equal with exact mathematical calculation including an intermediate fractional result. "5/2*4=8" is not acceptable because the sides of the equation would only be equal if division were done with truncation.
      4. At most two digits together are acceptable. For example, "123+1 = 124" is not acceptable.
      5. A character sequences with a '0' directly followed by another digit is not acceptable. For example, "3*05=15" is not acceptable.

      With the assumptions above, an acceptable expression will never involve an intermediate or final arithmetic result with magnitude over three million.

      Input

      The input will consist of one to fifteen data sets, followed by a line containing only 0.

      The first line of a dataset contains blank separated integers r c, where r is the number of rows in the hex pattern and c is the number of entries in the odd numbered rows. The next r lines contain the characters on the hex tiles, one row per line. All hex tile characters for a row are blank separated. The lines for odd numbered rows also start with a blank, to better simulate the way the hexagons fit together. Properties 1-5 apply.

      Output

      There is one line of output for each data set. It is the unique acceptable equation according to rules 6-10 above. The line includes no spaces.

      Example

      Input:
      5 1
       6
      / 3
       =
      9 -
       7
      3 3
       1 + 1
      * 2 0 =
       3 3 7
      5 2
       9 -
      * 2 =
       3 4
      + 8 3
       4 /
      0
      
      Output:
      6/3=9-7
      3*21+10=73
      8/4+3*9-2=43
      
      

      Added by:Nikola P Borisov
      Date:2008-11-07
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Mid-Central Regional ACM-ICPC Contest 2008









      SPOJ Problem Set (classical)

      3308. The Bridges of San Mochti

      Problem code: BRIDGES2


      You work at a military training facility in the jungles of San Motchi. One of the training exercises is to cross a series of rope bridges set high in the trees. Every bridge has a maximum capacity, which is the number of people that the bridge can support without breaking. The goal is to cross the bridges as quickly as possible, subject to the following tactical requirements:

      One unit at a time!
      If two or more people can cross a bridge at the same time (because they do not exceed the capacity), they do so as a unit; they walk as close together as possible, and they all take a step at the same time. It is never acceptable to have two different units on the same bridge at the same time, even if they don't exceed the capacity. Having multiple units on a bridge is not tactically sound, and multiple units can cause oscillations in the rope that slow everyone down. This rule applies even if a unit contains only a single person.
      Keep moving!
      When a bridge is free, as many people as possible begin to cross it as a unit. Note that this strategy doesn't always lead to an optimal overall crossing time (it may be faster for a group to wait for people behind them to catch up so that more people can cross at once). But it is not tactically sound for a group to wait, because the people they're waiting for might not make it, and then they've not only wasted time but endangered themselves as well.

      Periodically the bridges are reconfigured to give the trainees a different challenge. Given a bridge configuration, your job is to calculate the minimum amount of time it would take a group of people to cross all the bridges subject to these requirements.

      For example, suppose you have nine people who must cross two bridges: the first has capacity 3 and takes 10 seconds to cross; the second has capacity 4 and takes 60 seconds to cross. The initial state can be represented as (9 0 0), meaning that 9 people are waiting to cross the first bridge, no one is waiting to cross the second bridge, and no one has crossed the last bridge. At 10 seconds the state is (6 3 0). At 20 seconds the state is (3 3 /3:50/ 0), where /3:50/ means that a unit of three people is crossing the second bridge and has 50 seconds left. At 30 seconds the state is (0 6 /3:40/ 0); at 70 seconds it's (0 6 3); at 130 seconds it's (0 2 7); and at 190 seconds it's (0 0 9). Thus the total minimum time is 190 seconds.

      Input

      The input consists of one or more bridge configurations, followed by a line containing two zeros that signals the end of the input. Each bridge configuration begins with a line containing a negative integer –B and a positive integer P, where B is the number of bridges and P is the total number of people that must cross the bridges. Both B and P will be at most 20. (The reason for putting –B in the input file is to make the first line of a configuration stand out from the remaining lines.) Following are B lines, one for each bridge, listed in order from the first bridge that must be crossed to the last. Each bridge is defined by two positive integers C and T, where C is the capacity of the bridge (the maximum number of people the bridge can hold), and T is the time it takes to cross the bridge (in seconds). C will be at most 5, and T will be at most 100. Only one unit, of size at most C, can cross a bridge at a time; the time required is always T, regardless of the size of the unit (since they all move as one). The end of one bridge is always close to the beginning of the next, so the travel time between bridges is zero.

      Output

      For each bridge configuration, output one line containing the minimum amount of time it will take (in seconds) for all of the people to cross all of the bridges while meeting both tactical requirements.

      Example

      Input:
      -1 2
      5 17
      -1 8
      3 25
      -2 9
      3 10
      4 60
      -3 10
      2 10
      3 30
      2 15
      -4 8
      1 8
      4 30
      2 10
      1 12
      0 0 
      
      Output:
      17
      75
      190
      145
      162
      
      

      Added by:Nikola P Borisov
      Date:2008-11-07
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Mid-Central Regional ACM-ICPC Contest 2008









      SPOJ Problem Set (classical)

      3309. Bulletin Board

      Problem code: BULLETIN

      The ACM Student Chapter has just been given custody of a number of school bulletin boards. Several members agreed to clear off the old posters. They found posters plastered many levels deep. They made a bet about how much area was left clear, what was the greatest depth of posters on top of each other, and how much of the area was covered to this greatest depth. To determine each bet's winner, they made very accurate measurements of all the poster positions as they removed them. Because of the large number of posters, they now need a program to do the calculations. That is your job.

      A simple illustration is shown above: a bulletin board 45 units wide by 40 high, with three posters, one with corners at coordinates (10, 10) and (35, 20), another with corners at (20, 25) and (40, 35), and the last with corners at (25, 5) and (30, 30). The total area not covered by any poster is 1300. The maximum number of posters on top of each other is 2. The total area covered by exactly 2 posters is 75.

      Input

      The input will consist of one to twenty data sets, followed by a line containing only 0. On each line the data will consist of blank separated nonnegative integers.

      The first line of a dataset contains integers n w h, where n is the number of posters on the bulletin board, w and h are the width and height of the bulletin board. Constraints are 0 < n ≤ 100; 0 < w ≤ 50000; 0 < h ≤ 40000.

      The dataset ends with n lines, each describing the location of one poster. Each poster is rectangular and has horizontal and vertical sides. The x and y coordinates are measured from one corner of the bulletin board. Each line contains four numbers xl yl xh and yh, where xl and yl, are the lowest values of the x and y coordinates in one corner of the poster and xh and yh are the highest values in the diagonally opposite corner. Each poster fits on the bulletin board, so 0 ≤ xl < xhw, and 0 ≤ yl < yhh.

      Output

      There is one line of output for each data set containing three integers, the total area of the bulletin board that is not covered by any poster, the maximum depth of posters on top of each other, and the total area covered this maximum number of times.

      Caution: An approach examining every pair of integer coordinates might need to deal with 2 billion coordinate pairs.

      Example

      Input:
      3 45 40
      10 10 35 20
      20 25 40 35
      25 5 30 30
      1 20 30
      5 5 15 25
      2 2000 1000
      0 0 1000 1000
      1000 0 2000 1000
      3 10 10
      0 0 10 10
      0 0 10 10
      0 0 10 10
      0
      
      Output:
      1300 2 75
      400 1 200
      0 1 2000000
      0 3 100
      
      

      Added by:Nikola P Borisov
      Date:2008-11-07
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Mid-Central Regional ACM-ICPC Contest 2008









      SPOJ Problem Set (classical)

      3310. Serial Numbers

      Problem code: SERIALN

      A manufacturer keeps an ordered table of serial numbers by listing in each row of the table a range of serial numbers along with two corresponding pieces of information called the status code and the transfer code. A four-column table stores information about ranges of serial numbers in this order: starting serial number, ending serial number, status code, transfer code. Serial numbers as well as transfer codes are integers from 1 to 231-1 (231-1 = 2147483647), and status codes are a single upper-case letter. The table is maintained in increasing order of serial numbers, serial number ranges are never allowed to overlap, and for any given serial number, the table must always accurately represent the most recent data (status code and transfer code) for that serial number.

      Let's say that 100,000 serial numbers are created with a status of "A" and a transfer code of "1". An entry for those serial numbers might look like this:

      1 100000 A 1

      This is obviously far more efficient than storing 100,000 individual rows all with the same status and transfer codes. The challenge arises when serial numbers within already defined ranges need to be given different status or transfer codes. For example, if serial number 12345 needs to change to status B, the above table would need to become three separate entries:

      1 12344 A 1
      12345 12345 B 1
      12346 100000 A 1

      Now let's change the transfer code of all serial numbers in the range 12000 to 12999 to 2. This gets us:

      1 11999 A 1
      12000 12344 A 2
      12345 12345 B 2
      12346 12999 A 2
      13000 100000 A 1

      Now change all existing serial numbers from 10000 to 100000 to status C and transfer code 2:

      1 9999 A 1
      10000 100000 C 2

      Once created a serial number will never be deleted, but it is possible to have ranges of undefined serial numbers between ranges of defined ones. To demonstrate, let's now set all serial numbers from 1000000 to 1999999 to status Z and transfer code 99:

      1 9999 A 1
      10000 100000 C 2
      1000000 1999999 Z 99

      Finally, the table is always maintained with a minimal number of rows, meaning specifically that there will never be two adjacent rows in the table where one would suffice. For example, consider the following serial number table:

      1 10 A 1
      11 20 A 1
      21 30 B 1

      The first two rows could actually be represented by a single row, meaning that the table above does not have a minimal number of rows. The same data represented by a minimal number of rows would look like this:

      1 20 A 1
      21 30 B 1

      The following table, however, because the first two rows have non-matching transfer codes, already contains the minimal number of rows:

      1 10 A 1
      11 20 A 2
      21 30 B 1

      Similarly, the following table cannot be reduced further because the first two rows do not represent a continuous series of serial numbers:

      1 10 A 1
      12 20 A 1
      21 30 B 1

      Input

      Each input case begins with a single line that is a character string naming the test case. This string contains at most 80 characters. The name "END" marks the end of the input. Following this will be 1 to 100 lines of the form "A B S T", where A, B, and T are integers in the range 1 to 231-1, S is an uppercase letter, and A<=B. These lines are, in the order they are to be applied, the serial number transactions to be recorded, where A is the start of the serial number range, B is the end of the serial number range, S is the status code, and T is the transfer code. The list of serial number transactions is terminated by a line containing only a 0 (zero) character.

      Output

      For each input case, echo the test case name to the output on a line by itself, followed by the resulting minimal-rows serial number table that results after all serial number transactions have been applied.

      Example

      Input:
      First Example
      1 100000 A 1
      12345 12345 B 1
      0
      And Another
      1 100000 A 1
      12345 12345 B 1
      12000 12999 A 2
      12345 12345 B 2
      0
      Test Case Three
      1 100000 A 1
      12345 12345 B 1
      12000 12999 A 2
      12345 12345 B 2
      10000 100000 C 2
      0
      Example Four
      1 100000 A 1
      12345 12345 B 1
      12000 12999 A 2
      12345 12345 B 2
      10000 100000 C 2
      1000000 1999999 Z 99
      0
      Example 5
      1 10 A 1
      21 30 B 1
      11 20 A 1
      0
      Example 6
      21 30 B 1
      1 10 A 1
      11 20 A 2
      0
      Example 7
      12 20 A 1
      21 30 B 1
      1 10 A 1
      0
      END
      
      
      Output:
      First Example
      1 12344 A 1
      12345 12345 B 1
      12346 100000 A 1
      And Another
      1 11999 A 1
      12000 12344 A 2
      12345 12345 B 2
      12346 12999 A 2
      13000 100000 A 1
      Test Case Three
      1 9999 A 1
      10000 100000 C 2
      Example Four
      1 9999 A 1
      10000 100000 C 2
      1000000 1999999 Z 99
      Example 5
      1 20 A 1
      21 30 B 1
      Example 6
      1 10 A 1
      11 20 A 2
      21 30 B 1
      Example 7
      1 10 A 1
      12 20 A 1
      21 30 B 1
      
      

      Added by:Nikola P Borisov
      Date:2008-11-07
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Mid-Central Regional ACM-ICPC Contest 2008









      SPOJ Problem Set (classical)

      3314. Umnozak

      Problem code: UMNOZAK

      The digit-product of a positive integer is the product of the number's decimal digits. For example, the digit-product of 2612 is 2 · 6 · 1 · 2 = 24.

      The self-product of a number is the product of the number and its digit-product. For example, the self-product of 2612 is 2612 · 24 = 62688.

      Write a program that, given two positive integers A and B (1 ≤ A ≤ B < 1018), calculates the number of positive integers whose self-product is between A and B, inclusive.

      Input

      The first line of input contains the integer T (1 ≤ T ≤ 20). The next T lines each contain a pair of integers A and B.

      Output

      For each test case, print a line with the number of positive integers whose self-product is between A and B.

      Example

      Input:
      3
      20 30
      145 192
      2224222 2224222
      
      Output:
      2
      4
      1
      

      For the second example, the self-products of the numbers 19, 24, 32, and 41 are 171, 192, 192 and 164, respectively.


      Added by:Neal Wu
      Date:2008-11-08
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:Croatian Olympiad in Informatics 2008









      SPOJ Problem Set (classical)

      3322. Doubled Numbers

      Problem code: DOUBLE

      Some numbers have a curious property: when rotating the number to the right, the new number is the double of the original. Rotating the number to the right means choosing the last digit and moving it to the beginning of the number, as the leftmost digit. For example, the number 421052631578947368 when rotated to the right gives 842105263157894736, which is the double of the original. These numbers are expressed in the decimal system. In any numeral system such numbers exist, for example, in the binary (base 2) numeral system, numbers 01 and 0101 have this property. Note that leading zeros are required in this case.

      Write a program that, for any given base B (2 <= B <= 250), finds the smallest number in that numeral system which has this property. Try not to precompute the numbers, the solution is very easy and pretty.

      Input

      The input consists of several test cases. The first line contains an integer T (T <= 20), the number of test cases. The following T lines contain one number B, each.

      Output

      For each number B, output one or more numbers separated by a blank space that represent the digits in base B (written as decimal numbers) of the smallest number which has this property.

      Example

      Input:
      3
      2
      10
      35
      Output:
      0 1
      0 5 2 6 3 1 5 7 8 9 4 7 3 6 8 4 2 1
      11 23
      

      Output explanation

      In  example #1
      The initial number (when converted to decimal system):
      0 * 2^1 + 1 * 2^0 = 1 
      After applying the rotation:
      1 * 2^1 + 0 * 2^0  = 2.
      
      In example #3
      The initial number (when converted to decimal system):
      11 * 35^1 + 23 * 35^0  =  408
      After applying the rotation:
      23 * 35^1 + 11 * 35^0  = 816.
      

      Added by:Reinier César Mujica Hdez
      Date:2008-11-10
      Time limit:2s
      Source limit:3072B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:OCI Olimpiads Cuban in Informatics 2008 day 1









      SPOJ Problem Set (classical)

      3347. Cestarine

      Problem code: HIGHWAY

      In a single day, N of Luka's trucks travel a specific highway. The highway has a number of exits and entrances. An exit with a particular number is in the same location as the entrance with that number.

      Upon entering the highway, a truck driver receives a ticket which indicates the entrance he used. When exiting, the driver pays a toll equal to the absolute difference of the entrance and exit numbers. For example, if a ticket says he used entrance 30, then exiting at exit 12 will cost him 18.

      Luka has figured out a way to save toll money that his company daily spends. Any two drivers can meet on the highway and exchange tickets, even if their routes don't overlap. Tickets can be exchanged an arbitrary number of times.

      However, a driver cannot use an exit if his ticket says he used the same entrance, since that would be suspicious.

      Write a program that calculates the least total amount of tolls that the drivers can achieve by exchanging tickets.

      Input

      On the first line of the input is the integer T (1 ≤ T ≤ 5), the number of test cases. T cases follow, each beginning with the single integer N (2 ≤ N ≤ 100,000). Each of the next N lines contains two integers between 1 and 1,000,000,000 inclusive, representing the entrance and exit numbers of a truck. Note that no two trucks will have the same entrance or exit numbers.

      Output

      For each test case, output the least total amount of tolls Luka's company must pay.

      Example

      Input:
      2
      3
      3 65
      45 10
      60 25
      3
      5 5
      6 7
      8 8
      
      Output:
      32
      5
      

      In the first example, the first and third drivers will exchange tickets. After this, the second and third drivers exchange tickets. After this, the drivers will have the tickets 60, 3, 45, respectively. The total amount in tolls is |65 - 60| + |10 - 3| + |25 - 45| = 32.

      Warning: large input/output data.
      Added by:Neal Wu
      Date:2008-11-13
      Time limit:1s-8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:Croatian Open 07/08 - Contest 6









      SPOJ Problem Set (classical)

      3359. Stack

      Problem code: STACK

      Alan loves to construct a stack of building bricks. His stack consists of many cuboids with square base. All cuboids have the same height 1. Alan puts the consecutive cuboids one over another.

      Recently in math class, the concept of volume was introduced to Alan. Consequently, he wants to compute the volume of his stack now. The lengths of cuboids bases (from top to bottom) are constructed by Alan in the following way:

      • Length of edge of the first square is one. i.e. a1 = 1.
      • Next, Alan fixes the length of the edge of the second square a2.
      • Next, Alan calculates the length an (n > 2) by 2*a2*an-1 - an-2. Do not ask why he chose such a formula; let us just say that he is a really peculiar young fellow.

      For example, if Alan fixes a2 = 2, then a3 = 7. If Alan fixes a2 = 1, then an = 1 holds for all n.

      Now Alan wonders if he can calculate the volume of stack of N consecutive building bricks. Help Alan and write the program that computes this volume. Since it can be quite large, it is enough to compute the answer modulo given natural number m.

      Input

      The input contains several test cases. The first line contains the number t (t <= 100000) denoting the number of test cases. Then t test cases follow. Each of them is given in a separate line containing three integers a2, N, m (1 <= a2, m <= 109, 2 <= N <= 109) separated by a single space.

      Output

      For each test case compute the volume of stack of N consecutive bricks constructed by Alan according to steps 1 to 3 and output its remainder modulo m.

      Example

      Input:
      3
      2 3 100
      1 4 1000
      3 3 1000000000
      
      Output:
      54
      4
      299
      

      Warning: large input/output data, be careful with certain languages

      Warning: A naive algorithm won't terminate in even 2 minutes.


      Added by:[Trichromatic] XilinX
      Date:2008-11-15
      Time limit:43s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:ACM Central European Programming Contest, Wroc³aw 2008









      SPOJ Problem Set (classical)

      3360. Digital Image Recognition

      Problem code: IMGREC2

      Description

      According to Wikipedia, image processing is any form of signal processing for which the input is an image, such as photographs or frames of video; the output of image processing can be either an image or a set of characteristics or parameters related to the image. Most image-processing techniques involve treating the image as a two-dimensional signal and applying standard signal-processing techniques to it.

      The task you are facing here is a relatively easy one (compared to our general conception of image processing!). Given a black-and-white image of size R * C with some digits (and possibly other shapes) on it, your program needs to figure out the digits written on the image. Specifically, the digits drawn on the graph will adhere to the following rules:

      1) Digits are drawn with a series of strokes. A stroke can be regarded as a rectangle of any size on the image, and its edges will always be parallel to either x-axis or y-axis. The number of strokes required to draw each digit will be exactly as follows:

      0 	1 	2 	3 	4 	5 	6 	7 	8 	9
      4 	1 	5 	4 	3 	5 	5 	2 	5 	5
      

      Refer to the figure below if you are unclear about how the digits are drawn.

      2) Although the width of strokes used to draw a digit might be different, the outer shapes of digits will strictly follow those specified in the figure below.

      3) In order for a digit to be recognizable, all parts (strokes and joints) presented in the graph below must also be clearly distinguishable in the image.

      (Refer to the last sample test case if you are unsure about this requirement; in that test case, when the middle stroke of 2 is omitted, the number should not be considered as recognizable.)

      4) You may assume that the image is not rotated, and there is no noise in the input.

      Please output the sum of digits recognizable in the graph. In the case that no characters is recognizable, please output 0 instead.

      Input

      There are multiple test cases in the input file.

      Each test case starts with two integers, R and C (1 <= R,C <= 500), specifying the number of rows / columns of the graph. Each of the following R lines contains consecutive C characters ("0" or "1"), describing the image to be processed.

      Two successive test cases are separated by a blank line. A case with R = 0, C = 0 indicates the end of the input file, and should not be processed by your program.

      Output

      For each test case, please print a single integer, the sum of recognizable numbers. See the sample output for format details.

      Example

      Input:
      5 12
      001101011111
      000101000011
      000101001111
      001101000011
      000000000111
      
      5 3
      111
      010
      110
      010
      110
      
      6 14
      11111000011111
      11001000000011
      11111001000000
      11111001001110
      11001011001010
      11111000001110
      
      5 2
      11
      01
      11
      01
      11
      
      6 9
      111100111
      000100001
      000100011
      011100010
      010000011
      011110000
      
      0 0
      
      Output:
      Case #1: 4
      Case #2: 0
      Case #3: 15
      Case #4: 3
      Case #5: 2
      

      Added by:[Trichromatic] XilinX
      Date:2008-11-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:ACM/ICPC Asian Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      3363. Svada

      Problem code: SVADA

      The local zoo has acquired a large open garden in which animals may freely move as in their natural habitats and entertain visitors with their usual shenanigans.

      The most popular animals are monkeys. With their climbing and jumping and other skills, they delight old and young visitors alike.

      One species of monkey has specialized in climbing tall trees and picking off coconuts. Another species has specialized in breaking them open.

      There are N monkeys of the first type (numbered 1 through N) and M monkeys of the second type (numbered 1 through M).

      Monkey k of the first type takes Ak seconds to find a good spot on the tree, after which it picks off its first coconut. After that the monkey produces a new coconut every Bk seconds.

      Monkey k of the second type takes Ck seconds to find a good tool for opening the coconuts, after which it opens its first coconut. After that the monkey opens another coconut every Dk seconds.

      Unfortunately, the second type of monkey is extremely aggressive so the two types may not be in the garden at the same time. Therefore, zoo keepers will chase away the first type of monkeys as soon as they have picked off all the coconuts. Similarly, if monkeys of the same type stay too long after opening all the coconuts, fights will ensue. Because of that, zoo keepers will send them away as soon as they have opened all the coconuts.

      The zoo keepers first arrive immediately after all coconuts have been picked, and again immediately after the monkeys open them all. The time needed for monkeys to enter or leave the garden is also negligibly small.

      Tomislav especially likes the second type of monkey, but can never guess when to arrive in order to see them. Help him calculate the time when the second type arrives if he knows the total time that monkeys spent in the garden, but does not know the number of coconuts in the garden.

      Input

      The first line contains the integer T (1 ≤ T ≤ 1 000 000 000), the total time that monkeys spent in the garden, in seconds.

      The next line contains the integer N (1 ≤ N ≤ 100), the number of monkeys of the first type.

      Each of the following N lines contains two integers Ak and Bk (1 ≤ Ak, Bk ≤ 1 000 000 000), how fast monkey k of the first type is.

      The next line contains the integer M (1 ≤ M ≤ 100), the number of monkeys of the second type.

      Each of the following M lines contains two integers Ck and Dk (1 ≤ Ck, Dk ≤ 1 000 000 000), how fast monkey k of the second type is.

      Output

      Output the number of seconds between the arrival of the first type of monkeys and the arrival of the second type.

      Example

      Input:
      20
      2
      3 2
      1 3
      3
      3 1
      4 1
      5 1
      
      Output:
      13
      
      

      Added by:Race with time
      Date:2008-11-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:COCI 2008-2009









      SPOJ Problem Set ()

      3372. Round Table

      Problem code: ROUNDT

      We have a round table with 2*N seats (1<= N <= 2000). The seats are numbered with the numbers from 1 to 2*N in order. This round table is in a round room with two doors. Door 1 is between seats 1 and 2N on the table, and door 2 is between seats N and N+1. We have 2N guests that we want to seat. Each guest has a id from 1 to 2N and we want to seat him/her exactly at the seat corresponding to his id. All the guest are split into two groups of N and each group is waiting in front of a door in a line. This room unfortunately has the problem that if you let a person go from door 1 and he/she has to seep at position p, to get to his seat he has to make either all people seating on seats from 1 to p-1 or all people seating on seats p+1 to 2N to get up to let him in. This presents you with the problem of how to let the guests in to cause minimum number of getting ups. The only thing you control is from which door to let the next guest. The guests that are waiting in front of door 1 can only get in from door 1 the same is true with door 2.

      Input

      On the first line there will one integer - N. Two more lines of input follow each with N integers in the range [1, 2N] - the guests waiting in front of door 1 and door 2 respectively. The first people in the list is the first to enter the room.

      Output

      Single integer the total min number of stand-ups that will happen if we choose the best sequence of letting guest in.

      Example

      Input:
      3
      4 5 3
      6 2 1
      
      Output:
      3
      

      Added by:Nikola P Borisov
      Date:2008-11-17
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6









      SPOJ Problem Set (classical)

      3373. Permutation Code

      Problem code: PERMCODE


      As the owner of a computer forensics company, you have just been given the following note by a new client:

      I, Albert Charles Montgomery, have just discovered the most amazing cypher for encrypting messages. Let me tell you about it. 

      To begin, you will need to decide on a set of symbols, call it S, perhaps with the letters RATE. The size of this set must be a power of 2 and the order of the symbols in S is important. You must note that R is at position 0, A at 1, T at 2, and E at 3. You will also need one permutation P of all those symbols, say TEAR. Finally you will need an integer, call it x. Together, these make up the key. Given a key, you are now ready to convert a plaintext message M of length n (M[0], M[1]... M[n-1]), that has some but not necessarily all of the symbols in S, into a cyphertext string C, also of length n (C[0], C[1],...C[n-1]), that has some but not necessarily all of the symbols in S.

      The encrypting algorithm computes C as follows:

      1. Calculate an integer d as the remainder after dividing the integer part of (n1.5 + x) by n. This can be expressed more succinctly as d = (int)(n1.5 + x) % n, where "%" is the remainder operator.
      2. Set C[d] to be the symbol in S whose position is the same as the position of M[d] in P.
      3. For each jd in 0..n-1, set C[j] to be the symbol in S whose position is the value obtained by xor-ing the position of M[j] in P with the position of M[(j+1) % n] in S. Note that the bitwise xor operator is "^" in C, C++, and Java.

      For example, consider this scenario where S=RATE, P=TEAR, x=102, M=TEETER, and n=6. To compute d, first calculate 61.5 + 102 = 116.696938, then take the remainder after dividing by 6. So d = 116 % 6 = 2. The following table shows the steps in filling in the cyphertext C. Note that the order of the steps is not important.


      0
      1
      2
      3
      4
      5

      S =
      R
      A
      T
      E



      P =
      T
      E
      A
      R



      M =
      T
      E
      E
      T
      E
      R









      C =
      E





      M[0] is T, T is at P[0]. M[1] is E, E is at S[3]. C[0] = S[0 xor 3] = S[3]

      E
      T




      M[1] is E, E is at P[1]. M[2] is E, E is at S[3]. C[1] = S[1 xor 3] = S[2]

      E
      T
      A



      2 is d. M[2] is E, E is at P[1], so C[2] =  S[1]

      E
      T
      A
      E


      M[3] is T, T is at P[0]. M[4] is E, E is at S[3]. C[3] = S[0 xor 3] = S[3]

      E
      T
      A
      E
      A

      M[4] is E, E is at P[1]. M[5] is R, R is at S[0]. C[4] = S[1 xor 0] = S[1]

      E
      T
      A
      E
      A
      A
      M[5] is R, R is at P[3]. M[0] is T, T is at S[2]. C[5] = S[3 xor 2] = S[1]

      I have included additional examples of encrypted messages at the end of this note for you to experiment with. However, first, I need to tell you about the decryption algorithm.

      Unfortunately, the next page of the note, with the decrypting algorithm, is completely unreadable because it is covered with huge, overlapping, messy ink blots. Given your considerable skill in unravelling puzzles, your task is to write the decoder based on your knowledge of the encoding algorithm.

      Input

      The input for the decoder consists of one or more sets of {key, encrypted message} pairs. The key is on 3 separate lines. The first line contains the single integer x, 0 < x < 10,000; the second line contains the string S; and the third line contains the string P, which will be a permutation of S. The length of S (and therefore P) will always be one of the following powers of two: 2, 4, 8, 16, or 32. Following the key is a line containing the encrypted message string C, which will contain at least one and at most sixty characters. The strings S, P, and C will not contain whitespace, but may contain printable characters other than letters and digits. The end of the input is a line which contains the single integer 0.

      Output

      For each input set print the decrypted string on a single line, as shown in the sample output.

      Example

      Input:
      102
      RATE
      TEAR
      ETAEAA
      32
      ABCDEFGHIJKLMNOPQRSTUVWXYZ._!?,;
      ;ABCDEFGHIJKLMNOPQRSTUVWXYZ._!?,
      MOMCUKZ,ZPD
      1956
      ACEHINT_
      ACTN_IHE
      CIANCTNAAIECIA_TAI
      0
      
      Output:
      TEETER
      HELLO_WORLD
      THE_CAT_IN_THE_HAT
      
      

      Added by:Nikola P Borisov
      Date:2008-11-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Mid-Central Regional ACM-ICPC Contest 2004









      SPOJ Problem Set (main)

      3374. Scavenger Hunt

      Problem code: SCAVHUNT


      Bill has been the greatest boy scout in America and has become quite a superstar because he always organized the most wonderful scavenger hunts (you know, where the kids have to find a certain route following certain hints). Bill has retired now, but a nationwide election quickly found a successor for him, a guy called George. He does a poor job, though, and wants to learn from Bill’s routes. Unfortunately Bill has left only a few notes for his successor. Bill never wrote his routes completely, he only left lots of little sheets on which he had written two consecutive steps of the routes. He then mixed these sheets and memorized his routes similarly to how some people learn for exams: practicing again and again, always reading the first step and trying to remember the following. This made much sense, since one step always required something from the previous step. George however would like to have a route written down as one long sequence of all the steps in the correct order. Please help him make the nation happy again by reconstructing the routes.

      Input

      The first line contains the number of scenarios. Each scenario describes one route and its first line tells you how many steps (3 ≤ S ≤ 333) the route has. The next S − 1 lines each contain one consecutive pair of the steps on the route separated by a single space. The name of each step is always a single string of letters.

      Output

      The output for every scenario begins with a line containing “Scenario #i:”, where i is the number of the scenario starting at 1. Then print S lines containing the steps of the route in correct order. Terminate the output for the scenario with a blank line.

      Example

      Input:
      2
      4
      SwimmingPool OldTree
      BirdsNest Garage
      Garage SwimmingPool
      3
      Toilet Hospital
      VideoGame Toilet
      
      
      Output:
      Scenario #1:
      BirdsNest
      Garage
      SwimmingPool
      OldTree
      
      Scenario #2:
      VideoGame
      Toilet
      Hospital
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-17
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK ERL JS NODEJS PYTH 3.2.3 n SED
      Resource:2007 - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set ()

      3375. Stamps

      Problem code: STAMPS

      Everybody hates Raymond. He’s the largest stamp collector on planet earth and because of that he always makes fun of all the others at the stamp collector parties. Fortunately everybody loves Lucy, and she has a plan. She secretly asks her friends whether they could lend her some stamps, so that she can embarrass Raymond by showing an even larger collection than his. Raymond is so sure about his superiority that he always tells how many stamps he’ll show.And since Lucy knows how many she owns, she knows how many more she needs. She also knows how many friends would lend her some stamps and how many each would lend. But she’s like to borrow from as few friends as possible and if she needs too many then she’d rather not do it at all. Can you tell her the minimum number of friends she needs to borrow from?

      Input

      The first line contains the number of scenarios. Each scenario describes one collectors party and its first line tells you how many stamps (from 1 to 1000000) Lucy needs to borrow and how many friends (from 1 to 1000) offer her some stamps. In a second line you’ll get the number of stamps (from 1 to 10000) each of her friends id offering.

      Output

      The output for every scenario begins with a line containing “Scenario #i:”, where i is the number of the scenario starting at 1. Then print a single line with the minimum number of friends Lucy needs to borrow stamps from. If it’s impossible even if she borrows everything from everybody, write impossible. Terminate the output for the scenario with a blank line.

      Example

      Input:
      3
      100 6
      13 17 42 9 23 57
      99 6
      13 17 42 9 23 57
      1000 3
      314 159 265
      
      
      Output:
      Scenario #1:
      3
      
      Scenario #2:
      2
      
      Scenario #3:
      impossible
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-17
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:2007 - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3376. Parking Lot

      Problem code: PARKINGL


      At a certain college, a small parking lot is arranged in a rectangular shape, with 20 spaces numbered 1, 2, 3..... 19, 20. Traffic flow is one way in a counter- clockwise direction. The lot looks something like this:

      subir imagenes


      Note that the first position encountered upon entering is 1 and the last is 20. Cars may exit or continue to drive in a counter-clockwise direction. The following assumptions apply to this problem:

      • At the start, class is in session and the lot is full (all 20 spaces are occupied by parked cars).

      • In addition to the (20) cars already parked in the lot, K autos are in the lot waiting for positions to become available (1 ≤ K ≤ 20).

      • Each waiting auto is positioned behind one of the occupied spaces. When a position empties, the space is filled either by the car waiting at that position or, if no car is waiting at that position, by the closest car, bearing in mind that the traffic flow is one way. (There is sufficient room at each position for the car parked in that position to leave and the car waiting at that position to then park.)

      • When an auto advances N positions to a free spot, all other cars advance N positions. Since the lot is circular, advancing 4 positions from position 18 means advancing to position 2.

      • None of the waiting cars exits.

      Input

      Write a program that reads data from standard input. Input consist of a line indicating the number of datasets, a blank line, and the datasets separated by a blank line. Each dataset is in two parts. The first part consists of integers, one per line beginning in column 1, representing initial positions of waiting autos. An integer 99 signals the end of this part of the data. The second part consists of integers, in the same format, representing positions vacated. Positions are vacated in the order in which their numbers appear in the second part of the data.

      Output

      The output of each dataset should consist a series of lines giving, for each initial (waiting) car posi- tion, the initial position and the final position of that car based on the description and assumptions stated above. The output lines must appear in the same order as the order of the initial positions given in the input. Print a blank line between datasets.

      Example

      Input:
      1
      
      6
      19
      17
      13
      1
      99
      1
      3
      20
      16
      
      Output:
      Original position 6 parked in 16
      Original position 19 parked in 3
      Original position 17 did not park
      Original position 13 parked in 20
      Original position 1 parked in 1
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-17
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:2007 PUJ - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3377. A Bug’s Life

      Problem code: BUGLIFE

      Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes that they feature two different genders and that they only interact with bugs of the opposite gender. In his experiment, individual bugs and their interactions were easy to identify, because numbers were printed on their backs.

      Given a list of bug interactions, decide whether the experiment supports his assumption of two genders with no homosexual bugs or if it contains some bug interactions that falsify it.

      Input

      The first line of the input contains the number of scenarios. Each scenario starts with one line giving the number of bugs (at least one, and up to 2000) and the number of interactions (up to 1000000) separated by a single space. In the following lines, each interaction is given in the form of two distinct bug numbers separated by a single space. Bugs are numbered consecutively starting from one.

      Output

      The output for every scenario is a line containing “Scenario #i:”, where i is the number of the scenario starting at 1, followed by one line saying either “No suspicious bugs found!” if the experiment is consistent with his assumption about the bugs’ sexual behavior, or “Suspicious bugs found!” if Professor Hopper’s assumption is definitely wrong.

      Example

      Input:
      2
      3 3
      1 2
      2 3
      1 3
      4 2
      1 2
      3 4
      
      
      Output:
      Scenario #1:
      Suspicious bugs found!
      Scenario #2:
      No suspicious bugs found!
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-17
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:2007 PUJ - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set ()

      3379. String Shuffle

      Problem code: SSHUFFLE

      Given three strings consisting of just lowercase letters, count the number of ways that the third string can be constructed by combining two subsequences from the first two strings.

      One derives a subsequence of the string by deleting zero or more characters from a string. For example, “”, “a”, “b”, “c”, “ab”, “ac”, “bc”, and “abc” are all the subsequence strings of “abc”. (Note that the empty string, “”, is a subsequence of any string.)

      The two subsequences are combined to make a third string by shuffling them together. That is, the relative order of the letters from the subsequence cannot be changed in the target string; but the two subsequences can be interleaved arbitrarily. For example, consider the two subsequences “abc” and “de”. By combining them, one can get the following strings: “abcde”, “abdce”, “abdec”, “adbce”, “adbec”, “adebc”, “dabce”, “dabec”, “daebc”, and “deabc”.

      Input

      The first line of the input contains a single integer t that indicates the number of test cases. Each test case contains 3 strings, each containing only lowercase characters. The length of each string is between 1 and 60, inclusive.

      Output

      For each test case, output a line with a single integer that denotes the number of ways that one can construct the third string from the first two strings as described above.

      Example

      Input:
      3
      abc abc abc
      aa aa aa
      abbcd bccde abcde
      
      
      Output:
      8
      10
      18
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:2008 PUJ - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3380. Tourist

      Problem code: TOURIST

      A lazy tourist wants to visit as many interesting locations in a city as possible without going one step further than necessary. Starting from his hotel, located in the north-west corner of city, he intends to take a walk to the south-east corner of the city and then walk back. When walking to the south-east corner, he will only walk east or south, and when walking back to the north-west corner, he will only walk north or west. After studying the city map he realizes that the task is not so simple because some areas are blocked. Therefore he has kindly asked you to write a program to solve his problem.

      Given the city map (a 2D grid) where the interesting locations and blocked areas are marked, determine the maximum number of interesting locations he can visit. Locations visited twice are only counted once.

      Input

      The first line in the input contains the number of test cases (at most 20). Then follow the cases. Each case starts with a line containing two integers, W and H (2 ≤ W , H ≤ 100), the width and the height of the city map. Then follow H lines, each containing a string with W characters with the following meaning:

      . Walkable area
      * Interesting location (also walkable area)
      # Blocked area

      You may assume that the upper-left corner (start and end point) and lower-right corner (turning point) are walkable, and that a walkable path of length H + W − 2 exists between them.

      Output

      For each test case, output a line containing a single integer: the maximum number of interesting locations the lazy tourist can visit.

      Example

      Input:
      2
      9 7
      *........
      .....**#.
      ..**...#*
      ..####*#.
      .*.#*.*#.
      ...#**...
      *........
      5 5
      .*.*.
      *###.
      *.*.*
      .###*
      .*.*.
      
      
      Output:
      7
      8
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:2007 PUJ - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3381. Highways

      Problem code: HIGHWAYS

      A number of cities are connected by a network of highways. Each highway is bidirectional and connects two cities, with a given travel time. What is the shortest time to get from a given city to another given city?

      Input

      The first line of input contains the number of test cases.

      Each test case starts with a line containing the number of cities n (2 ≤ n ≤ 100000), the number of highways m (1 ≤ m ≤ 100000), the starting city and the ending city. Cities are numbered from 1 to n.

      Then m lines follow, each describing one highway. The decription consists of the two distinct city numbers and the time in minutes to travel along the highway. The time will be between 1 and 1000.

      Output

      For each test case output a single line containing the minimum time it takes to get from the start to the destination. If no connection exists, output NONE.

      Example

      Input:
      2
      4 2 1 4
      1 2 5
      3 4 5
      4 4 1 4
      1 2 5
      2 3 5
      3 4 5
      4 2 6
      
      
      Output:
      NONE
      11
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3382. Monster Trap

      Problem code: MONSTER

      Once upon a time when people still believed in magic, there was a great wizard Aranyaka Gondlir. After twenty years of hard training in a deep forest, he had finally mastered ultimate magic, and decided to leave the forest for his home.

      Arriving at his home village, Aranyaka was very surprised at the extraordinary desolation. A gloom had settled over the village. Even the whisper of the wind could scare villagers. It was a mere shadow of what it had been.

      What had happened? Soon he recognized a sure sign of an evil monster that is immortal. Even the great wizard could not kill it, and so he resolved to seal it with magic. Aranyaka could cast a spell to create a monster trap: once he had drawn a line on the ground with his magic rod, the line would function as a barrier wall that any monster could not get over. Since he could only draw straight lines, he had to draw several lines to complete a monster trap, i.e., magic barrier walls enclosing the monster. If there was a gap between barrier walls, the monster could easily run away through the gap.

      For instance, a complete monster trap without any gaps is built by the barrier walls in the left figure, where “M” indicates the position of the monster. In contrast, the barrier walls in the right figure have a loophole, even though it is almost complete.

      subir imagenes


      Your mission is to write a program to tell whether or not the wizard has successfully sealed the monster.

      Input

      The input consists of multiple data sets, each in the following format.

      subir imagenes


      The first line of a data set contains a positive integer n, which is the number of the line segments drawn by the wizard. Each of the following n input lines contains four integers x, y, x , and y , which represent the x– and y–coordinates of two points (x, y) and (x , y ) connected by a line segment. You may assume that all line segments have non–zero lengths. You may also assume that n is less than or equal to 100 and that all coordinates are between −50 and 50, inclusive.

      For your convenience, the coordinate system is arranged so that the monster is always on the origin (0, 0). The wizard never draws lines crossing (0, 0).

      You may assume that any two line segments have at most one intersection point and that no three line segments share the same intersection point. You may also assume that the distance between any two intersection points is greater than 10^−5 .

      An input line containing a zero indicates the end of the input.

      Output

      For each data set, print “yes” or “no” in a line. If a monster trap is completed, print “yes”. Otherwise, i.e., if there is a loophole, print “no”.

      Example

      Input:
      8
      -7 9 6 9
      -5 5 6 5
      -10 -5 10 -5
      -6 9 -9 -6
      6 9 9 -6
      -1 -2 -3 10
      1 -2 3 10
      -2 -3 2 -3
      8
      -7 9 5 7
      -5 5 6 5
      -10 -5 10 -5
      -6 9 -9 -6
      6 9 9 -6
      -1 -2 -3 10
      1 -2 3 10
      -2 -3 2 -3
      0
      
      Output:
      yes
      no
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:2008 PUJ - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3385. Yoda Goes Palindromic !

      Problem code: YODA

      According to a very famous web site, which in this case we will trust, defines a palindrome as ‘a word, phrase, verse, or sentence that reads the same backward or forward’. For example, the phrase A man, a plan, a canal, Panama! is a palindrome. Actually, writing texts consisting of only palindromes is part of a literary technique called constrained writing.

      Now imagine the wise Yoda, the master of all, whose proficiency putting words together in sentences is one of his well-kwnown abilities. He is now interested in enriching his long- lasting, and maybe boring, inactivity periods by ‘composing’ palindromic sentences. That is, he has plans to use only palindromic sentences for his chats. For this matter, he needs to practice. The first task in his practice plan is to count all the palindromes that can be arranged out of a collection of characters.

      Today, you will be Yoda’s assistant for this first task. Your only mission is to, given a sequence of characters, determine how many palindromes can be obtained with some of the characters in the sequence; you will only take into account uppercase or lowercase letters. Put in other way, you need to determine how many permutations of a give sequence of characters are palindromes. Your solution will help definitively master Yoga.

      Input

      The input consists of several test cases, one per line. For each test case, the input consist of a sequence of ASCII characters.

      Output

      For each test case you should print in a single line, and according to the order of the test cases, the total number of palindromes generated by the input sequence of ASCII characters. For your purpose, you should only consider uppercase or lowercase characters appearing in the input; any other character should be ignored in the calculations. Uppercase and lowercase characters are not considered different; for example, A and a should not be considered different. In any case, the total number of palindromes will not exceed the number e^43 , where e is approximately 2.71828. Remember that the empty sequence is a palindrome itself.

      Example

      Input:
      A man, a plan, a canal, Panama!
      arD,R!A
      B.a.C1/
      12[’;. =1
      
      Output:
      15120
      2
      0
      1
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-18
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:2007 U.Nacional - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3387. Changing Maze

      Problem code: CHMAZE

      Luke Skywalker and his sister/love interest Leia are trying to get through a killer maze. And I mean killer! Every time step, the boundaries change. If our twins/lovebirds ever visit a square the same time a boundary appears, they’re toast. There is no need to panic; the Force will guide them through the maze, and they will not die. However, the Force needs to know what advice to give and is therefore asking you for help.

      Luke and Leia begin in the northwest corner of a maze. They want to make it to the southeast corner of the maze. At any given time step, Luke and Leia can move one square north, south, east, or west, or they can stay where they are. At every time step, the boundaries of the maze change: there is a finite list of patterns; if Luke and Leia are still in the maze when the list of patterns is exhausted, the maze cycles through again from the beginning of the list. You need to compute whether Luke and Leia can make it to the southeast corner of the maze, and, if so, the minimum number of time steps necessary for them to get there. Remember, the Force is counting on you! If you give the Force bad advice, we’ll have to wait around for A Newer Hope and Force Knows how long that could take!

      Input

      The input consists of several test cases. Each case (but the last) will begin with a line containing three decimal integers. The first is the number of rows in the maze; the second is the number of columns in the maze; the third is the number of patterns in the list. The first two numbers will be inclusively between 1 and 20; the third will be inclusively between 1 and 10. The integers will be separated by exactly one space and will be followed by one . Immediately following this line will be a number of patterns, equal to the number specified on the first line. Each pattern will consist of r lineas each containing c characters, where r is the number of rows and c is the number of columns indicated on the first line. Each character will be either 0 (indicating no boundary) or 1 (indicating a boundary). Each line will be terminated by , and an extra will follow each pattern. The northwest corner of the first pattern will always be zero, since Luke and Leia will be starting from there. The last case will be three zeros, separated by exactly one space and followed by exactly one . This case is not to be processed; it indicates the end of input.

      Output

      The output cases are to appear in the same order in wich they appear in the input. Each output case should be of the form Case c: Luke and Leia can escape in s steps. or of the form Case c: Luke and Leia cannot escape. c and s are decimal integers. c in the number of the case being processed (starting with 1) and s is the minimum number of time steps Luke and Leia require to reach the southeast corner. Each line should be terminated by exactly one .

      Example

      Input:
      5 5 1
      00000
      00000
      00000
      00000
      00000
      5 5 2
      00000
      00000
      00000
      00000
      00000
      01110
      01110
      11111
      01110
      01110
      0 0 0
      
      Output:
      Case 1: Luke and Leia can escape in 8 steps.
      Case 2: Luke and Leia cannot escape.
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:2007 U.Nacional - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3388. Double Near Palindromes

      Problem code: DNPALIN

      C-3PO is an expert in pretty much every language. His conversation with R2-D2 are always fun to observe un that R2-D2 speaks in Droid, C-3PO speak in English, and they understand each other perfectly! Anyway, humans and droids both enjoy playing word games. A palindrome is a word or sequence of one or more letters that reads the same forwards and backwards. A near palindrome is a word or sequence that can be changed to or kept a palindrome by changing exactly one letter to a different letter. For example. BAT is a near palindrome, since changing the T to a B woluld make the word a palindrome: BAB. PEEP is not a near palindrome: although PEEP is palindrome, changing any letter would remove its palindrome status. A double near palindrome is a word or sequence that consist of two near palindromes concatenated together. For example, BATMAN is a double near palindrome, since BAT and MAN are both near palindromes. Given a list of words, you are to determine wich words are double near palindromes and wich are not.

      Input

      The input consists of one or more words. All words (except the last) will be inclusively between 1 and 25 letters long and will consist of entirely of capital letters. The last word will be *END* and is not be processed; it simply indicates the end of the input. There may be any number of spaces and characters before, after, and between words.

      Output

      The output cases are to appear in the same order in wich they appear in the input. For each input case, you are to print either w is a double near palindrome. or w is not a double near palindrome. wichever is appropriate, where w is the input word. Exactly one should follow each output case (meaning there should be no blank lines in the output).

      Example

      Input:
      BATMAN
      CONSTANTINOPLE
      *END*
      
      Output:
      BATMAN is a double near palindrome.
      CONSTANTINOPLE is not a double near palindrome.
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:2007 U.Nacional - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3389. The Knights of the Round Circle

      Problem code: KNIGHTSR

      A group of Jedi Knights is having a competition. One of the Knights at random stands within a circle. The other Knights, in a random order, challenge him. If a challenger de- feats the Knight of the Round Circle, that Knight must leave the contest. The challenger then becomes the new Knight of the Round Circle and, as such, will face all subsequent challengers until he is defeated. If the current Knight of the Round Circle wins the chal- lenge, he stays within the circle and the challenger must leave the competition. The Knight within the circle at the end of the competition is deemed the winer. You may assume that no two Knights have exactly the same skill and that a stronger Knight will always defeat a weaker Knight.

      Suppose there are three Knights in the competition. If the strongest one happens to stand in the circle first, he will not be defeated, so no one will ever leave the circle. If the weakest one happens to be first in the circle, he will be kicked out after his first match. If th e Knight that defeated him was the strongest, he will win the final challenge as well (so only one Knight will ever leave the circle),otherwise the strongest Knight will kick the middle Knight out of the circle during his challenge (so that two Knights leave the circle). If the middle Knight stands in the circle first, he will be the only one kicked out of the circle, no matter what order the other two come at him. All in all, an average of 5/6 or 0.83 Knight will leave the circle during the competition.

      You are to compute the average number of Knights to leave the circle during a competition given the number of Knights in the competition.

      Input

      The input consists of several lines. Each line (but the last) will contain one positive decimal integer no larger than 10000. This integer is followed by exactly one . These integers represent the number of Knights in the competition. The last line will contain one zero, followed by . This line is not to be processed; it merely signifies the end of the input.

      Output

      The output cases are to appear in the same order in wich they appear in the input. For each case, you are to print With c competitors, a Jedi Knight will be replaced approximately t times. c is the number of competitors in this case and should be a decimal integer. t is the average number of times a Jedi Knight leaves the circle and should be a floating point decimal number with exactly two digits following the decimal point. There should always be at least one digit before the decimal point (use 0.50 rather .50, for example) The statement should be followed by two ’s, wich is to say that a blank line should follow every output case.

      Example

      Input:
      3
      1000
      0
      
      Output:
      With 3 competitors, a Jedi Knight will be replaced approximately 0.83 times.
      
      With 1000 competitors, a Jedi Knight will be replaced approximately 6.49 times.
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:2007 U.Nacional - Circuito de Maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3390. Tribe Council

      Problem code: TRIBE2

      The Kazooba tribe contains N men, who want to gather for a tribe council. The men are all descendants of a single one, who is the chief of the tribe. Since the people of this tribe are quite long lived, every person's ancestors, including the chief, are alive and will be attending the council.

      The men arrive at the council in some particular order and they are seated as they arrive. The men sit in a row of parallel tables. The first table is at the base of the Holy Mountain and the row extends indefinitely to the West (away from the Mountain). Unfortunately, each man doesn't get along with his father and his sons, so he doesn't want to sit at the same table with any of them. On the other hand, each man wants to be as close to divinity as possible, so, when he arrives at the council, he goes to the table closest to the Holy Mountain, where none of his children or father is already seated.

      As usual, the Gods of the tribe have a certain inclination for grandeur. Therefore, they would like to command the men to arrive in such an order, as to maximize the number of tables that are occupied. Unfortunately, they do not have any inclination for programming, so they have ordered you to write a program for that.

      Write a program that determines the maximum number of tables that can end up being occupied.

      Input

      The first line of the input file contains an integer N, representing the number of men in the tribe. All men are numbered from 1 to N; the chief is number 1. Each of the following lines describe a father–son relation and contains two integers A B separated by a blank, meaning that person number A is the father of the person number B. The relations described in the file are correct (for instance, there are no "cycles" and each person is a descendent of the chief).

      Output

      The output file should contain a single line with the maximum number of tables that can be occupied.

      Example

      Input:
      5
      1 4
      3 2
      1 3
      3 5
      
      Output:
      3
      
      
      Explanation: 
      If men arrive in the order 2 4 1 5 3, the following happens:
      
      • 2 goes to the first table
      • 4 goes to the first table
      • 1 has a son (4) at the first table, so he goes to the second table
      • 5 goes to the first table
      • 3 has two sons at the first table (2 and 5) and his father (1) is at the second table, so he goes to the third table

      Constraints

      • 1 < N <= 100 000
      • Any table has unlimited capacity.
      Note: The problem statement and test data was updated on 22-11-2008. I'm sorry for the inconvenience.
      Added by:Ajay Somani
      Date:2008-11-19
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:BOI 2003









      SPOJ Problem Set (classical)

      3393. Knot or Not

      Problem code: NOTOKNOT

      Disentangling of string loops is a classical 3D- puzzle. A designer of one of these puzzles wants to know if two given string loops can be disentangled or not.

      The designer says that a string loop configuration that can be disentangled is a Notknot. In fact, he says that knots are those string loops that can not be disentangled.

      Your task is to write a program to help the puzzle designer deciding if some configurations can or cannot be disentangled. In the problems that you are going to solve, loops are defined by straight segments in the space between points with integer coordinates. Then, a loop is described with a list of p points with integral coordinates for some p ≥ 3.

      Input

      Input consists of N test cases (1 ≤ N ≤ 1000). The number N is given in the first line of the input.

      Each test case contains the description of two loops, each one in a line. A description for a p points loop (3 ≤ p ≤ 20) is given in one input line with 3p integer numbers separated by blanks:

      x1 y1 z1 x2 y2 z2 . . . xp yp zp


      what represents the loop:

      (x1 , y1 , z1 ) − (x2 , y2 , z2 ) − · · · − (xp , yp , zp ) − (x1 , y1 , z1 )


      where there is a straight segment between adjacent coordinates.

      Output

      For each analyzed case, one line classifying the case: Notknot or Knot.

      Example

      Input:
      3
      10 0 0 0 0 -10 0 10 0 0 0 10
      5 0 0 -10 -10 0 0 5 0 10 10 0
      10 0 0 0 0 -10 0 10 0 0 0 10
      15 0 0 -10 -10 0 0 5 0 10 10 0
      1 0 0 0 1 0 0 0 1
      10 10 0 0 10 0 0 0 10 10 0 0 25 5 0 3 3 0
      
      
      Output:
      Notknot
      Knot
      Notknot
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-19
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:2008 U.Catolica & U.Central - Circuito de maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3394. Lagrange’s Four-Square Theorem

      Problem code: LAGRANGE

      The fact that any positive integer has a representation as the sum of at most four positive squares (i.e. squares of positive integers) is known as Lagrange's Four-Square Theorem. The first published proof of the theorem was given by Joseph-Louis Lagrange in 1770. Your mission however is not to explain the original proof nor to discover a new proof but to show that the theorem holds for some specific numbers by counting how many such possible representations there are. For a given positive integer n, you should report the number of all representations of n as the sum of at most four positive squares. The order of addition does not matter, e.g. you should consider 4^2 + 3^2 and 3^2 + 4^2 are the same representation.

      For example, let's check the case of 25. This integer has just three representations 1^2+2^2+2^2+4^2, 3^2 + 4^2, and 5^2. Thus you should report 3 in this case. Be careful not to count 4^2 + 3^2 and 3^2 + 4^2 separately.

      Input

      The input is composed of at most 255 lines, each containing a single positive integer less than 2^15 , followed by a line containing a single zero. The last line is not a part of the input data.

      Output

      The output should be composed of lines, each containing a single integer. No other characters should appear in the output. The output integer corresponding to the input integer n is the number of all representations of n as the sum of at most four positive squares.

      Example

      Input:
      1
      25
      2003
      211
      20007
      0
      
      Output:
      1
      3
      48
      7
      738
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-19
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:2008 U.Catolica & U.Central - Circuito de maratones ACIS / REDIS









      SPOJ Problem Set (classical)

      3405. Almost Shortest Path

      Problem code: SAMER08A

      Finding the shortest path that goes from a starting point to a destination point given a set of points and route lengths connecting them is an already well known problem, and it's even part of our daily lives, as shortest path programs are widely available nowadays.

      Most people usually like very much these applications as they make their lives easier. Well, maybe not that much easier.

      Now that almost everyone can have access to GPS navigation devices able to calculate shortest paths, most routes that form the shortest path are getting slower because of heavy traffic. As most people try to follow the same path, it's not worth it anymore to follow these directions.

      With this in his mind, your boss asks you to develop a new application that only he will have access to, thus saving him time whenever he has a meeting or any urgent event. He asks you that the program must answer not the shortest path, but the almost shortest path. He defines the almost shortest path as the shortest path that goes from a starting point to a destination point such that no route between two consecutive points belongs to any shortest path from the starting point to the destination.

      For example, suppose the figure below represents the map given, with circles representing location points, and lines representing direct, one-way routes with lengths indicated. The starting point is marked as S and the destination point is marked as D. The bold lines belong to a shortest path (in this case there are two shortest paths, each with total length 4). Thus, the almost shortest path would be the one indicated by dashed lines (total length 5), as no route between two consecutive points belongs to any shortest path. Notice that there could exist more than one possible answer, for instance if the route with length 3 had length 1. There could exist no possible answer as well.

      subir imagenes

      Input

      The input contains several test cases. The first line of a test case contains two integers N (2 ≤ N ≤ 500) and M (1 ≤ M ≤ 104), separated by a single space, indicating respectively the number of points in the map and the number of existing one-way routes connecting two points directly. Each point is identified by an integer between 0 and N -1. The second line contains two integers S and D, separated by a single space, indicating respectively the starting and the destination points (SD; 0 ≤ S, D < N).

      Each one of the following M lines contains three integers U, V and P (UV; 0 ≤ U, V < N; 1 ≤ P ≤ 103), separated by single spaces, indicating the existence of a one-way route from U to V with distance P. There is at most one route from a given point U to a given point V, but notice that the existence of a route from U to V does not imply there is a route from V to U, and, if such road exists, it can have a different length. The end of input is indicated by a line containing only two zeros separated by a single space.

      Output

      For each test case in the input, your program must print a single line, containing -1 if it is not possible to match the requirements, or an integer representing the length of the almost shortest path found.

      Example

      Input:
      7 9
      0 6
      0 1 1
      0 2 1
      0 3 2
      0 4 3
      1 5 2
      2 6 4
      3 6 2
      4 6 4
      5 6 1
      4 6
      0 2
      0 1 1
      1 2 1
      1 3 1
      3 2 1
      2 0 3
      3 0 2
      6 8
      0 1
      0 1 1
      0 2 2
      0 3 3
      2 5 3
      3 4 2
      4 1 1
      5 1 1
      3 0 1
      0 0
      
      
      Output:
      5
      -1
      6
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (classical)

      3406. Bases

      Problem code: SAMER08B

      What do you get if you multiply 6 by 9? The answer, of course, is 42, but only if you do the calculations in base 13.

      Given an integer B ≥ 2, the base B numbering system is a manner of writing integers using only digits between 0 and B -1, inclusive. In a number written in base B, the rightmost digit has its value multiplied by 1, the second rightmost digit has its value multiplied by B, the third rightmost digit has its value multiplied by B2, and so on.

      Some equations are true or false depending on the base they are considered in. The equation 2+2=4, for instance, is true for any B ≥ 5 - it does not hold in base 4, for instance, since there is no digit '4' in base 4. On the other hand, an equation like 2+2=5 is never true.

      Write a program that given an equation determines for which bases it holds.

      Input

      Each line of the input contains a test case; each test case is an equation of the form "EXPR=EXPR", where both "EXPR" are arithmetic expressions with at most 17 characters.

      All expressions are valid, and contain only the characters '+', '*' and the digits from '0' to '9'. No expressions contain leading plus signs, and no numbers in it have leading zeros.

      The end of input is indicated by a line containing only "=".

      Output

      For each test case in the input your program should produce a single line in the output, indicating for which bases the given equation holds.

      If the expression is true for infinitely many bases, print "B+", where B is the first base for which the equation holds.

      If the expression is valid only for a finite set of bases, print them in ascending order, separated by single spaces.

      If the expression is not true in any base, print the character '*'.

      Example

      Input:
      6*9=42
      10000+3*5*334=3*5000+10+0
      2+2=3
      2+2=4
      0*0=0
      =
      
      
      Output:
      13
      6 10
      *
      5+
      2+
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (classical)

      3407. Candy

      Problem code: SAMER08C

      Little Charlie is a nice boy addicted to candies. He is even a subscriber to All Candies Magazine and was selected to participate in the International Candy Picking Contest.

      In this contest a random number of boxes containing candies are disposed in M rows with N columns each (so, there are a total of M ×N boxes). Each box has a number indicating how many candies it contains.

      The contestant can pick a box (any one) and get all the candies it contains. But there is a catch (there is always a catch): when choosing a box, all the boxes from the rows immediately above and immediately below are emptied, as well as the box to the left and the box to the right of the chosen box. The contestant continues to pick a box until there are no candies left.

      The figure bellow illustrates this, step by step. Each cell represents one box and the number of candies it contains. At each step, the chosen box is circled and the shaded cells represent the boxes that will be emptied. After eight steps the game is over and Charlie picked 10+9+8+3+7+6+10+1 = 54 candies.

      subir imagenes



      For small values of M and N, Charlie can easily find the maximum number of candies he can pick, but when the numbers are really large he gets completely lost. Can you help Charlie maximize the number of candies he can pick?

      Input

      The input contains several test cases. The first line of a test case contains two positive integers M and N (1 ≤ M ×N ≤ 105), separated by a single space, indicating the number of rows and columns respectively. Each of the following M lines contains N integers separated by single spaces, each representing the initial number of candies in the corresponding box. Each box will have initially at least 1 and at most 103 candies.

      The end of input is indicated by a line containing two zeroes separated by a single space.

      Output

      For each test case in the input, your program must print a single line, containing a single value, the integer indicating the maximum number of candies that Charlie can pick.

      Example

      Input:
      
      5 5
      1 8 2 1 9
      1 7 3 5 2
      1 2 10 3 10
      8 4 7 9 1
      7 1 3 1 6
      4 4
      10 1 1 10
      1 1 1 1
      1 1 1 1
      10 1 1 10
      2 4
      9 10 2 7
      5 1 1 5
      0 0
      
      Output:
      54
      40
      17
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (classical)

      3408. DNA Sequences

      Problem code: SAMER08D

      Thomas, a computer scientist that works with DNA sequences, needs to compute longest common subsequences of given pairs of strings. Consider an alphabet Σ of letters and a word w=a1a2ar, where ai ∈ Σ, for i = 1, 2, …,r. A subsequence of w is a word x=ai1ai2ais such that 1 ≤ i1 < i2 < … < isr. Subsequence x is a segment of w if ij+1=ij + 1, for j = 1,2, …,s -1. For example the word ove is a segment of the word lovely, whereas the word loly is a subsequence of lovely, but not a segment.

      A word is a common subsequence of two words w1 and w2 if it is a subsequence of each of the two words. A longest common subsequence of w1 and w2 is a common subsequence of w1 and w2 having the largest possible length. For example, consider the words w1=lovxxelyxxxxx and w2=xxxxxxxlovely. The words w3=lovely and w4=xxxxxxx, the latter of length 7, are both common subsequences of w1 and w2. In fact, w4 is their longest common subsequence. Notice that the empty word, of length zero, is always a common subsequence, although not necessarily the longest.

      In the case of Thomas, there is an extra requirement: the subsequence must be formed from common segments having length K or more. For example, if Thomas decides that K=3, then he considers lovely to be an acceptable common subsequence of lovxxelyxxxxx and xxxxxxxlovely, whereas xxxxxxx, which has length 7 and is also a common subsequence, is not acceptable. Can you help Thomas?

      Input

      The input contains several test cases. The first line of a test case contains an integer K representing the minimum length of common segments, where 1 ≤ K ≤ 100. The next two lines contain each a string on lowercase letters from the regular alphabet of 26 letters. The length l of each string satisfies the inequality 1 ≤ l ≤ 103. There are no spaces on any line in the input. The end of the input is indicated by a line containing a zero.

       

      Output

      For each test case in the input, your program must print a single line, containing the length of the longest subsequence formed by consecutive segments of length at least K from both strings. If no such common subsequence of length greater than zero exists, then 0 must be printed.

      Example

      Input:
      3
      lovxxelyxxxxx
      xxxxxxxlovely
      1
      lovxxelyxxxxx
      xxxxxxxlovely
      3
      lovxxxelxyxxxx
      xxxlovelyxxxxxxx
      4
      lovxxxelyxxx
      xxxxxxlovely
      0
      
      
      Output:
      6
      7
      10
      0
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (classical)

      3409. Electricity

      Problem code: SAMER08E

      Martin and Isa stopped playing crazy games and finally got married. It's good news! They're pursuing a new life of happiness for both and, moreover, they're moving to a new house in a remote place, bought with most of their savings.

      Life is different in this new place. In particular, electricity is very expensive, and they want to keep everything under control. That's why Martin proposed to keep a daily record of how much electricity has been consumed in the house. They have an electricity meter, which displays a number with the amount of KWh (kilowatt-hour) that has been consumed since their arrival.

      At the beginning of each day they consult the electricity meter, and write down the consumption. Some days Martin does it, and some days Isa does. That way, they will be able to look at the differences of consumption between consecutive days and know how much has been consumed.

      But some days they simply forget to do it, so, after a long time, their register is now incomplete. They have a list of dates and consumptions, but not all of the dates are consecutive. They want to take into account only the days for which the consumption can be precisely determined, and they need help.

      Input

      The input contains several test cases. The first line of each test case contains one integer N indicating the number of measures that have been taken (2 ≤ N ≤ 103). Each of the N following lines contains four integers D, M, Y and C, separated by single spaces, indicating respectively the day (1 ≤ D ≤ 31), month (1 ≤ M ≤ 12), year (1900 ≤ Y ≤ 2100), and consumption (0 ≤ C ≤ 106) read at the beginning of that day. These N lines are increasingly ordered by date, and may include leap years. The sequence of consumptions is strictly increasing (this is, no two different readings have the same number). You may assume that D, M and Y represent a valid date.

      Remember that a year is a leap year if it is divisible by 4 and not by 100, or well, if the year is divisible by 400.

      The end of input is indicated by a line containing only one zero.

      Output

      For each test case in the input, your program must print a single line containing two integers separated by a single space: the number of days for which a consumption can be precisely determined, and the sum of the consumptions for those days.

      Example

      Input:
      5
      9 9 1979 440
      29 10 1979 458
      30 10 1979 470
      1 11 1979 480
      2 11 1979 483
      3
      5 5 2000 6780
      6 5 2001 7795
      7 5 2002 8201
      8
      28 2 1978 112
      1 3 1978 113
      28 2 1980 220
      1 3 1980 221
      5 11 1980 500
      14 11 2008 600
      15 11 2008 790
      16 12 2008 810
      0
      
      
      Output:
      2 15
      0 0
      2 191
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (main)

      3410. Feynman

      Problem code: SAMER08F

      Richard Phillips Feynman was a well known American physicist and a recipient of the Nobel Prize in Physics. He worked in theoretical physics and also pioneered the field of quantum computing. He visited South America for ten months, giving lectures and enjoying life in the tropics. He is also known for his books "Surely You're Joking, Mr. Feynman!" and "What Do You Care What Other People Think?", which include some of his adventures below the equator.

      His life-long addiction was solving and making puzzles, locks, and cyphers. Recently, an old farmer in South America, who was a host to the young physicist in 1949, found some papers and notes that is believed to have belonged to Feynman. Among notes about mesons and electromagnetism, there was a napkin where he wrote a simple puzzle: "how many different squares are there in a grid of N ×N squares?".

      In the same napkin there was a drawing which is reproduced below, showing that, for N=2, the answer is 5.

      subir imagenes

      Input

      The input contains several test cases. Each test case is composed of a single line, containing only one integer N, representing the number of squares in each side of the grid (1 ≤ N ≤ 100).

      The end of input is indicated by a line containing only one zero.

      Output

      For each test case in the input, your program must print a single line, containing the number of different squares for the corresponding input.

      Example

      Input:
      2
      1
      8
      0
      
      
      Output:
      5
      1
      204
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc TECS
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (classical)

      3411. Pole Position

      Problem code: SAMER08G

      In car races, there is always a high pole next to the finish line of the track. Before the race starts, the pole is used to display the starting grid. The number of the first car in the grid is displayed at the top of the pole, the number of the car in second place is shown below that, and so on.

      During the race, the pole is used to display the current position of each car: the car that is winning the race has its number displayed at the top of the pole, followed by the car that is in second place, and so on.

      Besides showing the current position of a car, the pole is also used to display the number of positions the cars have won or lost, relative to the starting grid. This is done by showing, side by side to the car number, an integer number. A positive value v beside a car number in the pole means that car has won v positions relative to the starting grid. A negative value v means that car has lost v positions relative to the starting grid. A zero beside a car number in the pole means the car has neither won nor lost any positions relative to the starting grid (the car is in the same position it started).

       

      subir imagenes

       

      We are in the middle of the Swedish Grand Prix, the last race of the World Championship. The race director, Dr. Shoo Makra, is getting worried: there have been some complaints that the software that controls the pole position system is defective, showing information that does not reflect the true race order.

      Dr. Shoo Makra devised a way to check whether the pole system is working properly. Given the information currently displayed in the pole, he wants to reconstruct the starting grid of the race. If it is possible to reconstruct a valid starting grid, he plans to check it against the real starting grid. On the other hand, if it is not possible to reconstruct a valid starting grid, the pole system is indeed defective.

      Can you help Dr. Shoo Makra?

      Input

      The input contains several test cases. The first line of a test case contains one integer N indicating the number of cars in the race (2 ≤ N ≤ 103). Each of the next N lines contains two integers C and P, separated by one space, representing respectively a car number (1 ≤ C ≤ 104) and the number of positions that car has won or lost relative to the starting grid ( -106P ≤ 106), according to the pole system. All cars in a race have different numbers.

      The end of input is indicated by a line containing only one zero.

      Output

      For each test case in the input, your program must print a single line, containing the reconstructed starting grid, with car numbers separated by single spaces. If it is not possible to reconstruct a valid starting grid, the line must contain only the value -1.

      Example

      Input:
      4
      1 0
      3 1
      2 -1
      4 0
      4
      22 1
      9 1
      13 0
      21 -2
      3
      19 1
      9 -345
      17 0
      7
      2 2
      8 0
      5 -2
      7 1
      1 1
      9 1
      3 -3
      0
      
      
      Output:
      1 2 3 4
      -1
      -1
      5 8 2 3 7 1 9
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (classical)

      3412. Higgs Boson

      Problem code: SAMER08H


      It's been 100 years since the detection of the first Higgs boson and now particle physics is a mainstream subject in all high schools. Obviously, kids love the fact that they can create tiny black holes using only their portable particle accelerators and show off to their friends and colleagues. Although the creation of big black holes that could swallow the whole planet is possible even with these portable particle accelerators, the devices are programmed to only thrown particles when this undesirable side effect is impossible.

      Your granddaughter is trying to create her own black holes with a portable accelerator kit, which is composed of two small particle accelerators that throw, each one, a boson-sized particle. Both particles are thrown at the same time, and a black hole appears when the particles collide. However, your granddaughter doesn't know how much time she'll have to wait before this happens. Fortunately, each accelerator can predict the particle's trajectory, showing four integer values into its display, called A, B, C and D. Each value can be replaced into the following equations:

       
      r = At + B
      θ = Ct + D
       

      in order to determine the trajectory of the particle, in polar coordinates. The radius (r) is represented in distance units and the angle (θ) in degrees. The time (t) is given in time units and it is always a rational value which can be represented by an irreducible fraction. Your granddaughter knows that in polar coordinates a point has infinite representations. In general, the point (r, θ) can be represented as (r, θ ±k ×360o) or ( -r, θ ±(2k + 1) ×180o), where k is any integer. Besides, the origin (r = 0) can be represented as (0, θ) for any θ.

      Using these parameters informed by each particle accelerator, your granddaughter wants to determine whether the particles will eventually collide and, if they do, the time when they will collide. After the first collision it is impossible to predict the particle's trajectory, therefore, only the first possible collision should be considered.

      Although your granddaughter is really intelligent and has a deep knowledge of particle physics, she does not know how to program computers and is looking for some notes in her grandfather's (or grandmother's) ICPC notebook (don't forget, she is your granddaughter!). Fortunately for you, there is a note on your notebook which says that you wrote that code during the 2008 ICPC South America Regional Contest (or, to be more specific, this contest).

      Input

      The input consists of several test cases, one per line. Each test case contains eight integer numbers separated by single spaces, A1, B1,C1, D1, A2, B2, C2, D2 ( -104A1, B1, C1, D1, A2,B2, C2, D2 ≤ 104). The first four input values (A1, B1,C1, D1) correspond to the four parameters displayed by the first portable particle accelerator and the following input values (A2,B2, C2, D2) correspond to the four parameters displayed by the second portable particle accelerator when both particles are thrown. The end of the input is represented by A1 = B1 = C1 = D1 = A2 = B2 = C2 = D2 = 0, which should not be processed as a test case, since these are the values displayed by the particle accelerators when a big black hole would be created if the particles were trown. Although the end of input is represented by a line with eight zeroes, note that the number zero is a possible input value.

      Output

      For each test case, your program must output a line containing two non-negative integers ta and tb separated by a single space. If there is no possibility of collision, ta = tb = 0, otherwise, ta/tb must be an irreducible fraction representing the earliest collision time. Even if the fraction results in an integer value, you still must output the number 1 as the denominator (see samples below).

      Example

      Input:
      1 1 180 0 2 0 180 360
      10 10 360 0 -24 18 180 72
      5 5 180 0 -12 9 10 40
      -9 5 5 180 2 5 5 180
      0 0 0 0 0 0 0 0
      
      
      Output:
      1 1
      0 0
      4 17
      0 1
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:DOC AWK C C# C++ 4.3.2 C++ 4.0.0-8 CLOJ F# GO JAVA NODEJS PAS fpc PAS gpc PDF PERL 6 PS PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TEXT
      Resource:South American Regional Contests 2008









      SPOJ Problem Set ()

      3413. Traveling Shoemaker Problem

      Problem code: SAMER08I

      Once upon a time there was a very peaceful country named Nlogonia. Back then, Poly the Shoemaker could come to the country and travel freely from city to city doing his job without any harassment. This task was very easy, as every city in Nlogonia had a direct road to every other city in the country. He could then easily travel the whole country visiting each city exactly once and fixing everybody's shoes.

      But not anymore. The times have changed and war has come to Nlogonia. The age when people could travel freely is over.

      Confederations identified by colors were formed among the cities all over the country, and now each city belongs to at least one and at most two confederations. When trying to enter a city, you must give to the border officer a ticket from one of the confederations this city belongs to. When leaving the city, you receive a ticket from the other confederation the city belongs to (i.e. different from the one you gave when entering) or from the same confederation if the city only belongs to one.

      As Poly the Shoemaker is a long time friend of Nlogonia, he is allowed to choose a ticket and a city he wants to enter as the first city in the country, but after that he must obey the confederations rules. He wants to do the same routine he did before, visiting each city exactly once in Nlogonia, but now it's not easy for him to do this, even though he can choose where to start his journey.

      For example, suppose there are four cities, labeled from 0 to 3. City 0 belongs to confederations red and green; city 1 belongs only to red; city 2 belongs to green and yellow; and city 3 belongs to blue and red. If Poly the Shoemaker chooses to start at city 0, he can enter it carrying either the red or the green ticket and leave receiving the other. Should he choose the red ticket, he will leave with a green ticket, and then there is only city 2 he can travel to. When leaving city 2 he receives the yellow ticket and now can't go anywhere else. If he had chosen the green ticket as the first he would receive the red one when leaving, and then he could travel to cities 1 or 3. If he chooses city 3, when leaving he will receive the blue ticket and again can't go anywhere else. If he chooses city 1, he receives the red ticket again when leaving (city 1 belongs only to the red confederation) and can only travel to city 3 and will never get to city 2. Thus, it is not possible to visit each city exactly once starting at city 0. It is possible, however, starting at city 2 with the yellow ticket, leaving the city with the green ticket, then visiting city 0, leaving with red ticket, then visiting city 1, leaving with red ticket again and, at last, visiting city 3.

      As you can see, it got really difficult for Poly the Shoemaker to accomplish the task, so he asks you to help him. He wants to know if it's possible to choose a city to start such that he can travel all cities from Nlogonia exactly once.

      Can you help Poly the Shoemaker?

      Input

      The input contains several test cases. The first line of a test case contains two integers N and C, separated by one space, indicating respectively the number of cities (1 ≤ N ≤ 500) and confederations (1 ≤ C ≤ 100) in the country. Each of the next C lines describes a confederation. It starts with one integer K (0 ≤ KN) and then K integers representing the cities which belong to this confederation. All integers are separated by single spaces and cities are numbered from 0 to N -1. Each city will appear at least once and at most twice and no city will be repeated on the same confederation.

      The end of input is indicated by a line containing two zeroes separated by a single space.

      Output

      For each test case in the input, your program must print a single line, containing the integer -1 if it's not possible to match the requirements or one integer representing the city where Poly the Shoemaker can start his journey. If there are multiple correct answers, print the smallest one.

      Example

      Input:
      4 4
      1 3
      3 0 1 3
      2 0 2
      1 2
      3 4
      1 0
      3 0 1 2
      1 1
      1 2
      3 4
      1 1
      2 1 0
      2 0 2
      1 2
      0 0
      
      
      Output:
      2
      -1
      1
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (classical)

      3414. Bora Bora

      Problem code: SAMER08J

      Bora Bora is a simple card game for children, invented in the South Pacific Island of the same name. Two or more players can play, using a deck of standard cards. Cards have the usual ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen and King. Each card has also one of four suits: Clubs, Diamonds, Hearts and Spades.

      Players sit on a circle around the table and play by turns. The next player to play may be the one to the left (clockwise direction) or to the right (counter-clockwise direction) of the current player, depending on the cards played, as we will see. At the start, the direction of play is clockwise.

      The deck is shuffled and each player is dealt a hand of cards. The remaining of the deck is placed, face down, on the table; this is called the stock pile. Then the first (topmost) card is removed from the stock and placed on the table, face up, starting another pile, called the discard pile.

      The objective of the game is for a player to discard all his cards. At each turn, a player discards at most one card. A card can be discarded only if it has the same rank or the same suit as the topmost card on the discard pile. A player discards a card by placing it, face up, in the discard pile (this card becomes the topmost). If a player does not have a suitable card to discard on his turn, he must draw one card from the stock and add it to his hand; if he can discard that card, he does so, otherwise he does nothing else and his turn ends. A player always discards the highest valued card he possibly can. The value of a card is determined first by the card rank and then by the card suit. The rank order is the rank itself (Ace is the lowest, King is the highest), and the suit order is, from lowest to highest, Clubs, Diamonds, Hearts and Spades. Therefore, the highest valued card is the King of Spades and the lowest valued card is the Ace of Clubs. As an example, a Queen of Diamonds has a higher value than a Jack (any suit) but has a lower value than a Queen of Hearts.

      Some of the discarded cards affect the play, as follows:

       

      • when a Queen is discarded, the direction of play is reversed: if the direction is clockwise, it changes to counter-clockwise, and vice-versa;

      • when a Seven is discarded, the next player to play must draw two cards from the stock (the number of cards in his hand increases by two), and misses his turn (does not discard any card);

      • when an Ace is discarded, the next player to play must draw one card from the stock (the number of cards in his hand increases by one), and misses his turn (does not discard any card);

      • when a Jack is discarded, the next player to play misses his turn (does not discard any card).

      Notice that the penalty for the first card in the discard pile (the card draw from the stock at the beginning) is applied to the first player to play. For example, if the first player to play is p and the first card on the discard pile is an Ace, player p draws a card from the stock and does not discard any card on his first turn. Also notice that if the first card is a Queen, the direction of play is reversed to counter-clockwise, but the first player to play remains the same.

      The winner is the player who first discards all his cards (the game ends after the winner discards his last card).

      Given the description of the shuffled deck and the number of players, write a program to determine who will win the game.

      Input

      The input contains several test cases. The first line of a test case contains three integers P, M and N, separated by single spaces, indicating respectively the number of players (2 ≤ P ≤ 10), the number of cards distributed to each of the players at the beginning of the game (1 ≤ M ≤ 11) and the total number of cards in the shuffled deck (3 ≤ N ≤ 300). Each of the next N lines contains the description of one card. A card is described by one integer X and one character S, separated by one space, representing respectively the card rank and the card suite. Card ranks are mapped to integers from 1 to 13 (Ace is 1, Jack is 11, Queen is 12 and King is 13). Card suits are designated by the suit's first letter: 'C' (Clubs), 'D' (Diamonds), 'H' (Hearts) or 'S' (Spades).

      Players are identified by numbers from 1 to P, and sit on a circle, in clockwise direction, 1, 2 …P, 1. The first P×M cards of the deck are dealt to the players: the first M cards to the first player (player 1), the next M to the second player (player 2), and so on. After dealing the cards to the players, the next card on the deck - the (P ×M + 1)-th card - is used to start the discard pile, and the remaining cards form the stock. The (P ×M + 2)-th card to appear on the input is the topmost card on the stock, and the last card to appear on the input (the N-th card) is the bottommost card of the stock (the last card that can be drawn). Player 1 is always the first to play (even when the card used to start the discard pile is a Queen). All test cases have one winner, and in all test cases the number of cards in the deck is sufficient for playing to the end of the game.

      The end of input is indicated by a line containing only three zeros, separated by single spaces.

      Output

      For each test case in the input, your program must print a single line, containing the number of the player who wins the game.

      Example

      Input:
      2 2 10
      1 D
      7 D
      1 S
      3 C
      13 D
      1 S
      5 H
      12 D
      7 S
      2 C
      3 2 11
      1 S
      7 D
      11 D
      3 D
      7 D
      3 S
      11 C
      8 C
      9 H
      6 H
      9 S
      3 3 16
      1 H
      10 C
      13 D
      7 C
      10 H
      2 S
      2 C
      10 S
      8 S
      12 H
      11 C
      1 C
      1 C
      4 S
      5 D
      6 S
      0 0 0
      
      
      Output:
      1
      3
      2
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (classical)

      3415. Shrinking Polygons

      Problem code: SAMER08K

      A polygon is said to be inscribed in a circle when all its vertices lie on that circle. In this problem you will be given a polygon inscribed in a circle, and you must determine the minimum number of vertices that should be removed to transform the given polygon into a regular polygon, i.e., a polygon that is equiangular (all angles are congruent) and equilateral (all edges have the same length).

      When you remove a vertex v from a polygon you first remove the vertex and the edges connecting it to its adjacent vertices w1 and w2, and then create a new edge connecting w1 and w2. Figure (a) below illustrates a polygon inscribed in a circle, with ten vertices, and figure (b) shows a pentagon (regular polygon with five edges) formed by removing five vertices from the polygon in (a).

      subir imagenes

       

      In this problem, we consider that any polygon must have at least three edges.

      Input

      The input contains several test cases. The first line of a test case contains one integer N indicating the number of vertices of the inscribed polygon (3 ≤ N ≤ 104). The second line contains N integers Xi separated by single spaces (1 ≤ Xi ≤ 103, for 0 ≤ iN -1). Each Xi represents the length of the arc defined in the inscribing circle, clockwise, by vertex i and vertex (i+1) mod N. Remember that an arc is a segment of the circumference of a circle; do not mistake it for a chord, which is a line segment whose endpoints both lie on a circle.

      The end of input is indicated by a line containing only one zero.

      Output

      For each test case in the input, your program must print a single line, containing the minimum number of vertices that must be removed from the given polygon to form a regular polygon. If it is not possible to form a regular polygon, the line must contain only the value -1.

      Example

      Input:
      3
      1000 1000 1000
      6
      1 2 3 1 2 3
      3
      1 1 2
      10
      10 40 20 30 30 10 10 50 24 26
      0
      
      
      Output:
      0
      2
      -1
      5
      
      

      Added by:Diego Satoba
      Date:2008-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:South American Regional Contests 2008









      SPOJ Problem Set (classical)

      3420. Falling Ice

      Problem code: FALLINGI


      Imagine disks of ice falling, one at a time, into a box, each ending up at the lowest point it can reach without overlapping or moving previous disks. Each disk then freezes into place, so it cannot be moved by later disks. Your job is to find the overall height of the final combination of disks.

      So that the answer is unique, assume that any disk reaching the bottom of the box rolls as far to the left as possible. Also the data is chosen so there will be a unique lowest position for any disk that does not reach the bottom. The data is also such that there are no "perfect fits": each disk that lands will be in contact with only two other points, on previous circles or the sides of the box. The illustrations above show white filled disks labeled with the order in which they fall into their boxes. The gray circle in the fourth illustration is not intended to be a disk that fell in. The gray disk is included to demonstrate a point: the gray disk is the same size as disk 2, so there is space for disk 2 on the very bottom of its box, but disk 2 cannot reach that position by falling from the top. It gets caught on disk 1 and the side of the box.

      One way to find the top intersection point of two intersecting circles is as follows. Suppose circle 1 has center (x1, y1) and radius r1, and suppose circle 2 has center (x2, y2), and radius r2. Also assume that circle 1 is to the left of circle 2, i.e., x1 < x2. Let

      dx = x2 - x1,
      dy = y2 - y1,
      D = sqrt(dx*dx + dy*dy),
      E = (r1*r1 - r2*r2 + D*D)/(2*D),
      F = sqrt(r1*r1 - E*E);

      then the upper intersection point is (x1 + (E*dx - F*dy)/D, y1 + (F*dx + E*dy)/D).


      subir imagenes

      Input

      The input consists of one or more data sets, followed by a line containing only 0 that signals the end of the input. Each data set is on a line by itself and contains a sequence of three or more blank-separated positive integers, in the format w, n, d1, d2, d3, ..., dn, where w is the width of the box, n is the number of disks, and the remaining numbers are the diameters of the disks, in the order in which they fall into the box. You can assume that w < 100, that n < 10, and that each diameter is less than w.

      Output

      For each data set, output a single line containing the height of the pile of disks, rounded to two places beyond the decimal point.

      The example data matches the illustrations above.

      Example

      Input:
      10 3 5 2 3
      8 2 5 5
      11 3 10 2 4
      9 3 4 4 6
      10 6 5 4 6 3 5 2
      0 
      
      Output:
      5.00
      9.00
      12.99
      9.58
      14.19
      
      

      Added by:Nikola P Borisov
      Date:2008-11-24
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Mid-Central Regional ACM-ICPC Contest 2006









      SPOJ Problem Set (classical)

      3426. Ouroboros Snake

      Problem code: OROSNAKE


      Ouroboros is a mythical snake from ancient Egypt. It has its tail in its mouth and continously devours itself.

      The Ouroboros numbers are binary numbers of 2^n bits that have the property of "generating" the whole set of numbers from 0 to 2^n - 1. The generation works as follows: given an Ouroboros number, we place its 2^n bits wrapped in a circle. Then, we can take 2^n groups of n bits starting each time with the next bit in the circle. Such circles are called Ouroboros circles for the number n. We will work only with the smallest Ouroboros number for each n.

      Example: for n = 2, there are only four Ouroboros numbers. These are 0011;0110;1100; and 1001. In this case, the smallest one is 0011. Here is the Ouroboros circle for 0011:


      subir imagenes


      The table describes the function o(n;k) which calculates the k-th number in the Ouroboros circle of the smallest Ouroboros number of size n. This function is what your program should compute.

      Input

      The input consists of several test cases. For each test case, there will be a line containing two integers n and k (1<=n<=15; 0<=k<2^n). The end of the input file is indicated by a line containing two zeros. Don't process that line.

      Output

      For each test case, output o(n;k) on a line by itself.

      Example

      Input:
      2 0
      2 1
      2 2
      2 3
      0 0
      
      Output:
      0
      1
      3
      2
      
      

      Added by:Daniel Gómez Didier
      Date:2008-11-24
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:PUJ Internal Contest









      SPOJ Problem Set (classical)

      3436. Histogram

      Problem code: HIST2


      In statistics, a histogram is a graphical display of tabulated frequencies, shown as bars. It shows what proportion of cases fall into each of several categories. It is a polygon composed of a sequence of rectangles aligned at a common base line. In this problem all rectangles have a width of unit length. But their heights are distinct. Some permutation of the heights will give the maximum perimeter. Your task is to find the maximum perimeter of the histogram and the number of permutations that give the maximum perimeter.

      In the image Figure (a) shows a histogram with heights {1,2,3,4} (1st sample testcase) and has a perimeter of 16 units. Figure (b) shows one of the permutations {3,1,2,4} having the maximum perimeter of 20 units.

      Input

      Input consists of multiple test cases. Each test case describes a histogram and starts with an integer N, 2 ≤ N ≤ 15, denoting the number of rectangles it is composed of. Next line consists of N space separated positive integers representing the heights of the rectangles. All heights are distinct and less than or equal to 100. N=0 indicates the end of tests. There are atmost 50 test cases.

      Output

      For each test case output the maximum possible perimeter of the histogram and the number of permutations that give maximum perimeter in a single line, separated by a single space.

      Example

      Input:
      4
      1 2 3 4
      3
      2 6 5
      0
      
      Output:
      20 8
      24 2
      
      

      Added by:Swarnaprakash
      Date:2008-11-29
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Kurukshetra 09 OPC









      SPOJ Problem Set (main)

      3442. The last digit

      Problem code: LASTDIG

      Nestor was doing the work of his math class about three days but he is tired of make operations a lot and he should deliver his task tomorrow. His math’s teacher gives two numbers a and b. The problem consist in find the last digit of the potency of base a and index b. Help Nestor with his problem. You are given two integer numbers: the base a (0 <= a <= 20) and the index b (0 <= b <= 2,147,483,000), a and b both are not 0. You have to find the last digit of a^b.

      Input

      The first line of input contains an integer t, the number of test cases (t <= 30). t test cases follow. For each test case will appear a and b separated by space.

      Output

      For each test case output an integer per line representing the result.

      Example

      Input:
      2
      3 10
      6 2

      Output: 9 6

      Added by:Jose Daniel Rodríguez Morales
      Date:2008-12-01
      Time limit:1s
      Source limit:700B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own









      SPOJ Problem Set (classical)

      3459. SkyScrapers

      Problem code: CEPC08B

      In a seaside village, there is an avenue of skyscrapers. Each skyscrapers is 100m wide and has certain height. Due to very high price of parcels, any two consecutive skyscrapers are adjacent. The avenue lies close to the beach so the street is exactly at the sea level. Unfortunately, this year, due to the global warming, the sea level started to increase by one meter each day. If the skyscraper height is no greater than the current sea level, it is considered flooded. A region is a maximal set of non-flooded, adjacent skyscrapers. This term is of particular importance, as it is sufficient to deliver goods (like current, carrots or cabbages) to any single skyscraper in each region. Hence, the city major wants to know how many regions there will be in the hard days that come. An example of an avenue with 5 skyscrapers after 2 days is given below.

      Input

      The input contains several test cases. The first line contains an integer t (t ≤ 15) denoting the number
      of test cases. Then t test cases follow. Each of them begins with a line containing two numbers n and
      d (1 ≤ n, d ≤ 106), n is the number of skyscrapers and d is the number of days which the major wants
      to query. Skyscrapers are numbered from left to right. The next line contains n integers h1, h2, . . . , hn
      where 1 ≤ hi ≤ 109 is the height of skyscraper i. The third line of a single test case contains d numbers
      tj such that 0 ≤ t1 < t2 < . . . < td−1 < td ≤ 109.

      Output

      For each test case output d numbers r1, r2, . . . , rd, where rj is the number of regions on day tj .

      Example

      Input:
      2
      3 3
      1 2 3
      1 2 3
      5 3
      1 3 5 1 3
      0 2 4
      
      
      Output:
      1 1 0
      1 2 1
      

      Added by:Robert Rychcicki
      Date:2008-12-06
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Central European Regional Contest 2008









      SPOJ Problem Set (classical)

      3461. Song Contest

      Problem code: SONG


      Every year, the continent of Cacophonea organises the Cacophonean Song Contest, for which each of its nations presents an act by a national singer or group. Each Cacophonean inhabitant may televote for any act which is not from his nation, so a nation can never vote for its own act. In the end, each of the s Cacophonean nations will award points to r acts. The act which received most votes from a certain nation will get r points from this nation, the act with the second largest amount of votes will get r - 1 points, etc., so the act with the rth largest amount of votes gets 1 point and less popular acts get no points from the voting nation. The final ranking of the song contest will then be decided by the total amount of points each nation received.

      Music producer Dustin has been eagerly following the Cacophonean Song Contest for many years. Lately, he has observed that in certain nations, televotes are politically rather than artistically motivated:

      (1) Politically voting nations prefer acts from neighbouring nations. More specifically, the Euclidean distance between their capital and another nation's capital is their popularity measure, irregardless of the artistic quality of the corresponding act. Hence, the nation with the closest capital will get most votes and the nation with the farthest capital will receive the least votes, which could yield no points at all if r < s - 1. It will never occur that two or more capitals will have the same distance to a certain capital.

      (2) Nations that vote quality-motivated will, as the name suggests, award points to nations according to an indisputable act ranking based on each act's artistic quality. In this ranking, there will be no ties so each nation has its own unique rank.

      However, Dustin has heard he can influence the voting behaviour of other nations: an artist can find favour of politically voting nations by giving them special attention during his act (e.g. by singing parts in their local dialects, waving their flags, etcetera). The more a politically voting nation will receive such attention in an act, the higher it will rank it. Of course this will be at the cost of the original act and might result in terribly campy results. Therefore, nations that vote according to artistic quality will punish such behaviour.

      More specifically, Dustin can divide an act into exactly s - 1 parts. Originally, all parts are dedicated to the nation of the performer (i.e. they reflect his original artistic ideas), but this can be changed:

      (1) For each part in the act that will be dedicated to a certain politically voting nation, that nation will rank the performer's nation one place higher (unless the performer's nation is already ranked first). As each nation has a unique ranking position, the nation that originally was at that higher rank will then be ranked one place lower.

      (2) Quality-motivated voting nations do not like these soft-soaping attempts at all. Therefore, for each part in the act that will be dedicated to a nation which is not the original performer's nation, quality-motivated nations will rank the original performer's nation one place lower (unless the performer's nation is already ranked lowest).

      Only the fact that a certain amount of parts is dedicated to a certain nation will influence voting behaviour: the exact part dedication sequence in the total act is not of interest here.

      Dustin wants to use this knowledge (which no other Cacophonean producer has) to produce a smashing act, yielding as much points in the overall results as possible. You are asked to determine what the largest possible overall point score is he can obtain for an act, when he optimally exploits the described act-changing practices.

      Input

      The first line of input consists of the integer number n, the number of test cases;

      Then, for each test case:

      A line with an integer number s (1 < s <= 100), indicating the number of participating nations in the song contest;

      Then, for each nation:

      (1) A line containing:

      (1.1) A string c (not containing any spaces) with the nation's name, followed by a space. Within a test case, there will not be multiple nations sharing the same name;

      (1.2) A character indicating the nation's voting behaviour: q if the voting behaviour is quality-motivated and p if the behaviour is politically motivated.

      (2) A line containing:

      (2.1) The location of the nation's capital, expressed in an (x, y) integer coordinate (-10000 <= x <= 10000, -10000 <= y <= 10000). x and y are separated by a space. Furthermore, y is followed by a space;

      (2.2) The actual artistic quality rank q of the nation's act. This is a unique number in the range 1...s.

      After description of each nation:

      A line with an integer number r (0 < r <= s - 1), indicating to how many nations each nation will attribute points;

      A line with the name of the nation for which Dustin should produce a song, achieving as much points as possible.

      Output

      For each test case, the output contains a single line with a single integer number: the maximal amount of points an act can obtain in the overall final score, if act-changing practices were performed in an optimal way.

      Example

      Input:
      2
      3
      Aulatrias q
      0 0 1
      Binen q
      5 0 2
      Cahin q
      0 -4 3
      2
      Cahin
      3
      Aulatrias p
      0 0 1
      Binen p
      5 0 2
      Cahin p
      0 -4 3
      2
      Binen
      
      Output:
      2
      4
      

      Added by:[Trichromatic] XilinX
      Date:2008-12-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Benelux Algorithm Programming Contest 2008









      SPOJ Problem Set (classical)

      3462. The Skatepark´s New Ramps

      Problem code: RAMP

      The local skating park has been given a financial incentive by the city to make the park interesting for skaters of all levels. The park wants to use the incentive to build a series of ramps, somewhat resembling a mountain range. When talking to some of the volunteers in the committee responsible for the project, you find out they're having dificulties deciding about the best conguration of the ramps. They know the number of ramps to be built, and for each ramp they agree on the range of the height for that ramp. They are still discussing exactly how high each ramp should be, since they can't afford to have them all at their highest, but they do want to spend all of the budget. This is the most important issue in the debate: they can't agree whether they want the differences between the ramps to be small, to give the full ride a more consistent feeling, or as big as possible, to create a more diverse set of challenges.

      You also notice they don't really have a good idea what the possibilities are, leaving them stranded in 'what-if' discussions. You decide to help them out by showing them the options they have, both the ones where the dierence between the highest and lowest ramp is kept as small as possible, as well as the one where that difference is as much as possible. Since the committee is mainly bickering over the allowable differences, you decide to start out by just presenting them the minimum and maximum difference between the highest and lowest ramp. Luckily, the park has a lot of space, so you won't need to take the placement of the ramps into account. All ramps have the same inclination, which is such that a ramp of height h will have a length 4h (measuredflat, not over the ramp).

      Input

      The first line of input consists of the integer number n, the number of test cases. For each test case:

      A line with the integer number r (2 <= r <= 10000), the number of ramps the park will place;

      A line with the integer number m (0 <= m <= 200000000), the number of cubic meters of concrete the park has money for;

      r lines with two numbers, l and t (0.00 <= l <= t <= 100.00), separated by one space, the minimum and maximum height in meters of the r-th ramp.

      You may assume all ramps are made entirely of concrete, and shaped as 1 meter wide prisms, with a triangle with two equal sides as base. A series of ramps within the given constraints and using all concrete is guaranteed to exist.

      Output

      For each test case, the output contains one line with two numbers, separated by one space: the minimum difference between the highest and lowest ramp and the maximum difference between the highest and the lowest ramp. These numbers are rounded to two decimals.

      Example

      Input:
      1
      3
      36
      1.00 4.00
      1.00 4.00
      1.00 4.00
      
      Output:
      0.00 3.00
      

      Added by:[Trichromatic] XilinX
      Date:2008-12-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Benelux Algorithm Programming Contest 2008









      SPOJ Problem Set (classical)

      3463. Robintron

      Problem code: ROBIN


      It is during the great war in the year 2240 that the Robinson family decides to leave the human empire, in search for more peaceful and quiet places. The Robinsons already have a planet in mind to which they wish to travel and want to get there as soon as possible. However, because all vehicles capable of spaceflight are being used for the war, the Robinson family has no way to escape to other planets by means of ordinary spaceflight. It is therefore that Joe Robinson, the father of the family, created the Robintron. The Robintron is a vehicle that is capable of travelling from one planet's surface to another by only using the forces of gravity.

      It is the gravitational pull of a planet that keeps the Robintron on a planet's surface. This pull extends as far as the planet's gravity well, a circular area around the center of the planet, which is generated by the planet's mass. However, these gravity wells can also be used to assist the Robintron in leaving a planet by the way of planet hopping. Planet hopping can be performed when the Robintron is on the surface of a planet and comes within the area of another planet's gravity well. The Robintron uses the other planet's gravity well to gain enough momentum to escape into space, and to land on the other planet's surface. Leaving a planet and subsequently landing on another one takes no significant amount of time.

      Planet hopping has some disadvantages. The Robintron must be within the gravity well of a planet other than the one it resides on, to be able to effectively use it for planet hopping. However, as the planets rotate around a star (which they all do in perfectly circular orbits), their position continuously changes according to their rotational speed. Thus, it can take up some time for the Robintron to enter the gravity well of a particular planet. Also, as soon as the Robintron chooses to enter the gravity well of a planet, it will move along with that planet around the star. Therefore, this could mean that another planet's gravity well may never come in reach of the Robintron.

      Given a list of planets in a star system, a starting position and destination, write a program that determines how many days it will take (using the ceiling function, i.e. ceiling(2.3) = 3) for the Robintron to travel to its destination, given that it travels via the fastest route possible.

      Because in most star systems all planets are positioned around the star in a disc, only two dimensions have to be taken into account. Also, a planet is assumed to be a single point in space, and the Robintron's coordinates are equal to those of the planet it resides on.

      Input

      The first line of input consists of the integer number n, the number of test cases;

      Then, for each test case:

      A line containing the positive integer number m (0 < m < 1000), the number of planets in the star system (excluding the star which always resides at position [0, 0]);

      Per planet a line containing 4 floating-point numbers x (-1e10 <= x <= 1e10) and y (-1e10 <= y <= 1e10), the x-coordinate and y-coordinate of the planet relative to the star at the start of the Robintron's journey respectively; r (0 < r <= 1e5) the radius of the planet's gravity well and s (0 <= s <= 2 * Pi) the speed, in radians per day, at which the planet rotates (counterclockwise) around the central star. The numbers are separated by a space.

      The Robintron's journey always starts at the first listed planet and its destination is always the last listed planet, which is always reachable from the Robintron's starting position. The star (at position [0, 0]) is too hot for the Robintron and cannot be used for planet hopping.

      Output

      For each test case, the output consists of a line with one integer number: the number of days (rounded up, or 0 if the Robintron can reach its destination immediately) that the Robintron must travel to reach its destination.

      Example

      Input:
      2
      3
      10.0 0.0 1.0 1.570796325
      -13.0 0.0 3.1 3.14159265
      17.0 0.0 4.1 0.0
      5
      10.0 0.0 1.1 1.0
      12.0 0.0 1.1 2.0
      13.0 0.0 1.1 1.0
      0.0 11.0 1.1 3.14159265
      14.0 0.0 1.1 1.0
      
      Output:
      3
      7
      

      Added by:[Trichromatic] XilinX
      Date:2008-12-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Benelux Algorithm Programming Contest 2008









      SPOJ Problem Set (classical)

      3465. Drive through MegaCity

      Problem code: DRIVE

      MegaCity of the future is a rectangular grid of streets. Each intersection has integer Cartesian coordinates x and y. To get from intersection a with coordinates xa, ya to intersection b with coordinates xb, yb you need to drive exactly | xa - xb | + | ya - yb | blocks. Usually, it takes 10 time units to drive one block, so one can easily compute the time it takes to get from a to b. However, traffic jams that occur in MegaCity turn estimation of minimal driving time into a complex problem that you have to solve.

      Traffic jams in MegaCity affect a rectangular area that is specified by coordinates of its bottom-left and top-right corners. The time to travel one block in the traffic jam is specified. All streets that are strictly inside the rectangular region are affected by the traffic jam. Sometimes, it is better to drive around the traffic jams to save time, but sometimes it is better to drive through some traffic jams as shown in the example - 17 blocks are driven outside of traffic jams, taking 10 time units per block, and 2 blocks in the light traffic jam with 11 time units per block.

      Input

      Multiple test cases. The number of them is given in the very first line. For each test case:

      The first line contains four integer numbers xa, ya, xb and yb, coordinates of the start and finish intersections. The second line contains a single integer number n (0 <= n <= 1000) which specifies the number of traffic jams. The following n lines describe traffic jams. Each traffic jam is described by five integer numbers x1,i, y1,i, x2,i, y2,i and ti, where first four numbers are coordinates of the bottom-left and top-right corners of the jammed area (x1,i < x2,i, y1,i < y2,i), and ti (10 < ti <= 108) is the time it takes to travel one block inside this traffic jam. All coordinates are from 0 to 108 inclusive. Areas of traffic jams neither intersect nor touch each other. Start and finish points are different and do not lie inside nor on the border of any traffic jam.

      Output

      For each test case:

      A single integer - the minimal driving time from intersection a to intersection b.

      Example

      Input:
      1
      1 6 15 3
      4
      2 1 3 7 44
      5 2 10 4 33
      8 5 11 9 22
      12 1 14 8 11
      
      Output:
      192
      

      Warning: A naive algorithm may not run in time!

      Note: In Sphere Online Judge system, "Memory Limit Exceeded" will be shown as "Runtime Error(other)", with the 0.00 second run-time & 92-200k memory used, or "Runtime Error(SIGSEGV)" with 250M memory used.


      Added by:[Trichromatic] XilinX
      Date:2008-12-07
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:ACM Northeastern European Regional Contest 2008









      SPOJ Problem Set (classical)

      3476. Deposit

      Problem code: DEPOSIT

      Banks offer deposit schemes of various kinds to attract customers. In an r -year progressively reducing recurring deposit scheme (PRRDS) of a bank, a customer is required to deposit progressively reducing amounts every year for r years. Depending on the duration r of the scheme and the total amount T deposited in r years, the bank offers to return on maturity, i.e., after the expiry of r years, an amount R , which is equal to k times the amount deposited in the first year. The bank ensures that the return R looks attractive by making a suitable choice of k ; k being a natural number.

      In a PRRDS, the amount to be deposited in each but the last two years is exactly equal to the sum of amounts to be deposited in the next two years. The amounts to be deposited in the last two years, say x in the last year and y in the last but one year, are progressively reducing (x, y > 0;y > x) and are determined so that the total amount deposited in r years is exactly equal to the specified amount T . Assume that all deposits are in whole number of Rupees.

      Write a program for the bank, so that given r , k and T , the program computes x and y for which the return R is maximum. For example in a 4-year scheme with r = 4 , k = 3 and T = 500 , the progressively reducing recurring deposits 248, 126, 122 and 4, ensures the maximum return R = 744 with x = 4 and y = 122 .

      Input

      The input may contain multiple test cases.

      For each test case there is only one input line. The line gives values of r , k and T . Assume that r is not greater than 20.

      A line containing a zero `0' as the first character follows the last case.

      Output

      For each test case there is only one output line. The line gives the computed values of x , y and R .

      Example

      Input
      4 3 500 
      5 3 10000 
      6 4 8000 
      8 5 12000 
      0
      
      Output
      4 122 744 
      5 1425 12855 
      1 666 13332 
      1 363 23635
      

      Added by:Duc
      Date:2008-12-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM Kanpur 2007









      SPOJ Problem Set (classical)

      3477. Baby

      Problem code: BABY


      A baby tries to solve the well-known eight-queen puzzle: the problem of placing eight chess queens on an 8×8 chessboard so that no two queens share the same row, column, or diagonal. The baby understands the concept of row and column quite well but diagonal is not very clear to her. As a result she succeeds placing eight queens on the board so that no two queens share the same row or column but there remains the possibility that some queens share the same diagonal.

      Given baby's queens (a solution by the baby) and a valid eight-queen solution, it is possible to move baby's queens to positions of queens in the valid solution. Assume that in a single move, a queen can be moved one unit row-wise or column-wise into an unoccupied position.

      Write a program to find the minimum number of moves required to move baby's queens to positions of queens in the valid solution. The program should be usable for a more general n -queen puzzle where n queens are placed on an n×n chessboard, 4 ≤ n ≤ 16 . Assume that rows and columns of the chessboard are numbered 1, 2,..., n .

      Input

      The input consists of multiple test cases.

      Each case begins with a line containing the integer n .

      Each of the next two lines contains a sequence of n integers. Integers in the first line represent column numbers of baby's queens appearing in rows 1, 2,..., n respectively. In the same way, the second line contains column numbers of queens in the given valid solution. A space separates two consecutive integers in the sequence.

      A line containing a zero `0' as the first character follows the last case.

      Output

      For each test case, print the minimum number of moves required.

      Example

      Sample Input
      4 
      1 2 3 4 
      3 1 4 2 
      4 
      3 2 4 1 
      3 1 4 2 
      5 
      5 3 1 4 2 
      5 3 1 4 2 
      5 
      1 5 2 4 3 
      3 1 4 2 5 
      0
      
      Sample Output
      6 
      2 
      0 
      8
      

      Added by:Duc
      Date:2008-12-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM Kanpur 2007









      SPOJ Problem Set (classical)

      3483. Begin

      Problem code: BEGIN

      Begin a sequence of distinct natural numbers Ni , i = 0, 1, 2,... , with the number B (= N0) ; generate numbers Ni , i = 1, 2,... , recursively and end the sequence with the last generated number E . The characteristic of numbers and the process for generation are stated below:

      * Each number in the sequence contains an even number of decimal digits and is of the form f1d1f2d2fk...dk where d1, d2,..., dk , are k distinct digits in increasing order and each fj is a non-zero digit.

      * For i = 0, 1, 2,... , if Ni = f1d1f2d2...fkdk then Ni+1 = F1D1F2D2...FKDK , where K$ \ge$k ; D1, D2,..., DK , are distinct digits that occur in Ni and appear in increasing order in Ni+1 ; and FJ is the frequency of DJ in Ni , for J = 1, 2,..., K . For example if Ni = 102335 then Ni+1 = 1011122315 .

      Write a program to find for a given E , the longest sequence of numbers that ends with E and begins with the smallest B .

      Again consider an example; if E =1011122315 then the required sequence of numbers is 303355 103325 1011122315.

      Input

      The input may contain multiple test cases.

      Each test case contains only one input, viz., E .

      The input terminates when a line containing 0 appears as a test case.

      Output

      For each test case, print the longest sequence of numbers that ends with E and begins with the smallest B . Use space to separate two consecutive numbers in the sequence.

      Example

      Sample Input
      1011122315
      22
      112213
      0
      
      Sample Output
      303355 103325 1011122315
      22
      13 1113 3113 2123 112213
      

      Added by:Duc
      Date:2008-12-09
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM Kanpur 2006









      SPOJ Problem Set (classical)

      3484. Crossbits

      Problem code: CROSSBIT


      Crossbits are like Crosswords; instead of entering words you enter binary bits 01 in a Crossbit under certain given conditions, assuming that a solution exists. An empty Crossbit of size N is an empty grid of size N×N.

      Given a natural number N , consider entering N2 binary bits in an empty Crossbit, satisfying the following conditions:

      • Each square in the grid contains either a 0-bit or a 1-bit with no 1-bit in two major diagonals.
      • The total number of 1-bit in each row / column is exactly equal to K , K being a given natural number less than N.
      • A 0-bit has at least another adjacent 0-bit either in the same row or in the same column.
      • The Crossbit represents the N2 -bit binary number B formed by placing bits in the 1st , the 2nd , ... the Nth row from left to right.

      You are required to write a program that enters bits in an empty Crossbit so that the Crossbit represents the least binary number B for given N and K .

      As an illustration consider the case with N = 4 and K = 1 . The Crossbit shown below represents the least binary number B = 0010100000010100 of 16 bits satisfying the specified conditions.

      0 	0 	1 	0
      1 	0 	0 	0
      0 	0 	0 	1
      0 	1 	0 	0
      

      Input

      The input may contain multiple test cases.

      For each test case parameters N and K of the Crossbit are given in one line. Assume that N does not exceed 10.

      The input terminates with a line containing 0 as input.

      Output

      For each test case, print the Crossbit in N rows; each row contains N bits with a space between two neighbouring bits. Keep a blank line after the last output line of each test case.

      Example

      Sample Input
      4 1
      6 2
      0
      
      Sample Output
      0 0 1 0 
      1 0 0 0 
      0 0 0 1 
      0 1 0 0 
      
      0 0 0 1 1 0 
      1 0 0 1 0 0 
      0 0 0 0 1 1 
      1 1 0 0 0 0 
      0 0 1 0 0 1 
      0 1 1 0 0 0
      

      Added by:Duc
      Date:2008-12-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM Kanpur 2006









      SPOJ Problem Set (classical)

      3486. Elimination

      Problem code: ELIM


      Elimination of contestants from a live IQ contest on a TV channel is decided in phases.

      Initially at phase 0, N contestants, where N = 2n , n < 10 , are selected through a special online IQ contest in which a total of M (M > N) contestants participate. The contestants are identified by distinct registration numbers 1, 2,..., M . The selected contestants are ranked distinctly from 1 to N according to their performance in the online contest. They are qualified to participate in the live contest.

      In the pth phase, p = 1, 2,..., n, Kp contestants participate in the live contest, where Kp = 2n-p+1 . On the basis of response to questions presented during the show, Kp/2 of Kp contestants are ranked distinctly from 1 to Kp/2 . These Kp/2 contestants qualify to participate in the next phase. At the nth phase there are only two contestants and the one selected at this phase is the winner of the contest.

      You are required to write a program that identifies the winner of the contest, given the following information:

      • INFO_1: Registration numbers of N contestants who are selected through the online IQ contest, in order of the rank in the online IQ contest, and
      • INFO_2: A total of N - 1 qualified contestants in different phases; K2 in phase 1, K3 in phase 2, ... , and Kn+1 in phase n . Qualified contestants of different phases appear in order of phases, i.e., phase 1, phase 2, ... , phase n . Further, qualified contestants in a phase, say phase p , appear in the order of the rank in the phase, i.e., the rank in phase p . A qualified contestant of a phase, say phase p , is identified by his/her rank in the previous phase, i.e., in phase p - 1 .

      Input 

      Input may contain multiple test cases. For each case there are two input lines.

      The first line gives N integers representing INFO_1 while the second line gives N - 1 integers representing INFO_2.

      In each input line integers are separated by space. The input terminates with a line containing 0 as input.

      Output 

      For each test case there is only one output line. The line prints the registration number of the winner of the contest.

      Sample Input 

      23 18 6 20
      4 2 2
      29 57 4 33 5 12 16 18
      7 1 5 3 2 1 1
      0
      

      Sample Output 

      18
      29
      

      Added by:Duc
      Date:2008-12-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM Kanpur 2006









      SPOJ Problem Set (classical)

      3488. The Top-Code

      Problem code: TOPCODE

      A word is a string of two or more letters while a code is a string of one or more distinct words in lexicographic order. Thus a string of letters may represent either a word or a code. An optimum code is a code that contains the maximum number of words.

      For a given string of letters there may be one or more optimum codes. The optimum code of top priority is the optimum code that appears at the top when all optimum codes are arranged in lexicographic order.

      Given a string of letters, you are required to write a program that finds the following:

      • The total number of words, m in an optimum code,
      • The total number of optimum codes, n represented by the string,
      • The optimum code of top priority, the top-code.

      Input 

      Input consists of multiple test cases.

      For each test case there is only one line of input. It contains a string of at most 100 letters.

      A line consisting of a single letter terminates input.

      Output 

      For each test case, present output in two lines.

      The first line gives the two integers m and n defined above. The next line gives the optimum code of top priority, the top-code.

      Sample Input 

      aaaaaa
      words
      lexicographic
      a
      

      Sample Output 

      2 1
      aa aaaa
      1 1
      words
      3 2
      lexic og raphic
      


      Kanpur-Kolkata 2004-2005


      Added by:Duc
      Date:2008-12-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM Kanpur 2004









      SPOJ Problem Set (classical)

      3490. Hidden Triangle

      Problem code: HIDTRI


      Assume that each `0' or `1' in the array represents a point on a plane and the distance between each pair of neighbouring points row wise or column wise is unity. Assume further that every neighbouring pair of 1's, row wise, column wise or diagonally is connected by a line segment. Two line segments emerging from a point, either join together to form a longer line segment or form an angle of 45o, 90o or 135o, thus forming right-angled isosceles triangles. The existence of hidden right-angled isosceles triangles in an array is illustrated in the figure below.

      \epsfbox{p3258.eps}

      Input 

      Input consists of multiple test cases.

      For each test case the first line gives three integers: the case number k, the number of rows m and the number of columns n of the given array. A space appears between two neighbouring integers.

      Each of the next m lines gives a string of 0's and 1's of length n; the i-th line gives the i-th row of the array.

      Input terminates with a value zero for case number k.

      Output 

      For each test case, display output in one line. The line contains the case number k and the area of the largest right-angled isosceles triangle hidden in the array. The area is a real number with one digit after the decimal point. If a triangle does not exist then output `0.0' as the area.

      Sample Input 

      1 3 3
      101
      100
      101
      2 4 6
      001001
      010101
      111111
      000001
      0
      

      Sample Output 

      1 0.0
      2 4.0
      


      Kanpur-Kolkata 2004-2005


      Added by:Duc
      Date:2008-12-09
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM Kanpur 2004









      SPOJ Problem Set (classical)

      3492. Braille Transcription

      Problem code: BRAILLE

      Visually handicapped people use Braille system of codes for reading and writing. The basic Braille symbol (or cell) is composed of six dots arranged in two vertical columns, each column being three dots high. This pattern produces 64 one-cell symbols with character index #(20a1 + 21a2 + 22a3 + 23a4 + 24a5 + 25a6), where ai = 1, if dot i is embossed up and zero otherwise. The positions of these dots are numbered as follows:


      A cell without numbers A cell with numbers

      \epsfbox{p3254.eps}

      Many Braille codes are in use; one such is the Simple Braille System (SBS). In SBS alphabets in lower case are default characters; letters `a, b,..., z' have character indices `1, 2, ..., 26' respectively. The ``letter sign'' (dots 5-6) may be used optionally before a string of alphabets in lower case. Each numeric digit 0-9 requires one cell, with character index the digit itself. However the ``number sign'' (dots 3-4-5-6) is added before a string of numerals. In order to revert back to normal alphabets after a string of numerals, the ``letter sign'' is used. The blank cell is used as a space in alphabetic context and zero in numeric context. For example the numerals 1 - 10 are the same as the first ten letters of the alphabet, index of #a being 1 and #j being 10. SBS allows the contraction of `th', by a single cell with dots 1-4-5-6. A two-cell contraction for `tion' is allowed with dots 5-6 and dots 1-3-4-5.

      There are no single-cell codes for capital letters in SBS. So a ``capital sign'' (dot 6) is inserted before a capital letter. Two ``capital signs'' are inserted to indicate that the string of alphabets that follows is capitalized. To revert back to normal alphabets (or numerals), the ``letter sign'' (or the ``number sign'') is used. SBS ignores punctuation marks altogether.


      You are required to write a program for SBS transcription that converts an SBS code to English.

      Input 

      Input consists of multiple test cases.

      In each test case there is an SBS code. It is given in three input lines containing a certain number of Braille cells. Each Braille cell is represented by a 3×2 array of 0's and 1's, appearing in an odd and the next even numbered column of the three input lines, where `1' is used for an embossed dot and `0' otherwise.

      A line that is not a part of an SBS code, containing a single zero in column 1 terminates input.

      Output 

      For each test case, output the SBS code in English, in one line. In case the input does not conform to SBS rules stated above output simply the sign `?'.

      Sample Input 

      110010
      011100
      011110
      110110
      010100
      011110
      000011
      000101
      010110
      00001110
      00000100
      01010110
      0
      

      Sample Output 

      ?
      th5
      Tion
      THE
      


      Kanpur-Kolkata 2004-2005


      Added by:Duc
      Date:2008-12-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM Kanpur 2004









      SPOJ Problem Set (classical)

      3495. The Nobel Thief

      Problem code: NBLTHIEF

      The Nobel Prize of Kabiguru Rabindranath Thagore was stolen from a museum of Viswa Bharati University in West Bengal. The Central Bureau of Investigation (CBI) has been assigned the job to investigate the crime and recover the prize. CBI has identified some suspects and linked each one of them to a distinct subset of a set of clues.

      Let there be p suspects and q clues. Integers 1 to p identify suspects while q distinct letter-codes identify clues. The clues are of varying importance. The alphabetic order of letter-codes determines the priority order in the clues; letter-codes 'a' to 'z' vary from highest to lowest priority.

      Let L0 be the set of all suspects. Based on a clue '$ \alpha$', a subset L of L0 may be split into two disjoint subsets L+ $\scriptstyle \alpha$ and L- $\scriptstyle \alpha$. The subset L+ $\scriptstyle \alpha$ includes all elements of L that are linked to a subset of clues containing '$ \alpha$' and L- $\scriptstyle \alpha$ includes all other elements of L. Let n, n+ $\scriptstyle \alpha$, and n- $\scriptstyle \alpha$ denote respectively the total number of elements in L, L+ $\scriptstyle \alpha$ and L- $\scriptstyle \alpha$. The discriminatory power of a clue '$ \alpha$' to discriminate suspects in L is defined by $ \delta_{\alpha}^{}$ = - (| n+ $\scriptstyle \alpha$ - n- $\scriptstyle \alpha$|)

      Let L* denote a set of disjoint subsets of L0, each subset containing two or more elements. The discriminatory power $ \delta_{\alpha}^{*}$ of a clue '$ \alpha$' to discriminate suspects in subsets contained in L* is defined to be the sum of all $ \delta_{\alpha}^{}$'s corresponding to each subset in L*.


      CBI wants to select a set D of dominant clues so that the presence or absence of some or all of these clues can identify each suspect uniquely. The selection is to be done in stages.

      Let L* contain only L0 initially. At each stage of selection a clue '$ \beta$' with highest discriminatory power $ \delta_{\beta}^{*}$ is selected. Selecting the clue '$ \beta$' with highest priority breaks tie, if any. After a selection of '$ \beta$' each L in L* is split into disjoint subsets L+ $\scriptstyle \beta$ and ' L- $\scriptstyle \beta$' all resulting subsets with less than two elements are dropped from L*. The process of selection continues until L* becomes empty. All the clues thus selected form the set of dominant clues D.

      You are required to write a program to find the set of dominant clues D.

      Input 

      Input may contain multiple test cases. For each test case input is given in one line. It contains an integer k representing the case number and a certain number of strings of clues. The i-th string represents the subset of clues to which the i-th suspect is linked. A space separates two consecutive fields in input.

      Input terminates with an input 0 for the case number k.

      Output 

      For each test case, present output in one line. The line contains the case number k and a string of letters. The letters in the string correspond to the clues in D and appear in the order of their selection.

      Sample Input 

      1 cbx cpxb bc brc
      2 bac adce cbd d
      0
      

      Sample Output 

      1  xpr
      2  ab
      


      Kanpur-Kolkata 2004-2005


      Added by:Duc
      Date:2008-12-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM Kanpur 2004









      SPOJ Problem Set (classical)

      3543. Matrica

      Problem code: MATRICA


      A matrix is a rectangular table of letters. A square matrix is a matrix with an equal number of rows and columns. A square matrix M is called symmetric if its letters are symmetric with respect to the main diagonal (Mi,j = Mj,i for all pairs of i and j).

      For example, the following two matrices are symmetric:

      AAB          AAA
      ACC          ABA
      BCC          AAA
      

      However, the following two are not:

      ABCD          AAB
      ABCD          ACA
      ABCD          DAA
      ABCD
      

      Given a collection of available letters, you are to output a subset of columns in the lexicographically smallest symmetric matrix which can be composed using all the letters. If no such matrix exists, output "IMPOSSIBLE".

      To determine if matrix A is lexicographically smaller than matrix B, consider their elements in row-major order (as if you concatenated all rows to form a long string). If the first element in which the matrices differ is smaller in A, then A is lexicographically smaller than B.

      Input

      The first line of input contains two integers N (1 ≤ N ≤ 30000) and K (1 ≤ K ≤ 26). N is the dimension of the matrix, while K is the number of distinct letters that will appear.

      Each of the following K lines contains an uppercase letter and a positive integer, separated by a space.

      The integer denotes how many corresponding letters are to be used. For example, if a line says "A 3", then the letter A must appear three times in the output matrix.

      The total number of letters will be exactly N2. No letter will appear more than once in the input.

      The next line contains an integer P (1 ≤ P ≤ 50), the number of columns that must be output.

      The last line contains P integers, the indices of columns that must be output. The indices will be between 1 and N inclusive, given in increasing order and without duplicates.

      Output

      If it is possible to compose a symmetric matrix from the given collection of letters, output the required columns on N lines, each containing P character, without spaces. Otherwise, output "IMPOSSIBLE" (quotes for clarity).

      Example

      Input:
      3 3
      A 3
      B 2
      C 4
      3
      1 2 3
      
      Output:
      AAB
      ACC
      BCC
      
      Input:
      4 5
      E 4
      A 3
      B 3
      C 3
      D 3
      2
      2 4
      
      Output:
      AC
      BE
      DE
      ED
      
      Input:
      4 6
      F 1
      E 3
      A 3
      B 3
      C 3
      D 3
      4
      1 2 3 4
      
      Output:
      IMPOSSIBLE
      
      Warning: large input/output data.

      Note: The test data for this problem consist of the official test cases from the contest, as well some cases of my own.


      Added by:Neal Wu
      Date:2008-12-17
      Time limit:1s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:Croatian Open 08/09 - Contest 3









      SPOJ Problem Set (classical)

      3544. Binary Search Tree

      Problem code: BST

      A binary search tree is a tree in which every node has at most two children nodes (a left and a right child). Each node has an integer written inside it. If the number X is written inside a node, then the numbers in its left subtree are less than X and the numbers in its right subtree are greater than X.

      You will be given a sequence of integers between 1 and N (inclusive) such that each number appears in the sequence exactly once. You are to create a binary search tree from the sequence, putting the first number in the root node and inserting every other number in order. In other words, run insert (X, root) for every other number:

      insert (number X, node N)
                increase the counter C by 1
                if X is less than the number in node N
                         if N has no left child
                                 create a new node with the number X and set it to be the left child of node N
                         else
                                 insert (X, left child of node N)
                else (X is greater than the number in node N)
                         if N has no right child
                                 create a new node with the number X and set it to be the right child of node N
                         else
                                 insert (X, right child of node N)
      

      Write a program that calculates the value of the counter C after every number is inserted. The counter is initially 0.

      Input

      The first line contains the integer N (1 ≤ N ≤ 300 000), the length of the sequence.

      The remaining N lines contain the numbers in the sequence, integers in the interval [1, N]. The numbers will be distinct.

      Output

      Output N integers, each on its own line, the values of the counter C after each number is inserted into the tree.

      Example

      Input:
      8
      3
      5
      1
      6
      8
      7
      2
      4
      
      Output:
      0
      1
      2
      4
      7
      11
      13
      15
      

      Warning: large input/output data.

      Warning: A naive algorithm may not run in time; do not simply implement the above algorithm.

      Note: The test data for this problem consist of the official test cases from the contest, as well some cases of my own.


      Added by:Neal Wu
      Date:2008-12-17
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:Croatian Open 08/09 - Contest 3









      SPOJ Problem Set (classical)

      3545. Najkraci

      Problem code: NAJKRACI

      A road network in a country consists of N cities and M one-way roads. The cities are numbered 1 through N. For each road we know the origin and destination cities, as well as its length.

      We say that the road F is a continuation of road E if the destination city of road E is the same as the origin city of road F. A path from city A to city B is a sequence of road such that origin of the first road is city A, each other road is a continuation of the one before it, and the destination of the last road is city B. The length of the path is the sum of lengths of all roads in it.

      A path from A to B is a shortest path if there is no other path from A to B that is shorter in length.

      Your task is to, for each road, output how many different shortest paths containing that road, modulo 1 000 000 007.

      Input

      The first line contains two integers N and M (1 ≤ N ≤ 1500, 1 ≤ M ≤ 5000), the number of cities and roads.

      Each of the following M lines contains three positive integers O, D and L. These represent a one-way road from city O to city D of length L. The numbers O and D will be different and L will be at most 10000.

      Output

      Output M integers, each on its own line – for each road, the number of different shortest paths containing it, modulo 1 000 000 007. The order of these numbers should match the order of roads in the input.

      Example

      Input:
      4 4
      1 2 5
      2 3 5
      3 4 5
      1 4 8
      
      Output:
      2
      3
      2
      1
      
      Input:
      5 8
      1 2 20
      1 3 2
      2 3 2
      4 2 3
      4 2 3
      3 4 5
      4 3 5
      5 4 20
      
      Output:
      0
      4
      6
      6
      6
      7
      2
      6
      

      Note: The test data for this problem consist of the official test cases from the contest, as well some cases of my own.


      Added by:Neal Wu
      Date:2008-12-17
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:Croatian Open 08/09 - Contest 3









      SPOJ Problem Set (classical)

      3576. Boy Scouts

      Problem code: BOYSCOUT


      Boy Scouts of New England organize Scout Olympics every year. They ask each team to perform certain tasks, sum up their points, announce winners, and then stay up all night by the fire plying guitar and singing scout songs. This year, Scouts decided to organize the Olympics in one of the most beautiful forests in Maine. There will be only one difficult task. A team picks one tree as a starting point, then goes to another tree in a straight line, then to another, etc. until they come back to the starting one. They win as many points as there are trees on their route. However, they are only allowed to move in a counter-clockwise manner, i.e. after reaching a tree, they can only rotate to the left by less than 180 degrees. Furthermore, when they reach the starting tree again, they should be able to repeat the same route, still going couter-clockwise. More specifically, their path should trace out the boundary of a convex polygon. As they don't bring laptops to the Olympics, the Boy Scouts wants you to compute the maximum possible score a team can achieve.

      Input

      The first line of the input contains a single integer N (3 ≤ N ≤ 100), which is the number of trees in the forest. Each of the next N lines contain two real numbers x and y separated by a space character (-106 ≤ x, y ≤ 106), that represent coordinates of one tree. Coordinates are given with at most two decimal digits. There are no three colinear trees.

      Output

      Output one integer, the maximum number of points a team can score, followed by a newline.

      Example

      Input:
      5
      0 0
      1.5 -0.25
      0 -1
      -1 0.5
      0.5 1
      
      Output:
      4
      

      Added by:Jelani Nelson (Minilek)
      Date:2008-12-22
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:MIT Individual Contest 2008









      SPOJ Problem Set (main)

      3577. Parity

      Problem code: PARITY

      You are given n binary strings s1,...,sn, each of the same length m. Along with each si you are given a bit bi. You are also given some nonnegative integer k and want to know whether there exists a subset S of {0,1,...,m-1} of size at most k such that for each i=1,2,...,n, the bit bi is the XOR of the bits of si at the indices in S. The si are 0-indexed strings. Recall that the XOR of a set of bits is 1 if the number of bits equal to 1 is odd, else the XOR is 0 (in particular, the XOR of an empty set of bits is 0). For example, if s1 = 1010 and S = {0,3}, then b1 would be 1 (the first bit of s1) XOR'd with 0 (the last bit of s1), which is 1. Given n, k, and the strings s1,...,sn and their corresponding bi, find a set S of size at most k which produces the given bi. You should also detect when no such S exists.

      Input

      The first line contains n and k, space-separated (1 ≤ n ≤ 64, 0 ≤ k ≤ 10). n lines then follow, where the ith line contains si, followed by a space, then bi. In a given test case all strings si are of the same length m (1 ≤ m ≤ 50). k will not be bigger than m.

      Output

      If no set S of size at most k exists producing the given bi, output -1 followed by a newline. Otherwise, on the first line output the size of a possible S. If the size of that S is not 0, on the second line, output a space-separated list of the indices in S, followed by a newline. If there exist multiple valid S to be output, you can output any one of your choosing.

      Example

      Input:
      3 1
      111 1
      001 0
      011 1
      
      Output:
      1
      1
      

      Added by:Jelani Nelson (Minilek)
      Date:2008-12-22
      Time limit:5s-30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:MIT Individual Contest 2008









      SPOJ Problem Set (main)

      3578. Hashing

      Problem code: HASH


      Consider the hash function h(y) = a*y + b (mod m) which maps each integer to some integer between 0 and m-1. You are given x,n,c,d and are curious how many of the hash values h(x),h(x+1),...,h(x+n) land in the interval [c,d].

      Input

      The first line contains a positive integer t, the number of test cases (1 ≤ t ≤ 10^5). t lines then follow, where the ith line gives the values a,b,x,n,c,d,m, space-separated, for the ith test case. All given values are non-negative. Also, 1 ≤ m ≤ 1015, c ≤ d < m, a,b < m, x+n ≤ 1015, and a*(x+n) + b ≤ 1015.

      Output

      For each test case in order output the number of i, 0 ≤ i ≤ n, such that c ≤ a*(x+i) + b (mod m) ≤ d in that test case, followed by a newline.

      Example

      Input:
      2
      2 3 1 3 0 1 7
      1 0 0 8 0 8 9
      
      Output:
      1
      9
      

      Added by:Jelani Nelson (Minilek)
      Date:2008-12-22
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:MIT Individual Contest 2008









      SPOJ Problem Set (classical)

      3579. Disjoint Paths

      Problem code: DISJPATH


      One of your classes has K students in it who really don't like each other. In fact, they dislike each other so much that they want to find routes to class that don't cross at any intersection so that they won't ever see each other outside of class. Can you find such routes?

      Input

      The input file will contain multiple cases. The first line of each case is K N, where K is the number of routes you need to find and N is the number of intersections in MIT's floor plan. The intersections are numbered 1,...,N. This is followed by N lines, one for each intersection, containing the indices of the adjacent intersections, separated by spaces. (This means that if the line for intersection 2 contains a 3, then the line for intersection 3 will contain a 2.) Every intersection is adjacent to at least one other intersection. Each case is followed immediately by the next case. The end of the input is indicated by a line containing only "0 0". You may assume that 1 ≤ K ≤ 100 and 2 ≤ N ≤ 5000. The students all start at intersection 1 and their class is at intersection 2.

      Output

      For each case, output the case number, in the format "Case #:", followed by a newline. If there are K non-intersecting routes from the start (1) to the end (2), then this must be followed K lines, each one giving a list of corners, in order, on one such route from 1 to 2. If not, then output one line with the word "Impossible". Output a blank line after each test case.

      Example

      Input:
      3 5
      3 4 5
      3 4 5
      1 2
      1 2
      1 2
      4 5
      3 4 5
      3 4 5
      1 2
      1 2
      1 2
      0 0
      
      Output:
      Case 1:
      1 3 2
      1 4 2
      1 5 2
      
      Case 2:
      Impossible
      

      Added by:Jelani Nelson (Minilek)
      Date:2008-12-22
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:MIT Individual Contest 2008









      SPOJ Problem Set (main)

      3581. Tree Similarity

      Problem code: TREESIM

      You are given two labeled and ordered rooted trees T and T' and would like to calculate the distance from T to T', which is the minimum number of operations you can perform on T to make it equivalent to T'. For each operation you can choose to do one of three things:

      1. change the label of one node in T
      2. delete a non-root node in T
      3. insert a new node in T at a position somewhere below its root

      Recall the trees T and T' are ordered, which means that if a non-leaf node has c children, its children are ordered from 1 to c. That is, there is a 1st child, a 2nd child, etc., all the way up to a cth child. When we say a tree X is equivalent to a tree Y, we mean the root of X should have the same label as the root of Y, their roots should have the same number of children (call it c), and the subtree rooted at the ith child of the root of X should be equivalent to the subtree rooted at the ith child of the root of Y for i=1,2,...,c. We now describe what we mean by deletion and insertion of non-root nodes in T. When deleting a non-root node w with d children, let u be its parent and suppose w is u's ith child. Then the first child of w becomes u's ith child, the second child of w becomes u's (i+1)st child, etc. For j < i, the jth child of u remains the same, but for all j > i, the child which was formerly the jth child of u now becomes its (j+d-1)st child (they get "shifted over" due to the insertion of w's children into u's child list). To insert a non-root node w into the tree, we can choose any node u to be its parent, and we can choose any contiguous subsequence (possibly empty) of u's children to become w's children, putting w in their place. When inserting a node, we can give it any label we want at the time of insertion. The root of T can never be deleted, and you can never insert a new node above the root to become the old root's parent. You can, however, change the label of the root.

      Input

      The first line contains n and m separated by a space, the sizes of the trees T and T', respectively (1 ≤ n,m ≤ 60). The next n lines describe T. On the ith line is a description of the ith node in the tree: its label, the number of children it has, then a list of its children in order from first to last, all space-separated. The next m lines similarly describe T'. Labels are nonnegative integers fitting in a 32-bit signed integer. The root of each tree is the node which is not the child of any other node in the tree.

      Output

      On a single line output the minimum number of operations that can be performed on T to make it equivalent to T', followed by a newline.

      Example

      Input:
      3 2
      6 0
      1 2 0 2
      4 0
      2 1 1
      4 0
      
      Output:
      2
      

      Added by:Jelani Nelson (Minilek)
      Date:2008-12-22
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:MIT Individual Contest 2008









      SPOJ Problem Set (main)

      3582. Restaurant Tab

      Problem code: RSTAURNT

      After eating dinner at a restaurant with some friends, you determine how much money each person owes. Each of you has some cash and some change, but very few of you have exact change. Can you make change for each other so that each person ends up paying the exact right amount?

      Input

      The input file will contain multiple cases. The first line of each case is N, the number of people at the table. This is followed by N lines, one for each i ∈ [1,N], containing

      xi ci,1 ci,5 ci,10 ci,25 ci,100 ci,500 ci,1000 ci,2000 ci,5000 ci,10000

      where xi is the amount in cents that person i owes and ci,v is the number of coins or bills worth v cents that person i starts out with. For example, person 1 has c1,1 pennies, c1,5 nickels, etc. Each case is followed immediately by the next case. The end of the input is indicated by a line containing only a zero. You may assume that no person owes more money than they have (i.e. xi ≤ Σj j*ci,j) and that the total amount of money in cents that everyone starts with fits in a signed 32-bit integer. You may also assume that N ≤ 100000.

      Output

      For each case, output the case number, in the format "Case #:" (where # is the case number, starting at 1), followed by a space, followed by "YES" if all of the money can be rearranged so that each person ends up paying the correct amount and "NO" if not.

      Example

      Input:
      1
      10 0 0 1 0 0 0 0 0 0 0
      2
      0 0 0 0 0 2 0 0 0 0 0
      500 0 0 0 0 0 1 0 0 0 0
      1
      100 4 0 2 3 0 1 0 0 0 0
      0
      
      Output:
      Case 1: YES
      Case 2: YES
      Case 3: NO
      

      Added by:Jelani Nelson (Minilek)
      Date:2008-12-22
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:MIT Individual Contest 2008









      SPOJ Problem Set (classical)

      3591. Patting Heads

      Problem code: PATHEADS

      It's Bessie's birthday and time for party games! Bessie has instructed the N (1 ≤ N ≤ 100,000) cows conveniently numbered 1..N to sit in a circle (so that cow i [except at the ends] sits next to cows i-1 and i+1; cow N sits next to cow 1). Meanwhile, Farmer John fills a barrel with one billion slips of paper, each containing some integer in the range 1..1,000,000.

      Each cow i then draws a number Ai (1 ≤ Ai ≤ 1,000,000) (which is not necessarily unique, of course) from the giant barrel. Taking turns, each cow i then takes a walk around the circle and pats the heads of all other cows j such that her number Ai is exactly divisible by cow j's number Aj; she then sits again back in her original position.

      The cows would like you to help them determine, for each cow, the number of other cows she should pat.

      Input

      • Line 1: A single integer: N.
      • Lines 2..N+1: Line i+1 contains a single integer: Ai.

      Output

      • Lines 1..N: On line i, print a single integer that is the number of other cows patted by cow i.

      Example

      Input:
      5
      2
      1
      2
      3
      4
      
      Output:
      2
      0
      2
      1
      3
      

      The first cow pats the second and third cows; the second cows pats no cows; etc.


      Added by:Neal Wu
      Date:2008-12-26
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL
      Resource:USACO Dec 2008









      SPOJ Problem Set ()

      3678. Cattle Bruisers

      Problem code: CATTLEB

      Canmuu is out for revenge after being utterly defeated by Bessie in paintball and has challenged Bessie to a video game.

      In this game, Bessie starts out at point (BX, BY) in the coordinate grid (-1,000 <= BX <= 1,000; -1000 <= BY <= 1,000), and tries to escape, starting at time 0. She moves continuously at a velocity of (BVX, BVY) units/second (-100 <= BVX <= 100; -100 <= BVY <= 100). Thus, at time 1 she will be at point (BX + BVX, BY + BVY); at time 1.5 she will be at (BX + 1.5*BVX, BY + 1.5*BVY).

      Unfortunately, Canmuu has sent N (1 <= N <= 50,000) cattle bruisers to pursue Bessie. At time t=0, cattle bruiser i is at position (X_i, Y_i) (-1,000 <= X_i <= 1,000; -1,000 <= Y_i <= 1,000) with velocity (VX_i, VY_i) units/second (-1,000 <= VX_i <= 1,000; -1,000 <= VY_i <= 1,000).

      Each cattle bruiser carries a "proximity" weapon to fire at Bessie; the weapon can hurt Bessie when the cattle bruiser is no further than R (1 <= R <= 2,500) units from her.

      Bessie has a shield to protect herself from these attacks. However, she does not want to waste any of her shield's power, so she would like to know the maximum number of cattle bruisers within firing range for any (potentially non-integer) time t >= 0.

      In order to avoid precision errors with real numbers, it is guaranteed that the answer produced will be the same whether the attack range is decreased to R-0.0001 or increased to R+0.0001.

      Input

      * Line 1: Six space-separated integers: N, R, BX, BY, BVX, and BVY * Lines 2..N+1: Line i+1 contains four space-separated integers: X_i, Y_i, VX_i, and VY_i

      Output

      * Line 1: Print a single integer denoting the maximum number of cattle bruisers within attack range at any point in time.

      Example

      Input:
      
      3 1 0 0 0 2
      0 -3 0 4
      1 2 -1 1
      1 -2 2 -1
      
      Input details:

      Bessie starts at point (0, 0) and is moving at 2 units per second in the (positive) y-direction. There are 3 cattle bruisers, the first of which starts at point (0, -3) and travels 4 units per second in the y-direction. The maximum distance for a cattle bruiser to be in range of Bessie is 1 unit.

      Output:
      
      2
      
      Output details:

      At time 1.5, Bessie is at point (0, 3), and the three bruisers are at points (0, 3), (-0.5, 3.5), and (4, -3.5). The first two cattle bruisers are within 1 unit of Bessie, while the third will never be within 1 unit of Bessie, so 2 is the most achievable.


      Added by:Mir Wasi Ahmed
      Date:2009-01-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:USACO Holiday Special Contest 2009, Problemsetter - Neal Wu









      SPOJ Problem Set ()

      3679. Moo University - Emergency Pizza Order

      Problem code: MOOPIZZA


      Moo U's cafeteria has run out of hay and so must order pizzas for the C (1 <= C <= 1,000) calves attending Moo U. Conveniently, a large pizza from the local pizzeria, Pizza Farm, serves exactly one calf.

      Pizza Farm is willing to make a pizza for each calf, but, due to the size of the order, has three constraints on the order:

      * Although Pizza Farm has long list of T (1 <= T <= 30) vegetarian toppings, each of the pizzas must have exactly K (1 <= K <= T) toppings

      * No topping on a pizza can be duplicated (a pizza cannot have onions and onions, for example).

      * No two pizzas in the order can have the same set of toppings.

      For example, if pizza 1 has onions, green peppers, pineapples, and wheat grass, then it can be the only pizza with that exact set of toppings, although pizza 2 might have onions, green peppers, pineapples, and also olives.

      For ordering purposes, the toppings are numbered 1..T.

      The calves at Moo U are very picky when it comes to their pizza toppings. Some calves might not like all of the toppings available. A calf will eat a pizza only she likes every single one of the toppings on that pizza. Determine the maximum number of calves that can be fed.

      Input

      * Line 1: Three integers: C, T, and K. * Lines 2..C+1: Each line of space-separated integers describes which toppings one of the calves likes. The first integer on a line is the number of topping the calf likes. The remaining integers on the line are the toppings that the calf likes.

      Output

      * Line 1: A single integer, the maximum number of calves that can be fed.

      Example

      Input:
      
      3 2 1
      2 2 1
      1 1
      1 2
      
      
      Input details:

      There are three calves. Pizza Farm has two toppings and each pizza must have exactly one topping. The first calf likes both of the toppings, the second calf likes only the first topping, and the third calf likes only the second topping.

      Output:
      
      2
      
      Output details:

      There are only two pizzas that can be made: a pizza with topping 1 and a pizza with topping 2. If the first pizza is given to the first calf (since she likes topping 1) and the second pizza to the third calf (since she likes topping 2), two calves will be fed. There is no way to feed all three calves.


      Added by:Mir Wasi Ahmed
      Date:2009-01-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:USACO 2004 March Green Division, Problemsetter - Hal Burch









      SPOJ Problem Set (classical)

      3693. Maximum Sum

      Problem code: KGSS


      You are given a sequence A[1], A[2], ..., A[N] ( 0 ≤ A[i] ≤ 10^8 , 2 ≤ N ≤ 10^5 ). There are two types of operations and they are defined as follows:

      Update:

      This will be indicated in the input by a 'U' followed by space and then two integers i and x.

      U i x, 1 ≤ i ≤ N, and x, 0 ≤ x ≤ 10^8.

      This operation sets the value of A[i] to x.

      Query:

      This will be indicated in the input by a 'Q' followed by a single space and then two integers i and j.

      Q x y, 1 ≤ x < y ≤ N.

      You must find i and j such that x ≤ i, j ≤ y and i != j, such that the sum A[i]+A[j] is maximized. Print the sum A[i]+A[j].

      Input

      The first line of input consists of an integer N representing the length of the sequence. Next line consists of N space separated integers A[i]. Next line contains an integer Q, Q ≤ 10^5, representing the number of operations. Next Q lines contain the operations.

      Output

      Output the maximum sum mentioned above, in a separate line, for each Query.

      Example

      Input:
      5
      1 2 3 4 5
      6
      Q 2 4
      Q 2 5
      U 1 6
      Q 1 5
      U 1 7
      Q 1 5
      
      Output:
      7
      9
      11
      12
      
      
      Warning: large Input/Output data, be careful with certain languages

      Added by:Swarnaprakash
      Date:2009-01-10
      Time limit:2s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Kurukshetra 09 OPC









      SPOJ Problem Set (classical)

      3713. Primitive Root

      Problem code: PROOT

      In the field of Cryptography, prime numbers play an important role. We are interested in a scheme called "Diffie-Hellman" key exchange which allows two communicating parties to exchange a secret key. This method requires a prime number p and r which is a primitive root of p to be publicly known. For a prime number p, r is a primitive root if and only if it's exponents r, r2, r3, ... , rp-1 are distinct (mod p).

      Cryptography Experts Group (CEG) is trying to develop such a system. They want to have a list of prime numbers and their primitive roots. You are going to write a program to help them. Given a prime number p and another integer r < p , you need to tell whether r is a primitive root of p.

      Input

      There will be multiple test cases. Each test case starts with two integers p ( p < 2 31 ) and n (1 ≤ n ≤ 100 ) separated by a space on a single line. p is the prime number we want to use and n is the number of candidates we need to check. Then n lines follow each containing a single integer to check. An empty line follows each test case and the end of test cases is indicated by p=0 and n=0 and it should not be processed. The number of test cases is atmost 60.

      Output

      For each test case print "YES" (quotes for clarity) if r is a primitive root of p and "NO" (again quotes for clarity) otherwise.

      Example

      Input:
      5 2
      3
      4
      
      7 2
      3
      4
      
      0 0
      
      
      Output:
      YES
      NO
      YES
      NO
      

      Explanation

      In the first test case 31, 32 , 33 and 34 are respectively 3, 4, 2 and 1 (mod 5). So, 3 is a primitive root of 5.

      41, 42 , 43 and 44 are respectively 4, 1, 4 and 1 respectively. So, 4 is not a primitive root of 5.


      Added by:Swarnaprakash
      Date:2009-01-14
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Kurukshetra 09 OPC









      SPOJ Problem Set (classical)

      3723. Snooker

      Problem code: SNOOKER

      Consider a rectangular snooker table with pockets only at the 4 corners of the rectangle as shown in the image below. Consider all integer points on the boundary of the table. At each point, except the four corners (four pockets), you are allowed to hit the ball at an angle of 45 degrees from the side of the table from which you are hitting the ball.

      From any point on the boundary you can hit the ball in two directions and they are considered to be two different ways. For instance in the image shown below, from the point S the ball can be hit in two ways as shown.

      Given the dimensions of the board your task is to find the number of ways in which the ball can be hit so that it eventually reaches one of the four holes.

      Consider the ball to be of negligible size, like a point. Also assume that the ball does not lose energy due to collisions or friction - it keeps moving until it drops into a hole.

      Input

      The input has multiple test cases. Each test case consists of two space separated integers M and N, 2 ≤ M,N ≤ 10^5, representing the dimensions of the table. M=N=0 indicates the end of tests. There are atmost 300 testcases.

      Output

      For each test case output the number of ways as described, in a separate line.

      Example

      Input:
      2 2
      2 4
      3 5
      0 0
      
      Output:
      0
      4
      24
      
      

      Added by:Swarnaprakash
      Date:2009-01-16
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Kurukshetra 09 OPC









      SPOJ Problem Set (classical)

      3724. Rainbow Ride

      Problem code: RAINBOW

      Mr.Raju and his extended family are on vacation in Chennai. They visit MGM and see the Rainbow ride. They want to enjoy the ride. However, there are some problems.

      Each person in the family likes some other people in the family. Each person insists that he or she will go on the ride only if all the people whom that person likes and all the people who like that person also go on the ride. If someone doesn't like anyone and no one likes him, he may come for the ride.

      You have been roped in to solve this dilemma. Given the weight of the each person in the family, and the list of people they like, and the maximum weight that the Rainbow can bear safely, calculate the maximum number of people in the family who can go on the rainbow.

      Input

      There will be multiple test cases in the input. For our convenience the family members are numbered from 1 to n. Each test case begins with a line containing two integers n ( 1 ≤ n ≤ 1000 ) and C ( 0 ≤ C ≤ 1000 ), where n is the number of people in the family and C the maximum capacity of the ride in kilograms.

      The next line contains n space separated integers with the ith integer giving the weight of the i th family member. These weights are positive and less than or equal to 200 kilograms. Then n lines follow. Each line contains a sequence of integers separated by spaces. The first integer ki gives the number of people in the family person i likes, followed by the persons i likes. An empty line separates each test case. The end of input is indicated by n=0 and C=0 and it should not be processed.There are atmost 50 test cases.

      Output

      For each test case output on a separate line the maximum number of persons that can take the ride under the given conditions.

      Example

      Input:
      5 200
      50 50 50 50 50
      1 2
      1 3
      0
      1 5
      1 4
      
      3 200
      100 100 100
      1 2
      1 3
      1 1
      
      0 0
      
      Output:
      3
      0
      

      Added by:Swarnaprakash
      Date:2009-01-16
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Kurukshetra 09 OPC









      SPOJ Problem Set (classical)

      3725. Taming a T-REX

      Problem code: TREX


      Although evolution theory suggests that mammals started to dominate this world only after the mass extinction of the dinosaurs, there are some people who say man and dinosaurs may have co-existed for some time. Some argue that man even tamed and used some of these animals like the Flintstones. Shankar is such a believer and Sunil is a skeptic.

      One day Sunil asked Shankar, "If your argument is right how would you tame a T-REX and what would you use it for?". Shankar replied, "We can use it for cow transportation from one village to another and we can keep it calm by feeding it at constant intervals". Sunil argued that the T-REX would have a maximum capacity C to carry. Let us say the distance is d km. If it is long, the T-REX would eat all the cows before it reaches the other village. Shankar argued that he knew a method that takes the maximum possible number of cows M to the destination. Sunil replied, "Oh really? I will give a few conditions. The T-REX will eat 1 cow every km until it reaches the destination. It may do so at any time during a 1 km stretch. So,there can not be a situation where the TREX has no cow to eat. If you drop cows in the middle, you can do so only at distances which are a multiple of 1 km. And, finally all the cows at the destination need to be alive i.e you can not cut a cow (fractions are not allowed)".

      Shankar was stunned. He needs your help. Given I (the number of cows at the starting village) , d and C find M, the maximum number of cows that can be taken to the destination subject to the mentioned constraints.

      Input

      There will be multiple test cases in the input. The input begins with a line containing a single integer n,n ≤ 300, which gives the number of test cases. Then n lines follow each containing the three integers I, 1 ≤ I ≤ 106, d, 1 ≤ d ≤ 105, and C, 1 ≤ I ≤ 106, in that order separated by spaces. d is in kilometers.

      Output

      For each test case print on a separate line the maximum number of cows that can be transported to the destination village under the given conditions.

      Example

      Input:
      2
      3000 1000 1000
      30 10 10
      
      
      Output:
      533
      5
      

      Note:

      A few test cases have been added and this problem has been rejudged on January 25th, 2009.


      Added by:Swarnaprakash
      Date:2009-01-17
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Kurukshetra 09 OPC









      SPOJ Problem Set (classical)

      3749. Subset Sums

      Problem code: SUBSUMS

      Given a sequence of N (1 ≤ N ≤ 34) numbers S1, ..., SN (-20,000,000 ≤ Si ≤ 20,000,000), determine how many subsets of S (including the empty one) have a sum between A and B (-500,000,000 ≤ A ≤ B ≤ 500,000,000), inclusive.

      Input

      The first line of standard input contains the three integers N, A, and B. The following N lines contain S1 through SN, in order.

      Output

      Print a single integer to standard output representing the number of subsets satisfying the above property. Note that the answer may overflow a 32-bit integer.

      Example

      Input:
      3 -1 2
      1
      -2
      3
      
      Output:
      5
      

      The following 5 subsets have a sum between -1 and 2:

      • 0 = 0 (the empty subset)
      • 1 = 1
      • 1 + (-2) = -1
      • -2 + 3 = 1
      • 1 + (-2) + 3 = 2

      Added by:Neal Wu
      Date:2009-01-19
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS









      SPOJ Problem Set (classical)

      3763. George

      Problem code: GEORGE

      Last week Mister George visited Croatia. Since Mister George is a very important person, while he was in a street, the police disallowed entry to that street, but vehicles that entered the street before Mister George could continue driving.

      While Mister George was visiting, Luka drove his truck around town. But because of some of the streets being closed off, he couldn't make his delivery in time and almost lost his job. Although it is late now, he is wondering how he could have planned his delivery better i.e. what would have been the least time needed to make his delivery while Mister George was visiting. He knows the route mister George took.

      The city is modeled with intersections and two-way streets connecting them. For each street, Luka knows how much time he needs to traverse it (mister George needs he same amount of time).

      For example, if Mister George starts traversing a street during minute 10 and needs 5 minutes to exit it, this street will be blocked during minutes 10, 11, 12, 13 and 14. Luka can enter the street during minutes 9 and earlier, or 15 and later.

      Write a program that calculates the least amount of time Luka needs to make his delivery, if he starts driving K minutes after the arrival of Mister George.

      Input

      The first line contains two integers N and M (2 <= N <= 1000, 2 <= M <= 10 000), the number of intersections and the number of streets. The intersections are numbered 1 to N. The second line contains four integers A, B, K and G (1 <= A, B <= N, 0 <= K <= 1000, 0 <= G <= 1000). These are, in order:

      • The intersection where Luka starts;
      • The intersection Luka must get to;
      • The difference in starting times between mister George and Luka (Luka starts at intersection A exactly K minutes after mister George starts his route);
      • The number of intersections on Mister George's route.
      The third line contains G integers, the labels of intersections mister George will visit. Every pair of adjacent integers denotes a street he will traverse. That street will exist and Mister George will traverse every street at most once. Each of the following M lines contains three integers A, B and L, meaning that there is a street between intersection A and B, and it takes L minutes to traverse. L will be between 1 and 1000.

      Output

      Output the least amount of time (in minutes) Luka needs to make his delivery.

      Example

      Input:
      6 5
      1 6 20 4
      5 3 2 4
      1 2 2
      2 3 8
      2 4 3
      3 6 10
      3 5 15
      
      Output:
      21
      

      Input:
      8 9
      1 5 5 5
      1 2 3 4 5
      1 2 8
      2 7 4
      2 3 10
      6 7 40
      3 6 5
      6 8 3
      4 8 4
      4 5 5
      3 4 23
      
      Output:
      40
      

      Croatian Open Competition in Informatics (COCI) - 2007/2008 Contest #6
      Added by:Andrés Mejía-Posada
      Date:2009-01-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:Croatian Open Competition in Informatics (COCI) - 2007/2008 Contest #6









      SPOJ Problem Set (classical)

      3791. Street

      Problem code: STREET

      There are n lots on one side of a street (where n ≤ 500). We would like to erect at most k apartment buildings on these lots. Each building must occupy an interval of at most t consecutive lots. Moreover, each lot i has a height restriction r[i] (where r[i] ≤ 100). A building cannot exceed any of the height restriction of any lot on which it is built (that is, the maximal height of the building that can be erected on lot i to j is:

      H = min{r[i], r[i + 1], ..., r[j]})

      Hence, the maximum usable facade space of the building is: H × (j − i + 1). We would like to have a program to select at most k non-overlapping intervals to erect the buildings such that the total usable facade space is maximized.

      Example 1

      Consider a street of length 10. The height restriction of each lot is as follows:

      7, 3, 12, 11, 13, 4, 8, 6, 6, 20
      Suppose we would like to erect at most k = 2 buildings and each building occu- pies at most t = 4 lots. Then, to maximize the total usable facade space, we choose two intervals r[3..5] = (12, 11, 13) and r[7..10] = (8, 6, 6, 20) (see “Example 1” in the figure below). The maximum usable facade space is 3 ∗ min{12, 11, 13} + 4 ∗ min{8, 6, 6, 20} = 57.

      Example

      Example 2

      Suppose we would like to erect at most k = 3 buildings on the same street with the same height restrictions as in Example 1, and each building occupies at most t = 4 lots. Then, to maximize the total usable facade space, we choose three intervals r[3..5] = (12, 11, 13), r[7..9] = (8, 6, 6) and r[10..10] = (20) (see “Example 2” in the figure above). The maximum usable facade space is 3 ∗ min{12, 11, 13} + 3 ∗ min{8, 6, 6} + 1 ∗ 20 = 71.

      Input

      The input file is as follows: The first line contains three integers n, k, and t separated by a space character, where 1 ≤ n ≤ 500, 1 ≤ k ≤ n, and 1 ≤ t ≤ n. The rest of the nlines contain n positive integers representing the height restriction for the n lots. For Example 1, the input file looks like:

      10 2 4
      7
      3
      12
      11
      13
      4
      8
      6
      6
      20
      

      The input should be read from the standard input, and your program will be run several times, each one with one of the test cases.

      Output

      The output file contains an integer which is the maximum usable facade space. For the above example, the output file looks like:

      57
      


      National Olympiad in Informatics (NOI) - 2007
      Added by:Andrés Mejía-Posada
      Date:2009-01-31
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:National Olympiad in Informatics (NOI) - 2007









      SPOJ Problem Set (classical)

      3831. Lubenica

      Problem code: LUBEN


      Children in school are having fun instead of listening to the teacher. With their iPhone devices the children throw watermelons at each other on the Facebook social site.

      The game started when Goran threw one watermelon at each of his friends during the first class that day. During subsequent classes, all children (including Goran) behaved like this:

      • If they had been hit by an odd number of watermelons during the previous class, they threw exactly one watermelon at each of their friends;
      • If they had been hit by an even number of watermelons (including zero), then they hit each of their friends with two watermelons.

      The children are numbered 1 through N, Goran obviously being number 1. The friend relationships between the children are also known.

      Write a program that will calculate the total number of watermelons thrown after H classes.

      Input

      The first line contains two integers N and H (1 ≤ N ≤ 20, 1 ≤ H ≤ 1 000 000 000), the number of kids and classes.

      Each of the following N lines contains a string of N characters '0' or '1'. The character (A, B) in this matrix is '1' if children A and B are friends.

      No child will be their own friend. The input matrix will be symmetric

      Output

      Output the number of watermelons after H classes.

      Example

      Input:
      5 3
      01000
      10110
      01000
      01001
      00010
      
      Output:
      26
      

      Added by:Race with time
      Date:2009-02-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:COCI 2008/2009 - Contest #5, 7th February 2009









      SPOJ Problem Set (classical)

      3832. Kruska

      Problem code: KRUS


      Aladdin has become bored of life at the palace. He has a steady job, his wife Jasmine, kids are on the way and life is becoming monotonous. Prompted by all this, he has decided to have one more adventure before settling down.

      He has decided to find the Golden Pear, an extremely valuable legendary artifact that no one has been able to find.

      The desert Aladdin is searching is can be modeled as an N×N grid of cells. Rows and columns are numbered 1 through N top to bottom and left to right. Some of the cells in the desert contain wizards that help Aladdin's quest in an unusual way.

      Aladdin starts his quest in the top left corner of the desert on a Monday facing right. His movement involves repeating these steps:

        1. If the current cell contains a wizard that is awake, then Aladdin turns 90 degrees left or right, depending on what the wizard says.

        2. If moving forward would take Aladdin out of desert, he turns 180 degrees.

        3. Aladdin moves forward one cell and it takes him exactly one day.

      For each wizard we know his location and his activity schedule for each day of the week. The schedule is a string of exactly seven letters 'L', 'R' or 'S', each character telling us what the wizard does on one day of the week (starting with Monday). The letter 'L' means that Aladdin will be told to turn left, 'R' that Aladdin will be told to turn right, while 'S' means the wizard sleeps that day.

      An old prophecy says that after K changes in direction (in steps 1 and/or 2) Aladdin will find the Pear.

      Write a program that calculates how many days the search will last, according to the ancient prophecy.

      Input

      The first line contains two integers N and K (2 ≤ N ≤ 200, 1 ≤ K ≤ 1 000 000 000), the size of the desert and the number of direction changes in the prophecy.

      The second line contains an integer M (0 ≤ M ≤ 10 000), the number of wizards.

      Each of the following M lines contains two integers R and C (1 ≤ R, C ≤ N), and a string of seven letters 'L', 'R' or 'S'. The numbers represent the row and column where the wizard is located, while the string is his schedule.

      No two wizards will share the same cell, nor will there be a wizard in cell (1, 1).

      Output

      Output the length of the search in days.

      Example

      Input:
      5 2
      2
      1 3 RRSRRRR
      1 5 RRRRLRR
      
      Output:
      4
      

      Added by:Race with time
      Date:2009-02-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:COCI 2008/2009 - Contest #5, 7th February 2009









      SPOJ Problem Set (classical)

      3833. Tresnja

      Problem code: TRES

      Lana lives in a small but merry village. There is a row of cherry trees next to the main street. Lana numbered the trees with consecutive integers starting with 1.

      After much studying, Lana noticed that the number of the tree uniquely determines the amount of cherries the tree gives.

      For one tree, consider consecutive groups of digits in the tree's number. For each group of digits, multiply the digit by the square of the length of the group. Adding these numbers for all groups gives the total number of cherries the tree gives.

      For example, in tree number 77744007, the groups are 777, 44, 00 and 7. The amount of cherries will be 7·3^2 + 4·2^2 + 0·2^2 + 7·1^2 = 86 units.

      The time has come to pick the cherry trees and the villagers have agreed to pick all trees numbered A through B (inclusive). Write a program that will calculate the total amount of cherries picked.

      Input

      Input consists of two integers A and B (1 ≤ A ≤ B ≤ 10^15), the first and last trees to be picked.

      Output

      Output a single integer, how many units of cherries will be picked.

      Example

      Input:
      100 111
      
      Output:
      68
      

      Added by:Race with time
      Date:2009-02-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:COCI 2008/2009 - Contest #5, 7th February 2009









      SPOJ Problem Set (classical)

      3863. Area of circles

      Problem code: VCIRCLES

      Given N circles. Calculate the total area that these N circles cover.

      Input

      First line: N (1 <= n <= 50)

      - In the i-th line of the next n lines contains 3 integers Xi, Yi and Ri, separated by spaces. These are the coordinates of the center and the radius of the i-th circle (-10000<=Yi-Ri,Yi+Ri,Xi-Ri,Xi+Ri<=10000)

      Output

      The total area that these N circles cover with 5 digits after decimal point

      Example

      Input:
      2
      5 6 3
      5 5 5
      
      Output:
      78.53982
      

      Added by:Phenomenal
      Date:2009-02-14
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:IOICAMP









      SPOJ Problem Set (classical)

      3865. Reljef

      Problem code: RELJEF


      Two groups of cavemen got into a land dispute and decided to settle it the old fashion-way, by throwing sticks at each other. The fight was organized in a cave, high enough that the ceiling is of no concern, but mineral deposits on the ground get in the way of flying sticks.

      The cave can be divided into R rows and C columns, so that the entire cave consists of R×C cells. Each cell in the cave is either empty or contains a chunk of mineral. Two chunks of minerals are part of the same cluster if they are adjacent in one of the four main directions (up, down, left, right).

      One group of cavemen is on the left side of the cave, the other on the right side. The groups alternate throwing sticks at the other group; first a group chooses the height at which the stick will fly and then (climbing on each others' shoulders as necessary) they throw it and the stick flies horizontally through the cave at the chosen height.

      If the stick hits a chunk of mineral on the way, it destroys the chunk, the cell becomes empty and the stick stops its journey.

      When a chunk is destroyed, it is possible that a cluster falls apart. If a newly created cluster would float in the air, then it falls down because of gravity. While falling, the cluster does not change shape i.e. all chunks in it fall together. As soon as some chunk in the falling cluster lands on a chunk from a different cluster or the ground, the entire cluster stops falling. Of ourse, if a cluster lands on another, they merge and become one.

      Your program will be given the layout of minerals in the cave and the heights at which sticks were thrown. Determine the layout of minerals after the sticks are exchanged.

      Input

      The first line contains two integers R and C (1 ≤ R, C ≤ 100), the dimensions of the cave.

      Each of the following R lines will contain C characters. The character '.' represents an empty cell, while the letter 'x' represents a chunk of mineral.

      The next line contains an integer N (1 ≤ N ≤ 100), the number of sticks thrown.

      The last line contains N integers separated by spaces, the heights at which sticks were thrown. All heights will be between 1 and R (inclusive), with height 1 being the bottom of the matrix and height R the top. The first tick is thrown left to right, the second right to left and so on.

      No cluster will initially float in the air. Also, the input data will be such that at no point will two or more clusters fall simultaneously, so that there will be no ambiguous situations.

      Output

      The output should consist of R lines, each containing C characters, the final layout of the cave, in the same format as in the input.

      Example

      Input:
      8 8
      ........
      ........
      ...x.xx.
      ...xxx..
      ..xxx...
      ..x.xxx.
      ..x...x.
      .xxx..x.
      5
      6 6 4 3 1
      
      Output:
      ........
      ........
      ........
      ........
      .....x..
      ..xxxx..
      ..xxx.x.
      ..xxxxx.
      

      Added by:Race with time
      Date:2009-02-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:COCI 2008/2009 - Croatian Regional









      SPOJ Problem Set (classical)

      3866. Finding Palindromes

      Problem code: VPALIN

      A word is called a palindrome if we read from right to left is as same as we read from left to right. For example, "dad", "eye" and "racecar" are all palindromes, but "odd", "see" and "orange" are not palindromes.

      Given n palindromes, you can generate n × n pairs of them and concatenate the pairs into single words. The task is to count how many of the so generated words are palindromes.

      Input

      The first line of input file contains the number of strings n. The following n lines describe each string: The i+1-th line contains the length of the i-th string li, then a single space and a string of li small letters of English alphabet. You can assume that the total length of all strings will not exceed 2,000,000. Two strings in different line may be the same.

      Output

      Print out only one integer, the number of palindromes.

      Example

      Input:
      3
      1 a
      2 bb
      2 aa
      
      
      Output:
      5
      The 5 palindromes are:
      aa aaa aaa bbb aaaa 
      

      Added by:Phenomenal
      Date:2009-02-15
      Time limit:5s-7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:POI 2006









      SPOJ Problem Set (classical)

      3867. Who is The Boss

      Problem code: VBOSS

      Several surveys indicate that the taller you are, the higher you can climb the corporate ladder. At TALL Enterprises Inc. this "de facto standard" has been properly formalized: your boss is always at least as tall as you are. Furthermore, you can safely assume that your boss earns a bit more than you do. In fact, you can be absolutely sure that your immediate boss is the person who earns the least among all the employees that earn more than you and are at least as tall as you are. Furthermore, if you are the immediate boss of someone, that person is your subordinate, and all his subordinates are your subordinates as well. If you are nobody's boss, then you have no subordinates. As simple as these rules are, many people working for TALL are unsure of to whom they should be turning in their weekly progress report and how many subordinates they have. Write a program that will help in determining for any employee who the immediate boss of that employee is and how many subordinates they have. Quality Assurance at TALL have devised a series of tests to ensure that your program is correct. These test are described below.

      Input

      On the first line of the input is a single positive integer n, telling the number of test scenarios to follow. Each scenario begins with a line containing two positive integers m and q, where m (at most 30000) is the number of employees and q (at most 200) is the number of queries. The following m lines each list an employee by three integers on the same line: employee ID number (six decimal digits, the first one of which is not zero), yearly salary in Euros and finally height in μm (1 μm = 10-6 meters - accuracy is important at TALL). The chairperson is the employee that earns more than anyone else and is also the tallest person in the company. Then there are q lines listing queries. Each query is a single legal employee ID.

      The salary is a positive integer which is at most 10 000 000. No two employees have the same ID,and no two employees have the same salary. The height of an employee is at least 1 000 000 μm and at most 2 500 000 μm.

      Output

      For each employee ID x in a query output a single line with two integers y k, separated by one space character, where y is the ID of x's boss, and k is the number of subordinates of x. If the query is the ID of the chairperson, then you should output 0 as the ID of his or her boss (since the chairperson has no immediate boss except, possibly, God).

      Example

      Input:
      2
      3 3
      123456 14323 1700000
      123458 41412 1900000
      123457 15221 1800000
      123456
      123458
      123457
      4 4
      200002 12234 1832001
      200003 15002 1745201
      200004 18745 1883410
      200001 24834 1921313
      200004
      200002
      200003
      200001
      
      Output:
      123457 0
      0 2
      123458 1
      200001 2
      200004 0
      200004 0
      0 3
      

      Added by:Phenomenal
      Date:2009-02-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:NWERC 2003









      SPOJ Problem Set (classical)

      3870. Military Story

      Problem code: VMILI

      Military headquaters plan to develop a better protection for a spaceport. They suppose that the spaceport would be best protected if it is surrounded with as many fences as possible and each fence is patroled by armed guards. The corresponding order was issued and military engineers started to develop a project.

      Wishing to be promoted, sergeant Stupid sent soldiers to dig in fence poles before the project was actually ready. Without much thinking, the soldiers put a lot of poles at random. Help the sergeant to decide how to make barbwire fences using the poles so that the number of fences is maximal.

      Input

      The first line contains an integer 3 ≤ N ≤ 4000, which is the number of the poles. Each of the following N lines contains two integers 0 ≤ x, y ≤ 10000, which are the coordinates of a corresponding pole. No two poles have the same position.

      Output

      The output should contain a single integer number, which is the maximal possible number of nested fences that can be constructed. Each fence is a closed polygonal line without self-crossing whose vertices are poles. Different fences should not have common points.

      Example

      Input:
      4
      100 100
      200 100
      100 200
      300 300
      
      
      Output:
      1
      

      Added by:Phenomenal
      Date:2009-02-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:acm.timus.ru









      SPOJ Problem Set (classical)

      3871. GCD Extreme

      Problem code: GCDEX

      Given the value of N, you will have to find the value of G. The meaning of G is given in the following code

      G=0;

      for(k=i;k< N;k++)

      for(j=i+1;j<=N;j++)

      {

      G+=gcd(k,j);

      }

      /*Here gcd() is a function that finds the greatest common divisor of the two input numbers*/

      Input

      The input file contains at most 20000 lines of inputs. Each line contains an integer N (1Output

    • For each line of input produce one line of output. This line contains the value of G for the corresponding N. The value of G will fit in a 64-bit signed integer.

      Example

      Input:
      10
      100
      200000
      0
      
      Output:
      67
      13015
      143295493160
      
      Time limit has been changed. Some AC solutions get TLE
      

      Added by:Phenomenal
      Date:2009-02-16
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ACM World Final Warm up 1 - 2008









      SPOJ Problem Set (classical)

      3872. Party At School

      Problem code: VPARTY


      Today there is a party at school. N girls and M boys attend this party. The principal wants to give some presents to the girl and he decides to make the boy do that. Each boy has told the principal the name of the two girls that he wants to give the present to so the principal wants the form teacher to choose some boys to do that. However, he is short in cash now so he wants the number of boys selected is minimum but he also wants all the girls to have at least one present. If you select a boy, then he will give the presents to both of the girls he has chosen.

      Input

      The first line contains two integers N and M (2 ≤ N ≤ 1000, 1 ≤ M ≤ 1000) which is the number of the girls and boys.

      The i-th line of the following M lines contains two integers ai and bi (1 ≤ ai, bi ≤ N) which are the two girls that the i-th boy wants to give present to

      Output

      One single integer number, which is the minimum boys the form teacher should choose.

      Example

      Input:
      3 3
      1 2
      2 3
      1 3
      
      Output:
      2
      

      Added by:Phenomenal
      Date:2009-02-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:IOICAMP









      SPOJ Problem Set (classical)

      3884. When (You Believe)

      Problem code: WHEN

      It's said: there can be miracles, when you believe. The following programming language shows the power of "when". It has a very simple (case insensitive) grammar, shown below:

      PROGRAM := WHEN | PROGRAM WHEN
      WHEN := 'when ' EXPRESSION <ENTER> STATEMENTS 'end when' <ENTER>
      STATEMENTS := STATEMENT | STATEMENTS STATEMENT
      STATEMENT := PRINT | SET
      PRINT := 'print '  EXPRESSION_LIST <ENTER>
      SET := 'set ' ASSIGNMENT_LIST <ENTER>
      EXPRESSION_LIST := EXPRESSION | EXPRESSION_LIST ',' EXPRESSION
      ASSIGNMENT_LIST := ASSIGNMENT | ASSIGNMENT_LIST ',' ASSIGNMENT
      ASSIGNMENT := VARIABLE '=' EXPRESSION
      EXPRESSION := '(' EXPRESSION OP EXPRESSION ')' | VARIABLE | NUMBER 
      OP :=  '<' | '+' | '-' | 'and' | 'or' | 'xor'
      VARIABLE := '$' NOT_DOLLAR_STRING '$'
      NUMBER := DIGIT | NUMBER DIGIT
      DIGIT := '0' | .. | '9'
      NOT_DOLLAR_STRING := any sequence of printable characters (including blanks) 
                           that does not contain a $ symbol.
      

      In the above, any string enclosed in single quotes are to be treated literally. <ENTER> is the end of line.

      In words, Spaces are allowed before or after any literal except inside a number. Spaces are allowed in variable names, and each non-empty sequence of spaces is treated as a single underscore, so the following refer to the same variable:

       
      $Remote Switch#1$ 
      $Remote_Switch#1$ 
      $Remote   switch#1$ 
      

      All numbers appearing in the program will be integers between 0 and 1000000000, inclusive. All variable and literal values are integers between -1000000000 and 1000000000, inclusive. All variables are global and initially zero. The programs you will be tested on will never have an EXPRESSION that evaluates to a value outside of this range. The logical operators evaluate to 0 for false and 1 for true, and treat any nonzero value as true.

      Running the program amounts to executing all the active when clauses until none are active. More specifically, the active list of when clauses is initially empty, then the following steps are repeated:

      • In the order they appear in the program, the conditions of all when clauses that are not currently active are evaluated. If true, the clause is added to the end of the active list, with its first statement marked as "ready". Each active when clause has one "ready" statement.
      • If the active list is empty after this step, the program terminates.
      • The "ready" statement from the "current" when clause (initially the first clause in the active list) is executed.
      • The statement marked as "ready" is advanced, removing the when clause from the active list if this is the last statement in the "current" when clause.
      • The when clause marked as "current" is advanced, cycling to the beginning of the active list if the end is reached.

      In other words, inactive when conditions are evaluated to determine if these clauses are added to the active list. Then one statement (set or print) is executed from the current active when clause. If this is the last statement in that clause, it is removed from the active list. One the next iteration, one statement is executed from the next active when clause, etc.

      A set statement executes all the assignments concurrently, so that

      set $x$=$y$,$y$=$x$
      

      swaps the values of $x$ and $y$. The same variable cannot appear twice on the left hand part of the same set statement (so set $x$=1,$x$=2 is illegal).

      A print statement evaluates and prints the given expressions in the output, separated by commas and followed by a new line. So

      print 1,(2+3)
      

      results in the line

      1,5
      

      in the output.

      Input

      The input consists of a single syntactically correct program. You may assume that the program will not execute more than 100000 set statements and 100000 print statements.

      Output

      Print the output produced by executing the given program. Both the input and output file will not exceed 100KB.

      Example

      Input:
      When ($Mr. Bill$<5)
         Set $mr._bill$=($mr.  bill$+1),$Y$=($Y$+10)
      End When
      When ($mr. Bill$<10)
        Set $MR. BILL$=($mr. bill$+1)
        Print $mr. bill$,$Y$
      End When
      
      Output:
      3,20
      6,40
      7,40
      8,40
      9,40
      10,40
      

      Added by:[Trichromatic] XilinX
      Date:2009-02-17
      Time limit:2s
      Source limit:6666B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Whitney Houston: When You Believe









      SPOJ Problem Set (acm)

      3894. Bouncing Balls

      Problem code: BOBALLS

      Consider a grid having NxM squares. The top left square is (0,0) and the bottom right is (N-1,M-1). Each square in the grid is either occupied by a platform or has a number written on it. Two balls are released from the top of the grid (from locations (0,Y1) and (0,Y2), 0 <= Y1,Y2 < M). Each ball falls down vertically, unless either it falls down the bottom row, or encounters a platform beneath. When the ball encounters a platform beneath, it rolls either to the left or to the right, each with an equal probability. The score obtained by a ball is the sum of the numbers on the squares that it passes (including the starting square). However, if both the balls pass over the same square, points corresponding to that square are obtained only once, and not twice. Your goal is to choose Y1 and Y2 such that the expected score obtained by the two balls is maximized. For example, consider the grid below : (P reprsents a platform)

      N = 6, M = 6
      112214
      211243
      30PPP2
      423378
      1P9753
      220102
      

      Here, dropping a ball from position (0,3) could result in one of the following three scores :

      1) 2 + 2 + 1 + 1 + 0 + 2 + 4 + 1 + 2 = 15 
      2) 2 + 2 + 1 + 1 + 0 + 2 + 3 + 9 + 0 = 20
      3) 2 + 2 + 4 + 3 + 2 + 8 + 3 + 2 = 26
      

      The expected score is (considering only 1 ball) :

      1/2*(1/2*(15) + 1/2*(20)) + 1/2*(26)

      Input

      The first line contains the number of test cases.

      The first line for each test case consists of N and M.

      Lines 2..N+1 for each test case consist of M characters each. Each character is either a digit from 0 to 9, or the letter 'P'.

      Output

      The maximum expected score accurate upto 4 decimal places.

      Example

      Input:
      4
      5 5
      53214
      53214
      53214
      54214
      53214
      5 5
      00000
      0P0P0
      00000
      01P20
      00000
      5 5
      09090
      0P0P0
      00000
      01P20
      00000
      6 6
      112214
      211243
      30PPP2
      423378
      1P9753
      220102
      
      
      Output:
      45.0000
      2.2500
      19.3125
      35.5000
      
      

      Constraints

      Dataset 1: 1 <= number of test cases <= 100

      3 <= N,M <= 100

      All possible paths from the top will eventually lead to the ball falling from the bottom. There will be no "rebounds" possible. If there is a 'P' on square (x,y), there will not be a 'P' on squares (x-1,y-1) or (x-1,y+1) or (x+1,y-1) or (x+1,y+1). Also, platforms will not occur on the boundaries of the grid. Thus, the X coodinate of a platform will never be 0 or N-1, and the Y coordinate will never be 0 or M-1. The test case was generated to guarantee that any answer with absolute error in 1e-9 will got accepted. Time limit: 7s


      Added by:Race with time
      Date:2009-02-19
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Code Craft 09









      SPOJ Problem Set (classical)

      3920. Lucius Dungeon

      Problem code: BYTESE1


      LUCIUS’ DUNGEON (5 points) There are a set of rooms in a dungeon, arranged in an M × N rectangular grid. In one of the rooms, evil Lucius Malfoy has imprisoned Hermione, owing to his hatred towards the mudbloods. The noble Harry potter is on his way to rescue Hermione. Harry potter starts in the room at the top left corner of the grid, which is labeled (1,1). Each room contains some guards. It takes some time for Harry potter to kill all the guards in the room he is in. The time taken to kill the guards varies from room to room. Once he has killed all the guards in a room, he can move on to any one of its neighbors by going left, right, up or down, provided, of course, that there is a neighboring room in the corresponding direction. He cannot move diagonally.
      Lucius Malfoy, knowing that Harry Potter is on his way, has set a time bomb that will kill Hermione after T seconds. You will be given the position of Hermione, the time left for the bomb to go off and the time it takes for Harry to kill the guards in each of the rooms in the dungeon. Your task is to determine if it is possible for Harry to reach Hermione and save her by defusing the bomb before the T seconds expire. For example, suppose the dungeon is described by the following grid of numbers where the numbers start from (1,1):
      2 3 2
      2 5 1
      5 3 1
      3 1 1
      The number at position (i,j) indicates the time taken for Harry Potter to overpower the guards in room (i,j). Suppose Hermione is in the room at position (4,2). If T = 10. There is no way Harry Potter can reach Hermione in time. However, if M = 15, Harry Potter can reach Hermione with 4 seconds to spare, as follows. Starting from (1,1), he moves right to (1,2) and then (1,3), comes down all the way to (4,3) and then moves to (4,2). This takes 11 seconds (note that he must also overpower the guard in the room where Hermione is incarcerated). You can check that he cannot reach Hermione with more than 4 seconds to spare by any route.
      Note: If Harry reaches Hermione at exactly ‘T’ seconds from the start then the answer is “YES” with 0 seconds to spare.

      Input

      The first line consists of the number of test cases K (1<=K<=20). In each test case, the first line contains two integers M and N indicating the number of rows and columns in the rectangular dungeon(1 ≤ M,N≤ 100). Next M lines contain N integers (single digits only). The jth integer on ith line is the time taken to overpower the guards at room (i,j). The last line in each test case, contains three integers a, b and T, where (a,b) is the position of the cell where Hermione is held and T is the amount of time before the bomb goes off.

      Output

      For each of the test case, if it is not possible for Harry Potter to save Hermione then print NO. Otherwise, print two lines. The first line should say YES. The second line should contain a single integer indicating the maximum possible time to spare when Harry Potter rescues the Hermione.

      Example

      Input:
      2
      4 3 
      2 3 2
      2 5 1
      5 3 1
      3 1 1
      4 2 15
      2 2
      1 2
      1 1
      2 2 2
      
      Output:
      YES
      4
      NO
      

      Added by:Paritosh Aggarwal
      Date:2009-02-21
      Time limit:1s-8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









      SPOJ Problem Set (classical)

      3921. The Great Ball

      Problem code: BYTESE2


      The Great Ball (5 points) Hogwarts has organized The Great Ball to welcome the schools participating in the Triwizard Tournament. The ball is being held in the Great Hall and The Weird Sisters have been called to play the band. The students drift in to dance and then go out when they get tired. Hagrid is stationed at the gate and is noting down the time at which people enter and leave the hall. At the end of the day, he wonders what the maximum number of dancers was during the course of the ball. For convenience, he writes down for each person entering, the number of minutes from the start of the ball at which the person entered and left. The door of the hall is narrow, so at any time, either one person can enter or one person can exit, but not both. For example, suppose the observations noted down by Hagrid are the following:
      Serial NoEnters atLeaves at
      117
      224
      369
      438
      5510
      Each line denotes the entry time and exit time of one person. (The identity of the person is not important - the same person may enter and leave many times. For instance, in the example, it might well be that the entries and exits recorded at serial no. 2 & 5 refer to the same person). In this example, the maximum size of the dancers during the ball was 4. This was achieved between time 6 & 7. Hagrid is not good at Math so he requires your help. Your task is to read the list of entry and exit times and compute the maximum number of dancers during the ball.

      Input

      The first line is a single integer, T (1<=T<=100), which is the number of test cases. For each of the test case, the first line contains a single integer N, (1<=N<=100), the number of entries and exits recorded. This is followed by N lines. Each of these lines consists of two integers, separated by a space, describing the entry and exit time of that person. The entry and exit times are guaranteed to be distinct, and the entry time will be less than the exit time. The constraint on entry and exit times is 10000000.

      Output

      A total of T lines each of them containing a single integer, denoting the maximum number of dancers during the ball.

      Example

      Input:
      1
      5
      1 7
      2 4
      6 9
      3 8
      5 10
      
      Output:
      4
      

      Added by:Paritosh Aggarwal
      Date:2009-02-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









      SPOJ Problem Set (classical)

      3922. Mystical River

      Problem code: BYTESM1


      Harry Potter was punished for his impudence by Snape and was sent to the forbidden forest for detention. He has now lost his way amidst the forest. He has come across 3 mystical rivers flowing in his way to the school but he is not sure which river does he have to cross. Alongside each mystical river are stones after every meter with a number written on them. The numbers start with 1, 3 and 9 respectively for the three rivers. The number on a stone is equal to the no. on the previous stone plus the sum of its digits. For example, if one no. is 403 then the next no. is 403+4+0+3=410, the next no. is 410+4+1+0=415 and so on. Harry calls this a ‘stone river’. Harry knows that he has to cross at the stone number which is part of the stone river of the number he remembers. He has to now find the point of intersection of the stone river generated by the no. ‘N’ that he remembers, with the rivers of 1 or 3 or 9. Your task is to find which mystical river intersects the stone river generated by Harry’s number. Also find the point of intersection at which Harry can cross the mystical river. For example, if Harry remembers that he has to cross at the stone number which is part of the stone river of 29 then he has to cross at the stone number 107 which is also in the river of number 1. Stone river of 29: 29,40,44,52,59,73,83,94,107,…. River of 1: 1,2,4,8,16,23,28,38,49,62,70,77,91,101,103,107,…. Both the rivers meet at 107 and hence Harry has to cross at stone number 107. It is possible that the stone river might intersect with more than one of the mystical rivers. In that case, output the least intersection number.

      Input

      The first line consists of a single integer ‘T’ (1<=T<=50) which is the total number of test cases. Each of the next T lines consist of a single integer ‘N’ (1<=N<=99999999) which is the number that Harry remembers.

      Output

      A total of T lines, where each line consists of two integers separated by a space. The first integer represents the river out of 1, 3 and 9 which intersects with the stone river of ‘N’. The second integer represents the stone number at which Harry can cross.

      Example

      Input:
      2
      29
      42
      
      Output:
      1 107
      3 111
      

      Added by:Paritosh Aggarwal
      Date:2009-02-21
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:British Informatics Olympiad, 1999









      SPOJ Problem Set (classical)

      3923. Philosophers Stone

      Problem code: BYTESM2

      One of the secret chambers in Hogwarts is full of philosopher’s stones. The floor of the chamber is covered by h × w square tiles, where there are h rows of tiles from front (first row) to back (last row) and w columns of tiles from left to right. Each tile has 1 to 100 stones on it. Harry has to grab as many philosopher’s stones as possible, subject to the following restrictions:

      • He starts by choosing any tile in the first row, and collects the philosopher’s stones on that tile. Then, he moves to a tile in the next row, collects the philosopher’s stones on the tile, and so on until he reaches the last row.
      • When he moves from one tile to a tile in the next row, he can only move to the tile just below it or diagonally to the left or right.
      Given the values of h and w, and the number of philosopher’s stones on each tile, write a program to compute the maximum possible number of philosopher’s stones Harry can grab in one single trip from the first row to the last row.

      Input

      The first line consists of a single integer T, the number of test cases. In each of the test cases, the first line has two integers. The first integer h (1<=h<=100) is the number of rows of tiles on the floor. The second integer w (1<=w<=100) is the number of columns of tiles on the floor. Next, there are h lines of inputs. The ith line of these, specifies the number of philosopher’s stones in each tile of the ith row from the front. Each line has w integers, where each integer m (0<=m<=100) is the number of philosopher’s stones on that tile. The integers are separated by a space character.

      Output

      The output should consist of T lines, (1<=T<=100), one for each test case. Each line consists of a single integer, which is the maximum possible number of philosopher’s stones Harry can grab, in one single trip from the first row to the last row for the corresponding test case.

      Example

      Input:
      1
      6 5
      3 1 7 4 2
      2 1 3 1 1
      1 2 2 1 8
      2 2 1 5 3
      2 1 4 4 4
      5 2 7 5 1
      
      Output:
      32 	
      
      //7+1+8+5+4+7=32
      

      Added by:Paritosh Aggarwal
      Date:2009-02-21
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









      SPOJ Problem Set (classical)

      3924. Filchs Dilemna

      Problem code: BYTESH1


      Filch’s Dilemma (15 points) Argus Filch, the caretaker of Hogwarts, has been given the task to carpet the way to Hogwarts through the grounds. The way is 2 units wide and ‘N’ units long. He has only two types of carpets available, one is 1 unit wide and 2 units long and the other one is L shaped, having 3 square units. Here are their pictures:

      Filch can rotate the carpets when he lays them and has an infinite supply of both types of carpets. As Filch is a squib he cannot magically arrange the carpets and has to resort to logic to find out all possible ways of carpeting the way. He wishes to calculate the number of different ways of carpeting the way.
      For instance, a 2x3 way can be carpeted in 5 different ways as follows:


      Notice that both types of carpets can be used simultaneously. Consider, for instance the following way of carpeting a 2x4 way:


      Given N, you have to help Filch determine the number of ways to carpet the way of size 2XN. Since this number may be very large, it is sufficient to report the last four digits of the answer. For instance the number of ways to carpet a 2x13 way is 13465. Your program should just print 3465. If the answer is in 4 digits or less it should print the entire answer. For example, if N=3 you should print 5.

      Input

      The first line of the input consists of a single integer T(1<=T<=100). Each of the next T lines consists of a single integer N (1<=N<=1000000), indicating the size of the way.

      Output

      For each test case, output the last four digits of the number of ways of carpeting the 2xN way. If the answer involves fewer than 4 digits, print the entire number.
      Important Update - If the output of last four digits has leading zeros, print the output without the leading zeros

      Example

      Input:
      2
      3
      13
      
      Output:
      5
      3465
      

      Added by:Paritosh Aggarwal
      Date:2009-02-21
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









      SPOJ Problem Set (classical)

      3999. FROGGER

      Problem code: FROGGER

      “Frogger” was one of the first really popular arcade games after it was introduced by SEGA in 1981. The game consists of helping a frog cross a multi-lane motorway without getting run over by a car. You are given a view of an n-lane motorway where each lane consists of m different spaces that can either be empty or be occupied by a car. On each side of the motorway is a curb on which the frog can move freely. In the traffic lanes the frog can only move on the spaces not occupied by cars. The motorway is constructed in such a way that the direction in which the cars travel alternates between the lanes, with cars in the first lane (the one closest to the starting point of the frog) moving to the right. The cars never switch lanes and only move one step forward in each turn. To ensure a steady supply of traffic, a car that reaches the boundary of its lane is reentered at the opposite end of its lane. In one turn of the game all the cars move one step in their assigned direction while the frog can either move one step to the right or to the left, or one step up or down (between lanes or between the curb and the adjoining lane), or it can stand still. Contrary to the cars the frog cannot “wrap-around” i.e. move in one step between the first and last position of a lane or a curb. The frog and the cars move simultaneously. Thus the frog can move to a space given that there will be no car on it in the next round. If the frog is on the same space at the same time as a car it is run over and dies. Note that the frog can jump over an adjacent approaching car in the same lane as itself. Your job is to write a computer program that will calculate the minimum number of turns needed for the frog to get from its starting position on the curb to its final position on the curb on the other side of the road or to determine that this is not possible within a given number of rounds.

      Input

      First there will be a line containing the number of scenarios you are asked to help the frog in. For each scenario there will first be a line containing a positive integer x <= 10^5 giving the maximum number of rounds that can be used. The next line contains the number of lanes n, 1 <= n <= 20, and the length of each lane m, 1 <= m <= 50. Each of the next n + 2 lines will contain a string of m characters. The character X indicates a car, the character O (letter O) indicates a free space, the character F gives the starting position of the frog, and the character G gives the final destination of the frog. The first line indicates the destination curb, consisting of O’s and exactly one G while the last line gives the starting curb consisting of O’s and exactly one F, while the intermediate lines each represent one lane of the motorway.

      Output

      The output will be one line per scenario, either giving the minimum number of turns needed before the frog can get from its starting position to the final position without getting run over by a car or a statement indicating that this was not possible within the maximum number of allowed turns.

      Example

      Input:
      2
      10
      4 4
      OOGO
      XXOO
      XOOX
      XXOO
      XXOO
      OOFO
      2
      2 2
      OG
      XX
      OO
      FO
      
      Output:
      The minimum number of turns is 9.
      The problem has no solution.
      

      Added by:Fabio Avellaneda
      Date:2009-03-01
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:I maratón interuniversitaria del circuito Redis - Acis. Sedes: Politécnico - Javeriana









      SPOJ Problem Set (classical)

      4000. GALLUP

      Problem code: GALLUP

      Often, we see results of gallups, like this: Prefer red: 3.5% Prefer green: 4.5% Prefer yellow: 22.0% Prefer blue: 70.0% and you begin to wonder: how many people did they really ask? If the numbers are simple, like 20%, 40%, and 40%, you know that they asked 5 people (or 10, or 15, or more, but we are interested in the minimum number of people). Your task is to write a program that reads sets of percentages and calculates the smallest number of people that could produce the given percentages. We know that this number is always less than 10 000.

      Input

      The input is a set of percentages. Each set is on a line of its own. Every line starts with an integer n (0 <= n <= 20) giving the number of percentages in the set. If n > 0, the percentages follow as n numbers; these numbers may have 0–5 decimals, and all percentages in a set have the same number of decimals. (If there are no decimals, there is no decimal point.) The percentages always add up to about 100% as there may be small rounding errors. Numbers are rounded when digits are removed; they are rounded upwards if the first removed digit is 5 or more. Thus, 4.472 is rounded to 4.47, 4.5, or 4, depending on how many digits you want.

      Output

      For each set of data, print a line starting with “Case i :”, where “i” is the data set’s number. Then follows a space and an integer giving the computed number of people. If no legal answer in the range 1–9999 exists, print “error” instead of the number.

      Example

      Input:
      3 20 40 40
      3 33.3 33.3 33.3
      2 33 67
      1 100.0000
      4 3.75 4.25 22.00 70.00
      2 49 51
      2 50 51
      2 49 50
      0
      
      Output:
      Case 1: 5
      Case 2: 3
      Case 3: 3
      Case 4: 1
      Case 5: 400
      Case 6: 35
      Case 7: 200
      Case 8: error
      

      Added by:Fabio Avellaneda
      Date:2009-03-01
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:I maratón interuniversitaria del circuito Redis - Acis. Sedes: Politécnico - Javeriana









      SPOJ Problem Set (classical)

      4003. Subway planning

      Problem code: SUBWAYPL


      The government in a foreign country is looking into the possibility of establishing a subway system in its capital. Because of practical reasons, they would like each subway line to start at the central station and then go in a straight line in some angle as far as necessary. You have been hired to investigate whether such an approach is feasible. Given the coordinates of important places in the city as well as the maximum distance these places can be from a subway station (possibly the central station, which is already built), your job is to calculate the minimum number of subway lines needed. You may assume that any number of subway stations can be built along a subway line.
      Figure 1: The figure above corresponds to the first data set in the example input.

      subway example

      Input

      The first line in the input file contains an integer N, the number of data sets to follow. Each set starts with two integers, n and d (1 <= n <= 500, 0 <= d < 150). n is the number of important places in the city that must have a subway station nearby, and d is the maximum distance allowed between an important place and a subway station. Then comes n lines, each line containing two integers x and y (−100 <= x, y <= 100), the coordinates of an important place in the capital. The central station will always have coordinates 0, 0. All pairs of coordinates within a data set will be distinct (and none will be 0, 0).

      Output

      For each data set, output a single integer on a line by itself: the minimum number of subway lines needed to make sure all important places in the city is at a distance of at most d from a subway station.

      Example

      Input:
      2
      7 1
      -1 -4
      -3 1
      -3 -1
      2 3
      2 4
      2 -2
      6 -2
      4 0
      0 4
      -12 18
      0 27
      -34 51
      
      Output:
      4
      2
      

      Added by:Fabio Avellaneda
      Date:2009-03-01
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:I maratón interuniversitaria del circuito Redis - Acis. Sedes: Politécnico - Javeriana









      SPOJ Problem Set (easy)

      4004. Exploding CPU

      Problem code: CPU

      The well known hardware manufacturing company Processors for Professors is about to release a highly specialized CPU with exceptional functionality in, amongst other areas, number theory. It has, for example, an instruction PFACT that takes one parameter and returns all prime factors of that parameter, with an outstanding execution speed. It has, however, one considerable problem. The scientists at the testing lab has just found out that the PFACT instruction for some special input values freaks out and makes the entire processor explode. Even though this could be an amusing effect, it is not the way it was intended to work. The skilled mathematicians have, by trial and error, found that the explosive numbers all share the same interesting number theoretic properties, which might be of help when troubleshooting. An explosive number is a number x = p0p1p2 . . . pn where all pis are distinct prime numbers such that pi = Api−1 +B for i = 1, 2, . . . , n. n >= 3, p0 = 1. A and B are always integers, and might be different for different explosive numbers. For example, the processor will explode when factorizing the number 4505, because 4505 = 1 · 5 · 17 · 53 and 5 = 3 · 1 + 2, 17 = 3 · 5 + 2 and 53 = 3 · 17 + 2 and the numbers 5, 17 and 53 are all prime numbers. In this case A = 3 and B = 2. You are kindly asked to write a computer program that will aid this company in estimating the impact of the errors, by calculating the amount of explosive numbers that exists within a given range of integers.

      Input

      The input starts with a row containing the number 0 <= N <= 100 of test cases that will follow. For each test case, there will be one row containing two integers, xL and xH separated by a single space. These numbers are such that 0 <= xL <= xH <= 2,000,000,000.

      Output

      For each test case, output the number of explosive numbers that exist in the range xL <= x <= xH.

      Example

      Input:
      2
      4505 4505
      0 5000
      
      Output:
      1
      5
      

      Added by:Fabio Avellaneda
      Date:2009-03-01
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6 PYTH 3.2.3 n
      Resource:I maratón interuniversitaria del circuito Redis - Acis. Sedes: Politécnico - Javeriana









      SPOJ Problem Set ()

      4033. Phone List

      Problem code: PHONELST

      Phone List Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers:

      • Emergency 911

      • Alice 97 625 999

      • Bob 91 12 54 26

      In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.

      Input

      The first line of input gives a single integer, 1 <= t <= 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.

      Output

      For each test case, output “YES” if the list is consistent, or “NO” otherwise.

      Example

      Input:
      2
      3
      911
      97625999
      91125426
      5
      113
      12340
      123440
      12345
      98346
      
      Output:
      NO
      YES
      

      Added by:Andres Galvis
      Date:2009-03-08
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Nordic Collegiate Programming Contest 2007









      SPOJ Problem Set (classical)

      4036. Cuckoo Hashing

      Problem code: CUCKOO

      One of the most fundamental data structure problems is the dictionary problem: given a set D of words you want to be able to quickly determine if any given query string q is present in the dictionary D or not. Hashing is a well-known solution for the problem. The idea is to create a function h : Σ → [0..n − 1] from all strings to the integer range 0,1,..,n − 1, i.e. you describe a fast deterministic program which takes a string as input and outputs an integer between 0 and n−1. Next you allocate an empty hash table T of size n and for each word w in D, you set T[h(w)] = w. Thus, given a query string q, you only need to calculate h(q) and see if T[h(q)] equals q, to determine if q is in the dictionary. Seems simple enough, but aren’t we forgetting something? Of course, what if two words in D map to the same location in the table? This phenomenon, called collision, happens fairly often (remember the Birthday paradox: in a class of 24 pupils there is more than 50% chance that two of them share birthday). On average you will only be able to put roughly √n-sized dictionaries into the table without getting collisions, quite poor space usage!

      A stronger variant is Cuckoo Hashing. The idea is to use two hash functions h1 and h2. Thus each string maps to two positions in the table. A query string q is now handled as follows: you compute both h1(q) and h2(q), and if T[h1(q)] = q, or T[h2(q)] = q, you conclude that q is in D. The name “Cuckoo Hashing” stems from the process of creating the table. Initially you have an empty table. You iterate over the words d in D, and insert them one by one. If T[h1(d)] is free, you set T[h1(d)] = d. Otherwise if T[h2(d)] is free, you set T[h2(d)] = d. If both are occupied however, just like the cuckoo with other birds’ eggs, you evict the word r in T[h1(d)] and set T[h1(d)] = d. Next you put r back into the table in its alternative place (and if that entry was already occupied you evict that word and move it to its alternative place, and so on). Of course, we may end up in an infinite loop here, in which case we need to rebuild the table with other choices of hash functions. The good news is that this will not happen with great probability even if D contains up to n/2 words

      Input

      On the first line of input is a single positive integer 1 ≤ t ≤ 50 specifying the number of test cases to follow. Each test case begins with two positive integers 1 ≤ mn ≤ 10000 on a line of itself, m telling the number of words in the dictionary and n the size of the hash table in the test case. Next follow m lines of which the i:th describes the i:th word di in the dictionary D by two non-negative integers h1(di) and h2(di) less than n giving the two hash function values of the word di. The two values may be identical.

      Output

      For each test case there should be exactly one line of output either containing the string “successful hashing” if it is possible to insert all words in the given order into the table, or the string “rehash necessary” if it is impossible.

      Example

      Input:
      2
      3 3
      0 1
      1 2
      2 0
      5 6
      2 3
      3 1
      1 2
      5 1
      2 5
      Output:
      successful hashing
      rehash necessary
      

      Added by:Andres Galvis
      Date:2009-03-09
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Nordic Collegiate Programming Contest 2007









      SPOJ Problem Set (classical)

      4060. A game with probability

      Problem code: KPGAME

      Alice and Bob play the following game. First, they collect N small stones and put them together in one pile. After that, they throw a coin one by one. Alice starts first. If a player throws heads then he takes exactly one stone from the pile. In case of tails he don't do anything. The one who takes the last stone wins. For each player, his skill of throwing a coin is known (to everyone, including himself and his opponent). More precisely, if Alice wants to throw some specific side of the coin, she always succeeds with probability P. The same probability for Bob is Q. You are to find probability that Alice will win the game if both guys play optimally.

      Input

      Input starts with a line containing one integer T - a number of test cases (1 <= T <= 50). Then T test cases follow. Each of them is one line with three numbers N, P, and Q separated with a space (1 <= N <= 99999999, 0.5 <= P, Q <= 0.99999999). P and Q have not more than 8 digits after decimal point.

      Output

      For each test case output one line with a probability that Alice will win the game. Your answer must be precise up to 10^-6.

      Example

      Input:
      1
      1 0.5 0.5
      
      Output:
      0.666666667
      

      Added by:Pavel Kuznetsov
      Date:2009-03-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Vologda 2009









      SPOJ Problem Set (classical)

      4069. Morphing is Fun

      Problem code: MORPH


      Morphic is a tree that grows very rapidly, bringing happiness to its owner. It has a single trunk consisting of a number of cells stacked one on top of another. Each cell has one of n possible colors which determine the way it mutates during the night, while nobody can see it. Florists denote these colors by the first n small letters of the English alphabet and know exactly into how many cells, and of what colors, a cell of each color divides. In fact, they have wrote their knowledge down simply with n nonempty words, each word representing the resulting sequence of colors.

      A seed of a Morphic has a single cell of color a and is rooted firmly in the ground. As long as the Morphic is still alive, each night all its cells simultaniously morph according to the aforementioned rules, possibly causing an exponential growth because each new cell is of the same size as the original one. For example, if rules say that a becomes ab, and b becomes ca, then after two nights a seed will evolve to a trunk consisting of 4 cells: abca.

      Therefore the top of a Morphic is usually hidden in clouds. The only way to tell if it is still alive is to check if visible part of the trunk is changing colors. In order to do so, one can build enormously high (yet still of constant height) tower, and watch from its top a fixed fragment of the trunk.

      As you can easily see, it is either sufficient to observe first k cells from the bottom for some fixed k, or no matter how high the tower is, you will not be able to tell for sure if a Morphic died. The latter happens when for every k, rules cause the k-th cell to eventually stop changing colors, even though the tree is still alive and mutating.

      To prevent waste of money on building such enormous towers, you are to write a program that determines if it is possible to monitor health of a Morphic.

      Input

      The input contains several Morphics descriptions. The first line contains the number of descriptions t (t <= 10000) that follow. Each of them begins with the number of colors n (1 <= n <= 26). Next n lines contain the rules by which the Morphic grows. The i-th one describes the sequence of colors in bottom-up order obtained from a single cell of i-th color. Each line contains at most 100 lowercase English letters.

      Output

      For each test case output one line containing YES if building of a tower is pointless (as in: YES, we can save money!). Otherwise output NO.

      Example

      Input:
      4
      2
      ab
      a
      3
      ba
      c
      c
      3
      ba
      c
      b
      3
      bbbbbbbbbbbbbbb
      ccccccccccccccc
      c
      
      Output:
      YES
      YES
      NO
      YES
      
      Warning: enormous input/output data, be careful with certain languages
      Added by:[Trichromatic] XilinX
      Date:2009-03-17
      Time limit:13s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:ACM Central European Programming Contest, Wroc³aw 2008









      SPOJ Problem Set (classical)

      4070. Two Professors

      Problem code: TWOPROF


      There are two professors at the great Academy of X that really do not get along with each other. In order not to reveal their names, we will call them 1 and 2. The Academy employs exactly n professors, each of them has to give exactly one lecture. As their schedules are rather tight (they are professors, remember?), the starting and the ending time of each lecture is already fixed. However, it is not yet fixed where each lecture will take place. Obviously, it is impossible to schedule two lectures in the same room if their durations overlap; on the other hand, it is possible if one of them starts exactly at the same time that the other one ends. Your tasks is to find the minimal number of rooms allowing to arrange all the lectures. But know that professors 1 and 2 hate each other so much that they will never give their lectures in the same room.

      Input

      The input contains several test cases. The first line contains the number of test cases t (t <= 250). Each test begins with a line containing the number of professors n (2 <= n <= 100000). Next n lines follow, i-th of which contains two integers starti and endi (0 <= starti < endi <= 1000000000), the starting and the ending time of the lecture that the i-th professor gives, respectively.

      Output

      For each test case output the minimal number of rooms necessary to schedule all the lectures.

      Example

      Input:
      4
      2
      0 10
      10 20
      3
      0 10
      10 20
      10 20
      5
      4 14
      3 13
      2 12
      1 11
      0 10
      4
      0 10
      10 20
      20 30
      30 40
      
      Output:
      2
      2
      5
      2
      

      Warning: enormous input/output data, be careful with certain languages

      Note: The input is too large, so we have 4 input files and the total time limit is 17 seconds.


      Added by:[Trichromatic] XilinX
      Date:2009-03-17
      Time limit:17s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:ACM Central European Programming Contest, Wroc³aw 2008









      SPOJ Problem Set (classical)

      4103. Extend to Palindrome

      Problem code: EPALIN

      Your task is, given an integer N, to make a palindrome (word that reads the same when you reverse it) of length at least N (1 <= N <= 100,000). Any palindrome will do.

      Easy, isn't it? That's what you thought before you passed it on to your inexperienced team-mate. When the contest is almost over, you find out that that problem still isn't solved. The problem with the code is that the strings generated are often not palindromic. There's not enough time to start again from scratch or to debug his messy code.

      Seeing that the situation is desperate, you decide to simply write some additional code that takes the output and adds just enough extra characters to it to make it a palindrome and hope for the best. Your solution should take as its input a string and produce the smallest palindrome that can be formed by adding zero or more characters at its end. The input string will consist of only upper and lower case letters.

      Example

      Input:
      
      aaaa
      abba
      amanaplanacanal
      xyz
      
      Output:
      
      aaaa
      abba
      amanaplanacanalpanama
      xyzyx
      
      Note:
      1. All palindromes are considered case-sensitive (i.e. 'Aa' is not a palindrome).
      2. Large I/O. Be careful in certain languages.

      Added by:Muntasir Azam Khan
      Date:2009-03-22
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:Own problem, used in Next Generation Contest 5









      SPOJ Problem Set (classical)

      4110. Fast Maximum Flow

      Problem code: FASTFLOW

      Given a graph with N (2 ≤ N ≤ 5,000) vertices numbered 1 to N and M (1 ≤ M ≤ 30,000) undirected, weighted edges, compute the maximum flow / minimum cut from vertex 1 to vertex N.

      Input

      The first line contains the two integers N and M. The next M lines each contain three integers A, B, and C, denoting that there is an edge of capacity C (1 ≤ C ≤ 109) between nodes A and B (1 ≤ A, B ≤ N). Note that it is possible for there to be duplicate edges, as well as an edge from a node to itself.

      Output

      Print a single integer (which may not fit into a 32-bit integer) denoting the maximum flow / minimum cut between 1 and N.

      Example

      Input:
      4 6
      1 2 3
      2 3 4
      3 1 2
      2 2 5
      3 4 3
      4 3 3
      
      Output:
      5
      

      Viewing the problem as max-flow, we may send 3 units of flow through the path 1 - 2 - 3 - 4 and 2 units of flow through the path 1 - 3 - 4. Viewing the problem as min-cut, we may cut the first and third edges. Either way the total is 5.

      Note: see also http://www.spoj.pl/problems/MATCHING/.


      Added by:Neal Wu
      Date:2009-03-25
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS









      SPOJ Problem Set (classical)

      4142. Ellipse

      Problem code: ELLIPSE

      Given 5 points on a ellipse, calculate the area of the ellipse. We accept solutions with absolute error less than 10-6 or relative error less than 10-9.

      Input

      Many test cases. Each contains a line with 10 integers with absolute value less than 1000 - the X and Y coordinates of the 5 points, respectively.

      Input terminates by EOF. Note that there can be extra spaces in a single line.

      Output

      Each line contains a single float-point number - the area of the corresponding ellipse, or "IMPOSSIBLE" if the ellipse doesn't exist or can't be unique determined.

      Example

      Input:
      6 1 3 2 -2 -3 -3 -2 1 6
      7 -3 2 7 6 3 5 5 -2 -9
      
      Output:
      IMPOSSIBLE
      157.079633
      

      Note: You can click on "Wrong Answer" to get further information.

      Note: Judge is slightly modified to avoid some precision problems.


      Added by:[Trichromatic] XilinX
      Date:2009-03-27
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Classical Problem, description by Blue Mary









      SPOJ Problem Set ()

      4157. Domino

      Problem code: DOMINO2

      You have an nxm rectangle, some cells have some obstacles in. A domino piece is a 1x2 or 2x1 rectangle. You're going to place some domino pieces in this rectangle so that there's no empty cell is covered more than once and no cell with obstacles is covered. For some unknown reason, you have to ensure there's at least one piece covering some cell in row i and some cell in row i+1 at the same time for all i in 1..n-1. Similarly there's at least one piece covering some cell in column i and column i+1 for all i in 1..m-1. Your task is to count the number of different valid domino covering.

      Input

      The first line of the input contains two integer numbers n, m (1≤n,m≤15).

      The following n lines describe the rectangle. Each line contains m characters. The j-th character of line i+1 may be either a 'x'(ASCII code 120), representing obstacles in cell (i, j), or a '.'(ASCII code 46), representing an empty cell.

      Output

      One number, representing the number of different valid domino placing.

      Since the number could be quite large, output the answer modulo 19901013.

      Example

      Input:
      3 3
      ...
      ...
      ...
      
      Output:
      2
      

      Note

      The 2 different placings are

         112     411
         4.2     4.2
         433     332
      

      Added by:Bin Jin
      Date:2009-03-30
      Time limit:15s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.0.0-8
      Resource:Zhejiang TSC for Chinese National OI 2009









      SPOJ Problem Set (classical)

      4164. A conjecture of Paul Erdõs

      Problem code: HS08PAUL

      In number theory there is a very deep unsolved conjecture of the Hungarian Paul Erdõs (1913-1996), that there exist infinitely many primes of the form x2+1, where x is an integer. However, a weaker form of this conjecture has been proved: there are infinitely many primes of the form x2+y4. You don't need to prove this, it is only your task to find the number of (positive) primes not larger than n which are of the form x2+y4 (where x and y are integers).

      Input

      An integer T, denoting the number of testcases (T≤10000). Each of the T following lines contains a positive integer n, where n<10000000.

      Output

      Output the answer for each n.

      Example

      Input:
      4
      1
      2
      10
      9999999
      
      Output:
      0
      1
      2
      13175
      

      Added by:Robert Gerbicz
      Date:2009-04-05
      Time limit:5s
      Source limit:4096B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:High School Programming League 2008/09









      SPOJ Problem Set (first)

      4166. Four colors

      Problem code: HS08FOUR

      Let there be given n points: P1,P2...,Pn arranged in this order on a line. We would like to color them using four colors: white, black, red, and blue, in such a way that for every three consecutive points it is true that either
      1. the colors of these three points are pairwise distinct, or
      2. the color of some point is white.

      Input

      An integer T, denoting the number of testcases (T<100000). In each line you are given one positive integer ( n<1000000000 ). There are 5 input sets.

      Output

      Find the number of possible colorings of the n points. Since the answer can be very big, output only the answer modulo 1000000007.

      Example

      Input:
      4
      1
      2
      3
      1000

      Output:
      4
      16
      43
      283570349

      Warning: large input/output data, be careful with certain languages

      Warning: A naive algorithm will probably solve only the first input set.


      Added by:Robert Gerbicz
      Date:2009-04-05
      Time limit:1s
      Source limit:4096B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: CLOJ ERL JS PERL 6
      Resource:High School Programming League 2008/09









      SPOJ Problem Set (classical)

      4168. Square-free integers

      Problem code: SQFREE

      In number theory we call an integer square-free if it is not divisible by a perfect square, except 1. You have to count them!

      Input

      First line contains an integer T, the number of test cases (T≤100). The following T lines each contains one positive integer: n, where n ≤ 1014

      Output

      T lines, on each line output the number of (positive) square-free integers not larger than n.

      Example

      Input:
      3
      1
      1000
      100000000000000
      
      Output:
      1
      608
      60792710185947
      
      Warning: A naive algorithm probably not works.
      Added by:Robert Gerbicz
      Date:2009-04-06
      Time limit:20s
      Source limit:2009B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:classic, own input









      SPOJ Problem Set (classical)

      4172. Multiplicative digital root

      Problem code: DROOT

      For an integer find the multiplicative digital root of it! Multiple all nonzero digits of that number and repeat this process until it is only a single digit. We call that digit the multiplicative digital root of the number. For example the multiplicative digital root of n=2009 is 8, because the first iteration is: 2*9=18, the second is 1*8=8, and we stop here.

      Input

      The first line of the input file contains one integer T, the number of test cases. The following T lines each contains a big positive integer: n, where n<1010000

      Output

      Output the mulplicative digital root for each n.

      Example

      Input:
      4
      6
      2009
      555555555
      847938630482747410708417738635300464477112059683336648877683
      
      Output:
      6
      8
      5
      2
      
      Warning: large input data, be careful with certain languages

      Warning: not every languages are available for this task
      Added by:Robert Gerbicz
      Date:2009-04-06
      Time limit:2s
      Source limit:2048B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:DOC AWK C C++ 4.3.2 C++ 4.0.0-8 CLOJ F# GO NODEJS PAS fpc PAS gpc PDF PERL 6 PS PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL TECS TEXT
      Resource:classic, own input









      SPOJ Problem Set (classical)

      4176. A Knightly Pursuit

      Problem code: KPURSUIT

      In chess, game pieces move about an chessboard in a fashion defined by their type. The object of the game is to capture opposing pieces by landing on their squares, and eventually trapping the king piece.

      In our version of the game, we shall use a variable sized board with only 2 pieces on it: A white pawn which moves relentlessly towards the top row of the chessboard one square at a time per move; and a black knight which can move from its current location in any of up to eight ways: two squares up or down and one square left or right, or one square up or down and two squares left or right. The knight must remain on the board at all times; any move that would take it off the board is therefore disallowed. In the diagram below, the knight's position is labelled K and its possible moves are labelled 1 to 8.

      . . . . . . .
      . . 8 . 1 . .
      . 7 . . . 2 .
      . . . K . . .
      . 6 . . . 3 .
      . . 5 . 4 . .
      . . . . . . .

      The pawn moves first; then the knight and pawn alternate moves. The knight tries to land either on the square occupied by the pawn (a win) or on the square immediately above the pawn (a stalemate). If the pawn reaches the top row of the board the game ends immediately and the knight loses (a loss).

      Input

      The first line of input contains a positive integer, n, the number of games to analyze. For each game there are six lines on input:

      r, the number of rows in the chessboard.
      c, the number of columns in the chessboard.
      pr, the row of the starting position of the pawn.
      pc, the column of the starting position of the pawn.
      kr, the row of the starting position of the knight.
      kc, the column of the starting position of the knight.

      All numbers in the input don't exceed 100. (Thanks to Blue Mary for pointing that out).

      The pawn and the knight will have different starting positions. Row 1 is at the bottom of the board and Row r is at the top of the board. Column 1 is at the left and column c is at the right.

      Output

      If the knight can win and, output the minimum number of moves it must make to do so. If the knight cannot win, your program should determine if it can cause a stalemate and, if it can, the minimum number of moves it must make to do so. Finally if the knight cannot win or cause a stalemate, your program should compute the number of moves the knight makes before the pawn wins.

      Example

      Input:
      3
      99
      99
      33
      33
      33
      35
      3
      3
      1
      1
      2
      3
      99
      99
      96
      23
      99
      1
      
      Output:
      Win in 1 knight move(s).
      Stalemate in 1 knight move(s).
      Loss in 2 knight move(s).
      

      Added by:JaceTheMindSculptor
      Date:2009-04-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS
      Resource:Canadian Computing Competition 1999 Senior Question 4









      SPOJ Problem Set (classical)

      4177. Herding

      Problem code: HERDING

      Oh no! A number of stray cats have been let loose in the city, and as the City Cat Catcher, you have been assigned the vital task of retrieving all of the cats. This is an ideal opportunity to test your latest invention, a cat trap which is guaranteed to retrieve every cat which walks into a square-shaped subsection of the city.

      Fortunately, you have the assistance of one of the world's foremost cat psychologists, who has the amazing ability of predicting, given a square subsection of the city, exactly which of the four cardinal directions (north, east, south or west) the cat will head. While this information is handy, you still don't know where all the cats currently are.

      In order to prove the cost-effectiveness of your method to the City it would, of course, be important to minimize the number of traps used.

      Input

      The input will begin with a line consisting of two numbers n and m, separated by a space (1 ≤ n, m ≤ 1000). The city will be an n x m grid of square subsections. The next n lines will each consist of a string of length m, consisting of the letters 'N', 'E', 'S', or 'W', representing north, east, south and west, respectively. (The first character of the first line will be the northwesternmost point.) The direction in the square is the direction which cats will head if they are in that square. The cat psychologist assures you that cats have no interest in leaving the city.

      Output

      Output the minimum number of traps needed.

      Example

      Input:
      3 4
      SWWW
      SEWN
      EEEN
      
      Output:
      2
      

      Added by:JaceTheMindSculptor
      Date:2009-04-07
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS
      Resource:Canadian Computing Competition 2008 Stage 2 Day 2 Problem D









      SPOJ Problem Set (classical)

      4178. Distance on a square lattice

      Problem code: LATTICE

      Let L to be an nXn square lattice, you can consider its points as (x,y), where x and y are integers from the [1,n] interval. And let f(n) to be the expected distance between two not neccesserily distinct points on the lattice. For example f(1)=0 and f(2)=(2 +  2  )/4.

      Input

      There is no input.

      Output

      5000 lines, on the n-th line give the value of f(n) by 2 digits after the decimal point.

      Example

      Input:
      No input.
      
      Output:
      0.00
      0.85
      1.45
      2.01
      2.55
      .
      .
      .
      2607.03
      

      Added by:Robert Gerbicz
      Date:2009-04-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:AWK C++ 4.3.2 CLOJ F# GO PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL TECS TEXT
      Resource:own resource









      SPOJ Problem Set (classical)

      4179. Temptation Island

      Problem code: TEMPTISL

      On Monday, the number of frosh were reduced in half. To further reduce the number of engineers to a manageable number, the following challenge was devised for the second day. Each of the students would have to take this challenge individually.

      Each student would be placed at a vertex of perimeter fence of Waterloo (oh yeah, some background: to keep UofT’s engineering Lady Godiva band out of Waterloo, a fence was erected surrounding the university. The fence just happens to be an N-gon). At some other vertex along the fence would be located a temptation so seductive that no Waterloo student could resist – an extra-credit assignment. The challenge of each student is to go from his starting vertex to the vertex with the prize. There are however 3 rules:

      a) The student can only travel from vertex to vertex (backwards or forwards) along the polygonal fence.

      b) The student has to make contact with exactly K vertices (the vertex he starts at doesn’t count unless he returns to it). The K vertices need not be unique. The final vertex has to be the one with the prize.

      c) If the student cannot reach the prize and make contact with exactly K vertices, he fails the test and is kicked out of the university.

      Of course, no Waterloo student is satisfied with only 1 solution to any problem. Therefore, inevitably, each student determines all ways that he/she can win. Note that there may be no solution to the problem (the astute student has figured out that this will result in a class size of 0 – this is entirely allowable as the variable used to quantify enrollment was incorrectly defined as a whole number instead of a natural number).

      Input

      N K (N, K <= 50)
      A B (A = the starting vertex number, B = destination vertex number)
      -1 -1 terminates input

      Output

      The total number of ways of reaching the destination from the starting point by following the above rules. The total number of ways will be less than 263 - 1. Output 0 if there are no solution.

      Example

      Input:
      8 5
      1 4
      -1 -1
      
      Output:
      6
      

      Added by:JaceTheMindSculptor
      Date:2009-04-08
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS
      Resource:Woburn Challenge 2001









      SPOJ Problem Set (classical)

      4182. Candy (Again)

      Problem code: FCANDY

      You and a friend have a big bag of candy. You want to keep slim and trim, and so you would like to equalize the candy which you are sharing with your friend in terms of calorie count. That is, your task is to divide the candies into two groups such that the number of calories in each group is as close together as possible.

      Input

      The first line of input contains the number of different kinds of candy you have in your bag of candy N (1 ≤ N ≤ 100). On the following N lines, there are pairs of numbers describing each type of candy. The candy description is of the form ki ci where ki is the number of that particular type of candy contained in the bag and ci is the calorie count for each piece of that type of candy. You may assume that 1 ≤ ki ≤ 500 and 1 ≤ ci ≤ 200.

      Output

      Your output is one integer which is the minimum difference of calories between friends

      Example

      Input:
      4
      3 5
      3 3
      1 2
      3 100
      
      Output:
      74
      

      Added by:JaceTheMindSculptor
      Date:2009-04-08
      Time limit:0.5s-9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS
      Resource:Canadian Computing Competition 2008 Stage 2 Question E









      SPOJ Problem Set (classical)

      4185. Cube

      Problem code: CCCCUBE

      Imagine a cube formed from solid interlocking pieces of various shapes. If the pieces are sufficiently intertwined, the only way to separate them would be to cut some of them. We can ask the question, "is the cube stable?" That is, is it physically impossible to separate the cube into 2 or more fragments without deforming and cutting any individual piece?

      Your program must answer this question for a variety of such cubes. The pieces that make up a cube will be specified as follows: divide the cube into a grid of n*n*n miniature cubes, each labelled by a capital letter. Two adjacent (face-sharing) are joined together if and only if they are labelled by the same letter. For instance, the first example cube given consists of 3 solid pieces.

      Input

      Your program will be given the specification of up to 10 different cubes. The first two lines of each specification will consist of the size of that cube, n (1 ≤ n ≤ 10), and a blank line. There will be no spaces in the input. The input will be terminated by a number 0 on a line by itself.

      Output

      For each cube given, in the order specified, print "Yes" if that cube is stable, and "No" if it is not.

      Example

      Input:
      2
      
      AB
      AB
      
      BB
      BA
      
      3
      
      AAA
      BBB
      AAA
      
      AAA
      ABA
      AAA
      
      ABA
      ABA
      ABA
      
      0
      
      Output:
      No
      Yes
      
      

      Added by:Brian Bi
      Date:2009-04-08
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:2003 Canadian Computing Competition Stage 2 - Day 1, Question 3









      SPOJ Problem Set (classical)

      4186. Break a New RSA system

      Problem code: HS08CODE

      Today, Gerrob's RSA company has featured a New RSA cryptosystem: its public key is n, the secret keys are three distinct primes p, q and r, where n=p*q*r. Note that the ordinary RSA uses only 2 primes! Unfortunately some hackers have stolen a DVD from the company. It does not store the secret keys, only some information about the system, namely, the values of:
      φ (n) - Euler's totient function and
      σ (n) - the sum of the divisors.
      Obviously you know also n, because that's public.

      Now, Gerrob's RSA employees are trying to determine if hackers will be able to break the system. Could you help them to answer this question?

      Input

      The first line contains a single integer T, the number of test cases, where T≤ 20000. The following T lines each contains three numbers n, φ (n) and σ (n) in this order. There are 5 input sets.

      Output

      Output T lines, the values of p, q and r in increasing order. It is guaranteed that p, q, r<106.

      Example

      Input:
      4
      30 8 72
      61321 54912 68040
      451464315257 451286179344 451642497600
      91896729624994213 91896040105364880 91897419147616160
      Output:
      2 3 5
      13 53 89
      6397 8039 8779
      231859 574261 690187
      

      Warning: large input/output data, be careful with certain languages

      Warning: A naive algorithm will probably solve only the first input set.


      Added by:Robert Gerbicz
      Date:2009-04-08
      Time limit:0.400s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:High School Programming League 2008/09









      SPOJ Problem Set (first)

      4188. Amazing equality

      Problem code: HS08EQ


      The definition of a perfect number is about 2300 years old. A perfect number is defined as a positive integer which is the sum of its proper positive divisors, that is, the sum of the positive divisors excluding the number itself. What can we get if, in the sum, we replace each divisor by its square? You can prove that there is no such number. But there are many numbers for which the sum of some divisors' squares is equal to n, so n=d12+d22+...+dk2, where d1, d2, ...,dk are distinct (positive) divisors of n. You have to count how many times this happens. For example: the divisors of n=120 are 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120. And there are exactly two amazing equalities:
      120=22+42+102
      120=22+42+62+82

      Input

      The first number is T, denoting the number of test cases (T<1000). T lines follow, each of which contains one positive integer (n<1010).

      Output

      Output T lines, the answer for each n.

      Example

      Input:
      6
      120
      720
      1000
      1200
      92070
      123618780
      
      Output:
      2
      13
      0
      10
      6448
      292
      

      Added by:Robert Gerbicz
      Date:2009-04-09
      Time limit:12s
      Source limit:4096B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: CLOJ ERL JS PERL 6
      Resource:High School Programming League 2008/09









      SPOJ Problem Set (classical)

      4189. Landing

      Problem code: LANDING

      Keep watching the skies! Alien spacecraft are due to land any day now to share all of their advanced programming secrets with us.

      In preparation for this day, you've been asked with preparing a landing pad for our visitors in a given field. Unfortunately, due to enviromental considerations, you will not be permitted to remove any of the trees which currently exist on the field. These trees are of immense scientific research, since they have zero radius and only grow at points with integer co-ordinates. However, this could be a blessing in disguise. For security reasons, the landing pad must be in contact with atleast three trees. Security cameras will be placed at the tops of these trees.

      Alien spacecraft are perfectly circular craft of various sizes, so the landing pad will also be circular. Since it would be polite to warn potential visitors ahead of time if their spacecraft is too large for our landing pad, you must now determine the size of largest circular region that we can place on the field which contacts at least three trees, but does not contain any trees within.

      Input

      The first line of input consists of the number n of trees (3 ≤ n ≤ 100 000). the next n lines will each consist of a pair of integers x and y (-10000 ≤ x, y ≤ 10000), separated by a space, giving the co-ordinates of a tree. You may assume that no two trees are at the same co-ordinates.

      Output

      Output the radius of the largest possible landing pad. If the correct answer is R, you should output number a such that



      The above calculation is used to define an acceptable range or tolerance for the answer you find. You may also assime that r < 109. You may assume there exists at least one landing pad.

      Example

      Input:
      4
      1 1
      1 -1
      -1 -1
      -1 1
      
      Output:
      1.414214




      Added by:JaceTheMindSculptor
      Date:2009-04-09
      Time limit:5s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS
      Resource:Canadian Computing Competition 2008 Stage 2 Day 2 Problem F









      SPOJ Problem Set (classical)

      4197. Dominoes

      Problem code: DOMINOES

      Johnny is playing with some dominoes one afternoon. His dominoes come in a variety of heights and colors.

      Just like any other child, he likes to put them in a row and knock them over.
      He wants to know something: how many pushes does it take to knock down all the dominoes?
      Johnny is lazy, so he wants to minimize the number of pushes he takes.
      A domino, once knocked over, will knock over any domino that it touches on the way down.

      For the sake of simplicity, imagine the floor as a one-dimensional line, where 1 is the leftmost point. Dominoes will not slip along the floor once toppled. Also, dominoes do have some width: a domino of length 1 at position 1 can knock over a domino at position 2.
      For the mathematically minded:
      A domino at position x with height h, once knocked over to the right, will knock all dominoes at positions x+1, x+2, ..., x+h rightward as well.
      Similarly, the same domino knocked over to the left will knock all dominoes at positions x-1, x-2, ..., x-h leftward.

      Input

      The input starts with a single integer N (N ≤ 100000), the number of dominoes, followed by N pairs of integers.
      Each pair of integers represents the location and height of a domino, in that order (0 ≤ location ≤ 109, 0 ≤ height ≤ 109).
      No two dominoes will have the same location.

      Output

      A single integer on a single line: the minimum number of pushes Johnny must make in order to ensure that all dominoes are knocked over.

      Example

      Input:
      6
      1 1
      2 2
      3 1
      5 1
      6 1
      8 3
      Output:
      2
      Explanation
                    |
        |           |
      | | |   | |   |
      1 2 3 4 5 6 7 8
      

      Pushing 1 causes 2 and 3 to fall, while pushing 8 causes 6 to fall and gently makes 5 tip over as well.


      Added by:Brian Bi
      Date:2009-04-10
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Hanson Wang









      SPOJ Problem Set (classical)

      4198. Lego

      Problem code: LEGO


      It's Christmas morning, and you've got what you wanted: a box of Lego™! (Okay, maybe not, but better than nothing)

      Lego is pretty fun to tinker with, and you've decided to build some sort of shape.
      (For the sake of this problem, let's say your shape is basically 2-dimensional - it'll be a slab)

      But once you pick it up, you discover that you didn't plan it properly, and your wonderful shape just falls apart.
      Now, you're planning to build something big, and so you're going to use the computer to help you.
      Write a program, that given the layout of a Lego design, outputs the number of pieces it would break into if picked up.
      (Assume that the bricks bind together perfectly)

      The Legos will be built on a x-y coordinate plane, with (0,0) being the bottom left corner.
      The blocks are flat on your carpet, so a block will never 'fall down'.
      (If you haven't seen a Lego brick before: A Lego brick has grooves on its top that match with notches on the bottom.
      If a groove and a notch bind, the bricks will stay together. See the diagram.
      A brick will bind with another brick securely even if just a single notch touches another groove.

      Input:

      The first line contains N (the number of Lego pieces), 1 ≤ N ≤ 100000.
      N lines follow, each with 4 integers x1, y1, x2, y2 (0 ≤ x1 < x2 ≤ 2×109, 0 ≤ y1 < y2 ≤ 2×109)

      This means that there is a brick with bottom left corner (x1,y1) and top right corner (x2,y2). x denotes the horizontal coordinate and y the vertical coordinate. Two bricks will bind if one's bottom y-coordinate coincides with the other's top y-coordinate and the intersection of the two intervals (the bottom of one and the top of the other) has nonzero length.
      No bricks will overlap.

      Output:

      A single line containing the number of separate pieces that these blocks form.

      Sample Input:

      4
      0 0 2 2
      1 2 3 4
      2 0 4 2
      4 0 6 2

      Sample Output:

      2

      Explanation

      Blocks #1,2,3 are joined securely.
      However, #4 is just hanging around.


      Added by:Brian Bi
      Date:2009-04-10
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Hanson Wang









      SPOJ Problem Set (classical)

      4200. Hamster flight

      Problem code: HAMSTER1


      There is a competition of flying hamsters in Hamsterburg. Each competing hamster is thrown from a sling. The judges rate the flight according to its length and height. Let X meters be the distance of the flight, and Y meters – maximum height to which the hamster rose during the flight. The hamster will receive K1*X + K2*Y points for such a flight. The initial speed of the hamsters is V0 m/s. Free fall acceleration is g = 10 m/s2. There is no air friction. The size of the hamster and the sling are negligible. When the hamster is thrown from the sling its height is 0 meters. You should determine the angle at which the hamster must be thrown so that he receives maximum points.

      Input

      The first line of input contains number t – the amount of tests. Then t tests follow one per line. The description of each test consists of three integers separated by single spaces. The first integer is V0, the second – K1, the third – K2.

      Constraints

      1 <= t <= 10000
      1 <= V0 <= 100
      0 <= K1, K2 <= 1000
      0 < K1 + K2

      Output

      For each test output the angle in radians at which the hamster must be thrown, and the amount of points it will receive. The numbers should be separated with spaces. Print the numbers with exactly three digits in the fractional part.

      Example

      Input:
      3
      10 10 0
      10 0 10
      10 10 10
      
      Output:
      0.785 100.000
      1.571 50.000
      0.908 128.078
      

      Added by:Spooky
      Date:2009-04-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Advancement Spring 2009, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      4201. Coder Ratings

      Problem code: RATING

      Some of the more elite (and not-so-elite) coders around take part in a certain unnamed programming contest. In said contest, there are multiple types of competitions. Here, we consider the Open and High School competition types. For each type, each competitor receives a rating, an integer between 1 and 100000, inclusive. A coder's rating is based upon his or her level of performance in matches and is calculated using a complicated formula which, thankfully, you will not be asked to implement.

      Although the Open and High School ratings for a coder who has participated in both competition types lately are usually close, this is not always the case. In particular, High School matches are more about speed, since many coders are able to solve all the problems, whereas Open matches require more thinking and there is a steeper curve in terms of problem difficulty.

      Problem Statement
      You are given N coders (1 ≤ N ≤ 300000), conveniently numbered from 1 to N. Each of these coders participates in both High School and Open matches. For each coder, you are also given an Open rating Ai and a High School rating Hi. Coder i is said to be better than coder j if and only if both of coder i's ratings are greater than or equal to coder j's corresponding ratings, with at least one being greater. For each coder i, determine how many coders coder i is better than.

      Input Format
      On the first line of input is a single integer N, as described above.
      N lines then follow. Line i+1 contains two space-separated integers, Ai and Hi.

      Output Format
      Line i should contain the number of coders that coder i is better than.

      Sample Input

      8
      1798 1832
      862 700
      1075 1089
      1568 1557
      2575 1984
      1033 950
      1656 1649
      1014 1473
      

       

      Sample Output

      6
      0
      2
      4
      7
      1
      5
      1

       


      Added by:Brian Bi
      Date:2009-04-10
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      4202. Brackets Parade

      Problem code: BRPAR

      Count the number of different correct bracket sequences consisting of k1 pairs of brackets of the 1st type, k2 pairs of brackets of the 2nd type, …, km pairs of brackets of the m-th type. The bracket sequence is considered correct in the following cases:

      • empty sequence is correct;
      • if A is correct and B is correct then AB is correct;
      • if A is correct then (iA)i is correct where (i and )i are opening and closing brackets of the same type.

      Input

      The first line of input is the number 0 < n <= 1000 of test cases. Each of the following n lines describe a test case. Each line starts with number 0 < m <= 100 the amount of different bracket types. Then m positive numbers k1, k2, …, km follow each separated with a space. Number ki is the amount of pairs of brackets of i-th type. The total amount of pairs of brackets is not greater than 1000.

      Output

      For each test case output a line containing single integer – the answer to the problem modulo 1000000007.

      Example

      Input:
      3
      1 4
      2 2 2
      3 1 2 3
      
      Output:
      14
      84
      7920
      

      Added by:Spooky
      Date:2009-04-11
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Open All-Ukrainian Collegiate Contest Semi-Final, 2009









      SPOJ Problem Set (classical)

      4206. Fast Maximum Matching

      Problem code: MATCHING

      FJ has N (1 ≤ N ≤ 50,000) cows and M (1 ≤ M ≤ 50,000) bulls. Given a list of P (1 ≤ P ≤ 150,000) potential matches between a cow and a bull, compute the greatest number of pairs that can be matched. Of course, a cow can be matched to at most one bull, and vice versa.

      Input

      The first line contains three integers, N, M, and P. Each of the next P lines contains two integers A (1 ≤ A ≤ N) and B (1 ≤ B ≤ M), denoting that cow A can be matched with bull B.

      Output

      Print a single integer that is the maximum number of pairs that can be obtained.

      Example

      Input:
      5 4 6
      5 2
      1 2
      4 3
      3 1
      2 2
      4 4
      
      Output:
      3
      

      Cow 1 can be matched to bull 2, cow 3 to bull 1, and cow 4 to bull 3.

      Note: see also http://www.spoj.pl/problems/FASTFLOW/.


      Added by:Neal Wu
      Date:2009-04-12
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS









      SPOJ Problem Set (classical)

      4235. Wandering Queen

      Problem code: QUEEN

      There is a checkmates board with n rows and m columns. Some of the cells of the board are occupied. There is a queen standing on a certain cell. It wants to move to another cell of this board. Help it do this making the least possible moves. The queen can go any number of cells in any of eight directions in a single move, but it can't pass through or stand on the occupied cells and leave the board.

      Input

      The first line of the input contains number t – the amount of tests. Then t test descriptions follow. The first line of each test consists of two numbers n and m separated with a space. Then n lines follow each containing m characters describing the board. Character ‘.’ means a free cell, character ‘X’ – an occupied cell, character ‘S’ – the starting cell of the queen, character ‘F’ – the cell where the queen wants to go. It is guaranteed that there will be exactly one character ‘S’ and one character ‘F’ on each board.

      Constraints

      1 <= t <= 30
      2 <= n, m <= 1000

      Output

      For each test case print the minimum number of moves the queen has to do to reach the desired cell. Print ‘-1’ if the queen can’t reach the cell.

      Example

      Input:
      3
      3 3
      S..
      ...
      ..F
      3 3
      S..
      XX.
      F..
      3 3
      S..
      XXX
      ..F
      
      Output:
      1
      3
      -1
      

      Added by:Spooky
      Date:2009-04-16
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Advancement Spring 2009, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      4273. Train TimeTable

      Problem code: TTTABLE

      A train line has two stations on it, A and B. Trains can take trips from A to B or from B to A multiple times during a day. When a train arrives at B from A (or arrives at A from B), it needs a certain amount of time before it is ready to take the return journey - this is the turnaround time. For example, if a train arrives at 12:00 and the turnaround time is 0 minutes, it can leave immediately, at 12:00.

      A train timetable specifies departure and arrival time of all trips between A and B. The train company needs to know how many trains have to start the day at A and B in order to make the timetable work: whenever a train is supposed to leave A or B, there must actually be one there ready to go. There are passing sections on the track, so trains don't necessarily arrive in the same order that they leave. Trains may not travel on trips that do not appear on the schedule.

      Input

      The first line of input gives the number of cases, N(1<=N<=100). N test cases follow.

      Each case contains a number of lines. The first line is the turnaround time, T(0<=T<=60), in minutes. The next line has two numbers on it, NA and NB. NA is the number of trips from A to B, and NB is the number of trips from B to A(0<=NA,NB<=100). Then there are NA lines giving the details of the trips from A to B.

      Each line contains two fields, giving the HH:MM departure and arrival time for that trip. The departure time for each trip will be earlier than the arrival time. All arrivals and departures occur on the same day. The trips may appear in any order - they are not necessarily sorted by time. The hour and minute values are both two digits, zero-padded, and are on a 24-hour clock (00:00 through 23:59).

      After these NA lines, there are NB lines giving the departure and arrival times for the trips from B to A.

      Output

      For each test case, output one line containing "Case #x: " followed by the number of trains that must start at A and the number of trains that must start at B.

      Example

      Input:
      2
      5
      3 2
      09:00 12:00
      10:00 13:00
      11:00 12:30
      12:02 15:00
      09:00 10:30
      2
      2 0
      09:00 09:01
      12:00 12:02 
      
      Output:
      Case #1: 2 2
      Case #2: 2 0 
      

      Added by:abhijith reddy d
      Date:2009-04-27
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Google Codejam 2008









      SPOJ Problem Set (classical)

      4275. rotate it

      Problem code: BFROTATE

      Rotate the given string starting at the given place from the end with wrapping around at the end. You are allowed to use only BrainFck!

      Input

      Given an integer of strictly 2 digits and a string (length <= 99) in the same line without space between them. You may assume that the string consists of only printable characters and that the length of string is more than the given integer.

      Output

      One string of the same length as input and which has same characters in different order as described by problem.

      Example

      Input:
      04abcdefgh

      Output:
      efghabcd

      Added by:!(accepted)
      Date:2009-04-29
      Time limit:0.200s-1s
      Source limit:256B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:BF
      Resource:Prateek Sharma









      SPOJ Problem Set (classical)

      4305. Drilling

      Problem code: AE3A

      Byteman has asked you for help. He has divided the segment connecting points A and B into n+1 segments of equal length. If we assume that point A has coordinate 0, and point B coordinate n + 1, then there are n points with coordinates 1, 2, . . . , n between them. It is enough to find the farthest from A of these points in which some crude oil occurs. Byteman has informed you about the amounts of time necessary for making boreholes in these points — they are equal to t1, t2, . . . , tn respectively. You should create such a plan of drilling, that the time necessary to identify the oil reservoir’s boundary is shortest possible, assuming the worst-case scenario.

      Input

      The first line of the standard input contains a single positive integer n (1 ≤ n ≤ 2000). The second line contains n positive integers t1, t2, . . . , tn separated by single spaces (1 ≤ ti ≤ 106).

      Output

      Your program should write a single integer to the standard output—the smallest amount of time that Byteman has to spend (assuming the worst-case scenario) drilling in search of oil, to be sure that he will identify the reservoir’s boundary.

      Example

      For the input data:

      4
      8 24 12 6
      

      the correct result is:

      42
      

      Explanation of the example.

      Assume that Byteman makes the first borehole at point 1, what takes him time 8. It can then turn out that he finds crude oil there and he will have to check, how far to the right does the reservoir reach. He will need two more boreholes, making which requires 36 units of time in the worst case. Therefore, in this case Byteman will spend in total 44 units of time drilling.

      It turns out that it is better to start at point 2. If there is no crude oil there, it is sufficient to check point 1. However, in the worst case Byteman will have to make two more boreholes in points 3 and 4 and end his work in total time equal to 42.


      Added by:Race with time
      Date:2009-05-03
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Algorithmic Engagements 2009









      SPOJ Problem Set (classical)

      4324. The fate of the pineapple

      Problem code: EVERLAST

      In order to help terraform Mars, astronauts have brought (among other things) N (0<=N<5) young, healthy pineapple plants.

      This particular type of pineapple reproduces asexually in the following way:

      1. A single pineapple plant produces K (0<=K<15) new pineapple in one growing season.
      2. At the end of the growing season, the new pineapples are adults, and the old ones are dead.
      3. Increased levels of radiation have a P (0<=P<=1) chance of sterilizing any new pineapple that develops on Mars. This probability is independent for each pineapple.

      What is the probability that the pineapple population will never die out?

      Input

      The first line is the number of test cases (no more than 10^5). Each of the following lines describes a test case. The integers N and K and the decimal number P are separated by single spaces.

      Output

      There will be one line for each test case. Each line will have the probability of eventual survival in percent, to two decimals, followed by the percent sign.

      Example

      Input:
      5
      1 3 0.6666666666666666
      1 3 0.65
      1 1 0
      1 0 1
      3 4 0.7101634622811129
      
      Output:
      0.00%
      13.83%
      100.00%
      0.00%
      70.94%
      

      Added by:Paul Draper
      Date:2009-05-05
      Time limit:1s-4.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6









      SPOJ Problem Set (classical)

      4343. Empty Boxes

      Problem code: EBOXES

      N large empty boxes (assume they are of type:1) are initially placed on a table. An unknown number of boxes (type:1) are selected and in each of them K smaller boxes (type:2) are placed. Again an unknown number of type:2 boxes are selected and K boxes of type:3 are placed inside. This process is repeated T times. Now a box is assumed to be empty when it has no smaller boxes inside it. Finally after all the processes are complete let there be F empty boxes in total.

      LIMITS

      1< N,K,T,F <1000000

      Input

      First line of the input file contains the number of test cases. Then each line contains 4 integers N,K,T,F as described above.

      Output

      Each line should contain the total number of boxes on the table.

      Example

      Input:
      1
      11 8 2 102
      
      Output:
      115
      

      Added by:abhijith reddy d
      Date:2009-05-07
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6









      SPOJ Problem Set (main)

      4407. Counting Arborescence

      Problem code: DAGCNT

      "In graph theory, an arborescence is a directed graph in which, for a vertex v called the root and any other vertex u, there is exactly one directed path from v to u. In other words, an arborescence is a directed, rooted tree in which all edges point away from the root. Every arborescence is a directed acyclic graph."

      -- from Wikipedia, the free encyclopedia

      You are given a directed graph with N vertices, and your task is to count the number of different arborescences of size N that can be found in the given graph.

      Two arborescences are considered different when they consist of different edges.

      Input

      Input consists of multiple test cases.

      For each test case, the first line contains one integer N described as above.

      N lines follows, each consists of N characters, either '0' or '1', representing the adjacency matrix of the graph.

      The directed graph contains edge (i,j) if and only if the jth character of the ith line of the matrix is '1'.

      The graph consists of no more than 8 vertices.

      End of input is indicated by a line consisting of a single 0.

      Output

      For each test case, output one line consisting of one single integer, the number of arborescences.

      Example

      Input:
      2
      00
      00
      2
      01
      10
      0
      
      Output:
      0
      2
      

      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:11s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 C99 strict CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:Fudan University Local Contest #1









      SPOJ Problem Set (classical)

      4408. Build a Fence

      Problem code: FENCE1

      There is a wall in your backyard. It is so long that you can’t see its endpoints. You want to build a fence of length L such that the area enclosed between the wall and the fence is maximized. The fence can be of arbitrary shape, but only its two endpoints may touch the wall.

      Input

      The input consists of several test cases.

      For every test case, there is only one integer L (1<=L<=100), indicating the length of the fence.

      The input ends with L=0.

      Output

      For each test case, output one line containing the largest area. Your answer should be rounded to 2 digits after the decimal point.

      Example

      Input:
      1
      0
      
      Output:
      0.16

      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Fudan University Local Contest #1, practise session









      SPOJ Problem Set (classical)

      4409. Circle vs Triangle

      Problem code: AREA1


      You are given a triangle and a circle in a plane. You can arbitrarily rotate or move them. What's the maximum possible area of their overlapping region?

      Input

      Input consists of one or more lines. For each line, there are four integers describing one test case: the lengths of three sides of a triangle a, b, c; and the radius of a circle r; where 1<= a <= b <= c <= 100, 1<= r <= 100, a+b>c .

      End of input is indicated by a line consisting four zeros.

      Output

      For each test case, output a single line showing the largest overlapping area of the circle and the triangle. We accept solutions with absolute error less than 10-2.

      Example

      Input:
      3 4 5 1
      5 5 8 4
      0 0 0 0
      
      Output:
      3.14
      12.00
      
      Judge is modified on Feb 23,2010. Now you can click on "Wrong Answer" for further information.
      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:11s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Fudan University Local Contest #1









      SPOJ Problem Set (classical)

      4410. Repair the Door

      Problem code: REPAIR1

      Once upon a time, there was a famous university called Famous University. As thousands of students studied and lived in FU, a gigantic residential building was built, which is called 'B37'. All students lived in B37 happily.

      After decades, FU is still as famous as it had been in the past; however, the students living in it are now unhappy, because B37 is too old. Although the door of the building looks fine, it can be easily broken when being opened by some careless student too forcefully.

      So, Blue Mary, the accommodation officer of B37, is facing an extremely serious problem.

      With some mysterious methods, Blue Mary has predicted that exactly N students will enter or exit B37 during the next term. Unfortunately she doesn't know who the careless ones are, so she assumes that every student opening the door has a probability of P percent to be a careless one. When the door is broken by some careless guy, Blue Mary may repair it immediately or after some time, with a cost of A yuan. Unfortunately when a student goes through the door and finds it already broken and not repaired, she will report it to the headmaster, and Blue Mary will be subject to a fine of B yuan. The door is in good condition before the term begins, and will be repaired by the university after the term ends, so Blue Mary can leave the door unrepaired at the end of the term.

      Being good at mathematics, Blue Mary has made a strategy, to decide when to and when not to repair the door, in order to minimize her expense.

      Please write a program to calculate the expectation of her expense.

      Input

      The input consists of multiple test cases, the number of them is about 200000.

      For each test case, there is one line containing four non-negative integers N, P, A, B described as above, with 0<=N<=100000, 0<=P<=100, 0<=A<=100, 0<=B<=100.

      End of input is indicated by a line consisting of four zeros.

      Output

      For each test case, output one line containing the expectation of Blue Mary's minimal expense. We accept solutions with absolute error less than 10-4.

      Example

      Input:
      10 100 0 1
      10 100 1 0
      2 50 2 1
      0 0 0 0
      
      Output:
      0.0000
      0.0000
      0.5000
      

      Hint

      In the first sample, the door will be broken every time it is opened, but repairing is free, so just repair it every time.

      In the second sample, nothing will be fined, so just leave the door unrepaired.

      In the last sample, if the door is broken by the first student, Blue Mary will be fined 1 yuan, otherwise she doesn’t need to pay anything.


      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:11s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Fudan University Local Contest #1









      SPOJ Problem Set (classical)

      4411. Counting Expressions

      Problem code: EXPR3

      Count the number of distinct expressions involving n different operands a, b, c, etc. Only operators +, -, *, / and parentheses are permitted.

      Two expression are distinct if for some valid input values (i.e. You won't divide some number by zero) a, b, c, ... , the two expressions leads to different results. For example, a/b/c and a/(b*c) are the same expressions, but a/b+c and a/(b+c) are not.

      Input

      Multiply test cases. For each test case:

      A single line - n.(1<= n <=50).

      Input terminates by a single zero.

      Output

      For each test case:

      The number of different expressions, modulo 499999999999993.

      Example

      Input:
      3
      0
      
      Output:
      68
      

      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Fudan University Local Contest #1









      SPOJ Problem Set (classical)

      4412. Factorization, Factorization, Factorization

      Problem code: FACTOR1

      Factorize xn-1 into several irreducible polynomials over the integers.

      Input

      Multiply test cases. For each test case:

      A single line - n.(2<= n <= 1200).

      Input terminates by a single zero.

      Output

      For each test case, output the factorization of the given polynomial.

      There are multiple ways to express the factorization of a polynomial. To make it unique, we sort the irreducible polynomials according to the following rules:

      Lower order polynomials are always lexicographically smaller than higher order polynomials. Same order polynomials should be sorted by their coefficients. We compare the coefficients from high degree terms to low degree terms, including the omitted terms, which the coefficients are regard as 0. Coefficients are being compared first by absolute value then by sign. Smaller absolute values are lexicographically smaller. For the same absolute value, negative coefficients are lexicographically smaller than positive coefficients.

      See example for more output format details.

      Example

      Input:
      12
      0
      
      Output:
      (x-1)(x+1)(x^2+1)(x^2-x+1)(x^2+x+1)(x^4-x^2+1)
      

      Hint

      There should not be a "*" between digit and x, i.e. -2x^2 should be printed as -2x^2.


      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:11s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Fudan University Local Contest #1









      SPOJ Problem Set (classical)

      4413. Gem

      Problem code: GEM

      You are given a board with 8*8 squares. In each square, there can be either a colored gem or no gem at all. Gems with different colors are represented by different integers. It is guaranteed that there are no more than two consecutive gems with the same color either in a row or in a column.

      ........
      ........
      ........
      ........
      ........
      ..43366.
      ..121556
      44212335
      

      For two neighboring (up, down, left or right, we don't consider diagonal neighbors) squares, you can exchange the gems.

      ........
      ........
      ........
      ........
      ........
      ..43366.
      ..111556
      44222335
      

      You can also exchange a gem with a space. After that, if there are more than two consecutive gems with the same color in a row or in a column after exchange, these gems will be taken away simultaneously. Note that a gem could be counted both in its row and in its column; refer to the sample test cases for details.

      ........
      ........
      ........
      ........
      ........
      ..43366.
      .....556
      44...335
      

      If there is no gem under a gem, the gem will fall to the square below.

      ........
      ........
      ........
      ........
      ........
      .....66.
      .....556
      44433335
      

      After all the squares falling down to the floor or another gem square, repeat the procedure until there's no gem can be taken away: if there are more than two gems with the same color in a row or in a column, these gems will be taken away simultaneously. Then some gems will fall to the squares below, if there are no gems under those gems.

      ........
      ........
      ........
      ........
      ........
      .....66.
      .....556
      .......5
      
      ........
      ........
      ........
      ........
      ........
      ........
      .....666
      .....555
      
      ........
      ........
      ........
      ........
      ........
      ........
      ........
      ........
      

      Given a board with 8*8 squares. This board is stable and you can't take away any gems in the original board. Your task is to determine whether all gems can be taken away by a single exchange or not.

      Input

      The input consists of several test cases. Each test case will be eight lines, and each line contains eight characters. If in a square there is no gem, ‘.’ is used to identify it, otherwise an integer k is used to identify the gem's color, 1<= k <=9.

      There is a blank line between two consecutive test cases.

      End of input is indicated by a line consisting of 0.

      Output

      For each test case, output a single line. If all gems can be taken away by a single exchange, output Yes; otherwise output No.

      Example

      Input:
      ........
      ........
      ........
      ........
      ........
      ..43366.
      ..121556
      44212335
      
      ........
      ........
      ........
      .2......
      .2.22...
      .1.11...
      .2.22...
      .2.22...
      
      12121212
      21212121
      12121212
      21212121
      12121212
      21212121
      12121212
      21212121
      
      ........
      ........
      ........
      ........
      ........
      ...96...
      ...96...
      .996966.
      
      0
      
      Output:
      Yes
      Yes
      No
      Yes
      

      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Fudan University Local Contest #1









      SPOJ Problem Set (classical)

      4414. Highway

      Problem code: HIGHWAY1

      As we all know, every day, there are hundreds of trucks passing through the highway. As some of the trucks might carry several tons of goods, the highway will be damaged unless it is frequently repaired. The administration of highway is worried about this, so it invented repairing cars to ensure that the cars can pass through the highway.

      The highway has an initial durability. If a truck with x tons’ goods pass the highway, its durability will be decreased by x. Once the highway’s durability is less or equal to zero, it will be broken and can never be repaired. The trucks can’t pass through the broken ones.

      There are two kinds of repairing cars: T1 can increase the highway’s durability by r, T2 can increase the highway’s durability to p, if the highway’s durability is less than p. Although the repairing cars can pass through the broken parts, the broken parts can’t be repaired.

      Input

      The input consists of several test cases.

      For every test case, there are three integers N (1<=N<=100000), M (1<=M<=100000), I (1<=I<=1000) in the first line, indicating the highway’s length, the numbers of cars and the initial durability of the highway.

      Each of the next M lines described the information of cars in the following format:
      1 s t d -- There is a truck with d tons’ goods wanted to pass the interval [s, t]. You should check whether the truck can pass it. Notice that if the truck can't pass the whole interval, it will give up the whole passing; otherwise it can pass the highway freely, even if the highway will be broken after the truck’s passing.
      2 s t r -- A T1 car will pass the interval [s, t] and increase its durability by r.
      3 s t p -- A T2 car will pass the interval [s, t] and increase its durability to p.

      You can assume that 1<=s<=t<=N, 1<=d, p, r<=1000

      The input ends with N=M=I=0.

      Output

      For each case, you should return how many trucks can successfully pass the interval.

      Example

      Input:
      5 5 5
      1 1 3 3
      2 2 3 10
      1 1 3 3
      1 1 3 1
      1 2 3 1
      5 3 10
      1 1 2 5
      1 2 3 5
      1 1 3 5
      0 0 0
      
      Output:
      3
      2
      

      Hint

      In the second test case, the third truck can’t pass the road, because although the durability of interval [1, 2) and (2, 3] is larger than 0, in position 2, the durability is 0.


      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:11s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Fudan University Local Contest #1









      SPOJ Problem Set (classical)

      4415. Power of Integer

      Problem code: INTEGER1

      For a given positive integer y(y > 1), if we can find a largest integer k and a smallest positive integer x, such that x^k=y, then the power of y is regarded as k.

      Calculate the sum of the power of the integers from a to b. (2<= a <= b <=1018)

      Input

      The input consists of multiple test cases.

      For each test case, there is one line containing two integers a and b.

      End of input is indicated by a line containing two zeros.

      Output

      For each test case, output the sum of the power of the integers from a to b.

      Example

      Input:
      2 10
      248832 248832
      0 0
      
      Output:
      13
      5
      

      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:11s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Fudan University Local Contest #1









      SPOJ Problem Set (classical)

      4416. Jumping Hands

      Problem code: JUMP1

      In Shanghai, there are some famous clock towers built more than 100 years ago, such as the office building of Shanghai Customs, Xujiahui Church, etc. Every clock tower’s clock-face consists of three hands: an hour hand, a minute hand, and a second hand. The hands are not move smoothly as time passing. When a second passes, the hands jump to the next place clockwise: the second hand moves 1/60 ring, the minute hand moves 1/3600 ring and the hour hand moves 1/43200 ring.

      We assume that every hand’s mass is evenly distributed, and its thickness can be ignored. In other words, every hand’s centre of gravity is at the middle position of the respective hand. Suppose p1, p2 and p3 are, respectively, the position of the centre of gravity of the hour hand, that of the minute hand, and that of the second hand. The position of all three hands’ centre of gravity, P, is the average of p1, p2 and p3 weighted by the hands’ mass.

      Suppose P1 and P2 are the positions of the three hands’ centre of gravity at the start time and at the end time, respectively. Your task is to calculate the length of the path from P1 to P2. That is, if P3 is the position of the three hands’ centre of gravity on the clock-face at a point of time between start time and end time, X is the length of the path from P1 to P3, and Y is the length of the path from P3 to P2, the length of the path from P1 to P2 is X+Y.

      Input

      Input consists of one or more lines, each line describing one data set. Each line begins with 6 integers: L1, L2, L3, M1, M2, M3, followed by start time and end time. L1, L2 and L3 indicate the lengths of hour hand, minute hand and second hand respectively, where 1<= L1<L2<L<=100. M1, M2 and M3 indicate the weights of hour hand, minute hand and second hand respectively, where 1<= M1, M2, M3 <=100. The format of start time and end time is hh:mm:ss, where 0<= hh <=23, 0<= mm <=59, and 0<= ss <=59. Start time and end time should be in the same day.

      End of input is indicated by a line consisting of -1.

      Output

      For each data set, output a single line. Each line should give the length of the path for the positions of three hands’ centre of gravity at the start time and at the end time. We accept solutions with absolute error less than 10-2.

      Example

      Input:
      1 2 3 1 2 3 00:00:00 00:00:01
      3 4 5 1 1 1 09:00:00 18:00:00
      -1
      
      Output:
      0.08
      2826.27
      

      Added by:[Trichromatic] XilinX
      Date:2009-05-23
      Time limit:11s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Fudan University Local Contest #1









      SPOJ Problem Set (classical)

      4420. Counting Graphs

      Problem code: KPGRAPHS

      In this problem your task is to count the amount of graphs of different types. We only consider undirected graphs without self-loops. Every pair of vectices can be connected with at most one edge. Graphs are labeled, i.e. if a graph has N vertices, then each of them has a unique label from 1 to N.

      We will be interested in three types of graphs - connected, eulerian and bipartite. A graph is connected, if and only if there is at least one path between any pair of vertices. A graph is eulerian, if and only if it's connected and there is a cycle that goes through every edge exactly once. A graph is bipartite, if and only if we can split all of its vertices into two subsets A and B, such that every edge has one endpoint in A and another in B.

      Input

      The first line of the input contains one integer number T (1 <= T <= 1000) - the number of test cases.

      Next T lines contain different test cases. Each test case contains one integer number N (1 <= N <= 1000) - the number of vertices in a graph.

      Output

      For each test case, output the number of connected graphs, the number of euleran graphs and the number of bipartite graphs - all modulo 1000000007. See examples for the required format. Output one additional empty line after each test case.

      Example

      Input:
      2
      1
      2

      Output:
      Connected: 1
      Eulerian: 1
      Bipartite: 1

      Connected: 1
      Eulerian: 0
      Bipartite: 2


      Added by:Pavel Kuznetsov
      Date:2009-05-25
      Time limit:5s
      Source limit:7000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6









      SPOJ Problem Set (classical)

      4421. Irreducible polynomials over GF2

      Problem code: GF2


      Find the number of degree n irreducible polynomials over GF(2). For example: for n=1 there are two such polynoms: x and x+1. For n=2 there is only one: x2+x+1. Note that in R[x] the polynom x2 +1 is irreducible, but not over GF(2), because x2+1=(x+1)*(x+1)

      Input

      A single positive integer n, where n<500000

      Output

      Output the answer for n.

      Example

      Input:
      201
      Output:
      15989433276208858463104100421305100522608250813995004946218

      Input:
      1
      Output:
      2

      Input:
      2
      Output:
      1

      Input:
      3
      Output:
      2


      Added by:Robert Gerbicz
      Date:2009-05-25
      Time limit:0.5s-6s
      Source limit:4096B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:classic problem, own input









      SPOJ Problem Set (classical)

      4429. Spelling Lists

      Problem code: MIB

      J, of the Men In Black,  has been learning an alien language and has has a spelling test tomorrow.  J, however, is bored of studying the nonsensical (and often unpronouncable) words.

      Instead, he is seeing how many ways he can reorder his spelling list.  After making all possible permutations of word on his list, he sorts the rearranged lists lexiographically (by the first word, then the second...).  After the sort, in what position, with  the lexiographically first list being in position 1, is his original spelling list?

      Input

      The first line is the number of spelling lists (no more than 10).

      For each spelling list, a line with the number of words (no more than 1000) is given, followed by the original list on the next line.

      All words within a spelling list are unique.  Each word is composed of the letters a-z, is fewer than 100 characters, and is followed by a single space.

      Output

      On separate lines, give the positions of the original lists.

      Example

      Input:
      4
      4
      a b c d
      4
      d c b a
      1
      mrsmith
      6
      a aaaaaa aaaaa aaaa b bb

      Output:
      1
      24
      1
      55

      Added by:Paul Draper
      Date:2009-05-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6









      SPOJ Problem Set (classical)

      4452. Simple Arithmetics II

      Problem code: ARITH2


      While browsing aimlessly, Peter stumbled upon an old riddle he used to solve on his calculator when he was still young. It was the kind of a riddle where you punch in a bunch of numbers and operators into a simple pocket calculator and then turn it upside down to get the answer:

      These come in many different sizes but they are always exactly one foot long. Answer: 103 * 103 * 5.

      What are made of ice to keep people warm? Answer: 50 * 40 * 250 + 791.

      After a few minutes he found a large amount of such riddles and full of excitement he went to solve them. He turned his computer screen upside down...

      ... only to find out that he does not have a reasonable calculator program installed on his computer.

      Problem specification

      You are given multiple sequences of button presses of a simple pocket calculator that consist of digits and arithmetic operators. For each such sequence find the number it would produce on a pocket calculator's display.

      Note that the pocket calculator evaluates the operators in the order in which they are given. (i.e., there is no operator precedence.) Assume that the display of the calculator is large enough to show the result, and that its memory is sufficient to store all intermediate results.

      Input specification

      The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

      Each test case represents one sequence of button presses for a pocket calculator. The sequence consists of non-negative integers and arithmetic operators and ends with an equal sign. It may also contain spaces to improve readability.

      The operator / represents integer division, rounded down. You may assume that no test case contains division by zero and that in all test cases all intermediate results are non-negative.

      Tip: long long int in C/C++, long in Java or int64 in Pascal is enough for this problem.

      Output specification

      For each sequence from the input file output the number that would be displayed on the calculator.

      Example

      Input:
      4
      
      1 + 1 * 2 =
      
      29 / 5 =
      
      103 * 103 * 5 =
      
      50 * 40 * 250 + 791 =
      
      Output:
      4
      5
      53045
      500791
      

      Hint

      The first test case shows that there is no operator precedence.

      The second one shows that integer division always rounds down.

      The last two outputs are the answers to the two riddles in the problem statement: "shoes" (53045 upside down), and "igloos"(500791 upside down).


      Added by:[Trichromatic] XilinX
      Date:2009-05-31
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:IPSC 2009









      SPOJ Problem Set (classical)

      4453. Bouncing Balls II

      Problem code: BOBALLS2


      "Behold, my queen", said the jester, "the great Bouncing Ball Bowl!" The queen boredly waved her hand and sarcastically replied: "Let the fun begin!". And the fun begun! The jester spoke a magic word and all the colorful balls in his bowl started to roll and bounce, creating interesting pictures.

      The queen watched vividly for a few minutes, but then she started to be bored again. "Just wait a moment, Your Majesty, in a minute they'll…" started the jester, but the queen interrupted: "I'm a queen! I don't want to wait! Can't you just fast forward it or something?"

      Problem specification

      The jester's box is an X * Y (1<= X, Y <=5000)rectangle. The rectangle contains N(N <=3001) small balls. At any moment, each ball is travelling at the same speed in one of the four diagonal directions.

      The movement of the balls is continuous and for the purpose of this problem we may consider them to be points. When two or more balls meet, they bounce in a way described below.

      Your task is to determine the state of the box at given moments in time.

      Bouncing specification

      Bouncing does not change the speed of the balls. Following images show how the balls bounce off each other, and also off walls. Each image can be rotated arbitrarily. For example, the first image shows that whenever two balls meet at a right angle, they bounce and depart at a right angle again. One particularly tricky case is shown in the third image.

      Input specification

      The input starts with a line containing the dimensions X and Y of the box. We will use a coordinate system with axes parallel to the sides of the box, (0,0) at one of the corners and (X,Y) at the opposite corner.

      The second line contains the number of balls N.

      Each of the next N lines contains four integers x,y,vx,vy, where (x,y) are the coordinates of one ball at time 0 and (vx,vy) is its current velocity vector. (Each ball will be strictly inside the box and for each ball both the absolute values of vx and vy will be equal to 1. No two balls will start at the same place.)

      The following line contains the number of queen's requests M.(1<= M <=20)

      On the last line there are M numbers t1,…,tM – the points in time the queen wants to see. These numbers will be less than 1012.

      Output specification

      As a solution to this problem, we expect a file with M blocks, with the i-th block describing the situation at time ti.

      Each block must contain N lines, and each line must contain the x and y coordinates of one ball. The balls in each block must be sorted – primarily by to their first, secondarily by their second coordinate at that point in time.

      You may output an empty line between the blocks.

      Example

      Input:
      6 4
      4
      1 2 1 1
      5 2 1 1
      2 1 1 -1
      3 1 -1 -1
      1
      4
      
      Output:
      1 3
      3 2
      5 2
      6 3
      

      Note that the balls that start at (2,1) and (3,1) bounce off each other at a non-integer point in time.


      Added by:[Trichromatic] XilinX
      Date:2009-05-31
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:IPSC 2009









      SPOJ Problem Set (classical)

      4454. Brackets II

      Problem code: BRCKTS2


      Peter is preparing slides for his lecture on parsing arithmetic expressions. In the first part of the lecture he wants to focus just on parsing brackets. He invented an interesting geometric representation of a correct bracket sequence for his students, because one image is better than a thousand words:

      Formally, the definition of the geometric representation looks as follows. The simplest correct bracket sequence () is represented by a 1 * 1 square. If A is a correct bracket sequence and g(A) its represenation, then the representation for (A) is g(A) surrounded by a rectangle two units wider than g(A) and one unit taller than the highest point of g(A). If A and B are two correct bracket sequences and g(A) and g(B) are their representations, then we get g(AB) by placing g(B) one unit to the right of g(A).

      After he finished his slides, Peter started to play with the images he prepared. He painted the bounded areas of the images alternately black and white, in such a way that the outer-most areas are all painted black. For the example above this coloring looks as follows:

      Problem specification

      You are given a correct bracket sequence. Calculate the area that is colored black.

      Input specification

      The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

      Each test case consists of one line with a correct bracket sequence with length less than 350000. Every line will only contain characters ( and ).

      Output specification

      For each test case output one line with one integer – the area of the black part of the corresponding geometric representation.

      Example

      Input:
      2
      
      ((()))
      
      (())(()(()))
      
      Output:
      10
      20
      

      Added by:[Trichromatic] XilinX
      Date:2009-05-31
      Time limit:1s-7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:IPSC 2009









      SPOJ Problem Set (classical)

      4455. Going to the Movies

      Problem code: MOVIE


      N(N <= 120) friends decided to go to the local cinema together. They all bought tickets to the same row. As there was still some time left, each of them took her ticket and went shopping until the movie starts.

      They all arrived back late, the movie already started. The usher standing at the door agreed to let them in one by one. Each of the girls was supposed to find her place and sit down.

      However, the machine that printed their tickets was broken. Instead of consecutive numbers, each girl received a random seat number between 1 and K, where K is the number of seats in their row. The seat numbers they received were not necessarily distinct.

      When a girl tries to sit down, she enters the row at the end where seat number 1 is, and walks until she reaches the number on her ticket. If her desired seat is free, she just sits down. If it is already taken, she continues to walk in the same direction until she finds the first free seat, and sits there.

      Of course, it is possible that some unfortunate girl will reach the end of the row without finding a place to sit. In that case, the usher comes and throws her out.

      Problem specification

      You are given the numbers N and K.(1<= K <=200)

      Assume that each girl's ticket had a number between 1 and K, inclusive. Each number was drawn uniformly at random, and draws were independent.

      Also assume that the entire row was empty when the first girl started to look for her seat.

      Compute the probability that at least one girl suffered the sad fate of being thrown out by the usher.

      Input specification

      The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line.

      Each test case consists of a single line containing two integers N and K.

      Output specification

      For each test case output a single line with the probability as a simplest fraction. (Do not output any spaces before or after the / sign.)

      Example

      Input:
      3
      
      1 10
      
      2 3
      
      3 3
      
      Output:
      0/1
      1/9
      11/27
      

      In the third case there are 33 = 27 possibilities. Out of these, in 11 some girl is thrown out. These 11 sequences are: 133, 222, 223, 232, 233, 313, 322, 323, 331, 332, and 333.

      For example, if the sequence of numbers were 322, the first girl sits at seat #3, the second one at #2, and then the third one tries to sit at #2, but finds both seat #2 and seat #3 occupied, and she's thrown out.


      Added by:[Trichromatic] XilinX
      Date:2009-05-31
      Time limit:1s-7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:IPSC 2009









      SPOJ Problem Set (classical)

      4456. Jumbo Airlines

      Problem code: AIRLINES

      The new catchphrase of Jumbo Airlines is "No annoying neighbors, each flight a unique experience!"

      And as in most cases, the advertisement was produced by the marketing department, without ever consulting the engineers. They only learned about it after the boss asked them to "handle it ASAP".

      There are M seats in each row, and there are N rows of seats in the airplane. Hence the seats form an M * N grid. (For the purpose of this problem we will ignore the presence of aisles.) The airline sells exactly K tickets for each flight.

      To make sure that the "no annoying neighbors" part of the motto is satisfied, the seating must obey the following rule: Whenever a seat is occupied, the seats immediately in front of it and behind it, as well as the seats immediately to the left and to the right must remain free.

      An allowed arrangement is a set of K occupied seats that obeys the rule above.

      The "unique experience" part of the motto is then satisfied by using a different arrangement of occupied seats for each flight. (Two seating arrangements are different if there is at least one seat which is occupied in one arrangement and free in the other.)

      Problem specification

      You are given the numbers M, N and K. Find the number of different allowed seating arrangements.

      As this number can be very large, we're only interested in its value modulo 420047.

      Input specification

      Multiple test cases, seperated by blank lines.

      Each test case consists of a single line containing three integers M, N and K. (M <= N)

      There are two kinds of input:

      The input of the first kind satisfies that 1<= M <=15, 1<= N <=50, 3<= K <=50.

      The input of the second kind satisfies that 1<= M<= 4, 1<= N <= 109, 3<= K <=5.

      Input terminates by EOF.

      Output specification

      For each test case output a single line with the number of allowed arrangements modulo 420047.

      Example

      Input:
      2 4 4
      
      Output:
      2
      

      Hint

      The input file can be downloaded here. You may submit a TEXT file - the corresponding output file.


      Added by:[Trichromatic] XilinX
      Date:2009-05-31
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:TEXT
      Resource:IPSC 2009









      SPOJ Problem Set (classical)

      4457. Shopping II

      Problem code: SHOP2

      Karl is going to spend his holiday in Nothingland. Since there is nothing there, he has to buy all supplies now. At the moment, he is waiting at the checkout counter with a shopping cart full of stuff.

      Of course, he has a sufficient amount of money in his wallet. However, he prefers to use alternate means of payment if possible: luncheon vouchers, gift certificates, different types of coupons, etc. What makes the matter complicated is that the use of these items is often limited: e.g., luncheon vouchers can only be used to buy food, and gift certificates are often limited to a certain type of gifts.

      Problem specification

      You are given the number N(1<= N <=2000) of items in Karl's shopping cart and their prices. You are also given the number M(1<= M <=2000) of vouchers in his wallet, together with the information on their allowed use.

      When paying for his shopping, Karl may use vouchers for a larger sum than the cost of the things he is buying. It is also possible to split an item's cost between multiple vouchers and use a voucher to pay for more than one item.

      Compute the minimum amount of additional cash money Karl needs to pay for his shopping.

      Input specification

      The first line of input file contains an integer T specifying the number of test cases. T blocks follows, each block describes one test case. Each block is preceded by a blank line.

      Each block starts with line containing two positive integers N (the number of items) and M (the number of vouchers). The second line contains N numbers(each no more than 10000), the i-th of them being the price of the i-th item in Karl's shopping cart. The third line contains M numbers, the i-th of them being the cash value of the i-th voucher Karl has in his wallet. M lines follow. Each line consists of a number Ki (the count of items such that you can pay for them using the i-th voucher, no more than 100) followed by Ki numbers (the numbers of those items; items are numbered from 1 to N).

      Output specification

      For each test case output a single number specifying how much cash money Karl needs to pay for his shopping.

      Example

      Input:
      1
      
      3 2
      15 20 10
      20 30
      3 1 2 3
      1 3
      Output:
      15
      

      Added by:[Trichromatic] XilinX
      Date:2009-05-31
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:IPSC 2009









      SPOJ Problem Set (classical)

      4461. A Famous Airport Manager

      Problem code: AIRLINE2

      Mr. B is an airport manager. One day after lunch he looked out from his office and found that the color of each plane which was currently parked in the airport is either blue or green. Before supper he found that no plane is on the airport now. He couldn't remember the orders in which the planes took off, but he knew between the two observations no plane arrived at the airport. In addition, while one plane is setting its way to the takeoff area, the remaining planes must stay at their own position and cannot move. In the other words, considering the planes taking off in a specific order, the first plane will move while others stay at their own position. After the first plane took off, the second plane could move to the takeoff area and so on, until all the planes gone. Now he wants you to find out the number of different possible color sequences he might see, if he watched at the takeoff area during the whole afternoon.

      The airport can be divided into 9 square areas (3 rows x 3 columns), each area can park at most one plane. The area located at the first column of the first row is called "takeoff area". The plane can take off only in the takeoff area. Besides, each plane (including the one in the takeoff area) can move to a vacant neighboring area. Two areas are neighboring if and only if they share an edge.

      Input

      Each test case contains 3 lines, each of which contains 3 characters '*', 'B', 'G', denoting that the corresponding area is currently vacant, occupied by a blue plane, or occupied by a green plane, respectively. The first character of the first row is always a '*'. There is at least one place in the apron.

      There are about 30,000 test cases. Be careful!

      Output

      For each test case, display a single line containing the case number and the number of different possible color sequences Mr. B might see.

      Example

      Input:
      *BB
      BBB
      BBB
      *GB
      BBB
      BBB
      
      Output:
      Case 1: 1
      Case 2: 8
      

      Added by:[Trichromatic] XilinX
      Date:2009-06-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS PERL 6
      Resource:Blue.Mary's own problem, used in FDU Local Contest 2012









      SPOJ Problem Set (classical)

      4465. The Ant

      Problem code: ANTTT

      There are n sticks lying on the ground. The Ant can move only along the sticks. It can go from one stick to another only if the sticks intersect or touch each other. Help the Ant find out if it can reach the stick y from the stick x.

      Input

      The first line of the input contains number t – the amount of tests. Then t test descriptions follow. The first line of each test contains two integers n and m - the number of stick and the number of queries. Next n lines contain four integers Ax, Ay, Bx, By - the coordinates of the endpoints of a stick. You may consider stick to be straight segment on a plane. The next m lines contain two integers each x and y which are the queries.

      Constraints

      1 <= t <= 100
      1 <= n, m <= 1000
      -10000 <= Ax, Ay, Bx, By <= 10000
      1 <= x, y <=

      Output

      For each query print "YES" if the Ant can reach the stick number y from the stick number x, otherwise print "NO".

      Example

      Input:

      2
      3 3
      1 3 4 3
      3 4 3 1
      3 1 5 1
      1 2
      1 3
      2 2
      3 3
      1 1 3 1
      2 1 3 1
      3 2 4 1
      1 2
      1 3
      2 3


      Output:

      YES
      YES
      YES
      YES
      NO
      NO
       


      Added by:Spooky
      Date:2009-06-02
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Advancement Spring 2009, http://sevolymp.uuuq.com/
      author: elmariachi1414









      SPOJ Problem Set (classical)

      4476. Playfair Cracker

      Problem code: PLAYFAIR

      In this problem, you will crack Playfair cyphers or decide a multiple solutions exist, or decide no solution exist.

      Rules:

      1) Convert all letters in the text to uppercase and omit all non-alphabetic characters.

      2) Replace all letters 'J' by 'I'.

      3) Form digraphs, but avoid having twice the same letter in a digraph. Insert an extra 'X' between the identical letters if necessary. If the repeated letter is an 'X', insert a 'Q' instead.


      4) If the last digraph would be incomplete, append an extra 'X' to the text (or a 'Q' if the last letter in the text is an 'X').

      Consider the following message: "Programming in C and Pascal is easy; I will learn Java next year." The digraph representation would be: 

      PR OG RA MX MI NG IN CA ND PA SC AL IS EA SY IW IL LX LE AR NI AV AN EX TY EA RX

      Note the extra 'X' between the two 'M's of 'programming'. There is no extra 'X' between the two 'L's of 'will', because they are in different digraphs, but there is one between 'will' and 'learn'. There is also an extra 'X' at the end of the message. The 'J' in 'Java' is replaced by an 'I'.
      To illustrate the exceptions for the letter 'X' in the original text, consider the message "I am an ex-xenophobe, attempting to relax!". This becomes: 

      IA MA NE XQ XE NO PH OB EA TX TE MP TI NG TO RE LA XQ

      The next stage is the replacement of each digraph by an other digraph according to the following rules:

      The uppercase letters, 'J' excluded, are placed in a 5X5 square in some predetermined order. This is the key for the encryption.


      If the two letters of the digraph are in the same row of the square, replace them by the letters occuring at the immediate right of each one. If one of the letters is in the rightmost column, replace it by the letter in the first column of the same row (wrap around).


      If the two letters of the digraph are in the same column of the square, replace them by the letters occuring immediately below each one. Wrap around to the same column in the top row if one of them is in the bottom row. 
      If the letters are neither in the same row nor the same column, replace the first letter by the letter in the same row as the first letter and the same column as the second letter. Replace the second letter by the letter in the same row as the second letter and the same column as the first letter. 

      The resulting digraphs form the encrypted code.

      Input

      The input contains several cases, the number of which is on the first line. Every case has three parts. The first part is the plaintext and consists of one or more lines of ordinary text. The second part is the code that is the result of encrypting the first part. The third part is code for the text you are to decrypt. The parts are terminated by a hashmark ('#') on a line by itself. Code parts are printed as uppercase digraphs, 20 digraphs on a line, separated by one space. The last line of a code part can contain fewer than 100 digraphs. No code part will contain more than 5000 digraphs.

      Output

      For each case, first output a line "Case x:" where x is the case number (starting from 1).
      Then output the decrypted code represented as digraphs in the same format as the code parts in the input.  If more than one solution exist, output the following on a single line.

      MULTIPLE SOLUTIONS

      If no solutions exist output in one line:

      NO SOLUTIONS

      Separate the cases by an empty line.

      Example

      Input:
      2
      Programming in C and Pascal is easy; I will learn Java next year.
      #
      FV CV GE PH PW AS UX GL UY ZX GY LZ UV HE NS UI UQ IA QA EG
      XU XG EA HN KC HE VE
      #
      LX ZH AH EI NH XY MX KV HE OE RQ PD OQ AS KY EQ ZL EI
      #
      It is full moon!
      Meet me at Hammersmith Bridge tonight.
      #
      MP PI NZ AZ RN QV UG GD DO GD RQ AR KY GD HD NK PR DA MS OG
      UP GK IC QY
      #
      HL WT UP MC HQ RW PI CX DC ZD HB HG KL PM GI FP SK GE QR MF
      MP AR BH HM HA SP DP TC WM DZ PO RL SG MU DC SB OD SM MU CS
      UH RX BL MH HG WS DC BH MF KR MZ GT CD PU CS HD GH LK DP CT
      GI RZ CD EV KY GD MF IP GT IF KG IC EH TE SD QV QG PR RQ EV
      MU HK IF RC CR EQ OU PR SB GE CD PR PI UP DR UE EV FS BH MF
      EV FS DA BC MK GI
      #

      Output:
      Case 1:
      IA MA NE XQ XE NO PH OB EA TX TE MP TI NG TO RE LA XQ

      Case 2:
      CR YP TO GR AP HY IS AV ER YF AS CI NA TI NG SU BI EC TA ND
      IT HA SA RI CH HI ST OR YI FY OU AR EI NT ER ES TE DI NT HE
      PL AY FA IR CI PH ER SA ND MA NY MO RE OT HE RS IC AN ST RO
      NG LY RE CO MX ME ND SI MO NS IN GH SC OD EB OX OK TH AT CO
      NT AI NS AL LA BO UT TH ES EC RE TH IS TO RY OF CO DE SA ND
      CO DE BR EA KI NG


      Added by:Chen Xiaohong
      Date:2009-06-05
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Enhanced Version of Regional Warmup Contest 2005









      SPOJ Problem Set (classical)

      4478. Counting Expressions II

      Problem code: EXPR4

      Count the number of distinct expressions involving n different operands a, b, c, etc. Only operators +, -, *, / and parentheses are permitted.

      Two expression are distinct if for some valid input values (i.e. You won't divide some number by zero) a, b, c, ... , the two expressions leads to different results. For example, a/b/c and a/(b*c) are the same expressions, but a/b+c and a/(b+c) are not.

      Input

      Multiply test cases. For each test case:

      A single line - n.(1<= n <=2000).

      Input terminates by a single zero.

      Output

      For each test case:

      The number of different expressions, modulo 1000000007.

      Example

      Input:
      3
      0
      
      Output:
      68
      

      Added by:[Trichromatic] XilinX
      Date:2009-06-06
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict ERL JS NODEJS PERL 6
      Resource:Tomek Czajka









      SPOJ Problem Set (classical)

      4487. Can you answer these queries VI

      Problem code: GSS6

      Given a sequence A of N (N <= 100000) integers, you have to apply Q (Q <= 100000) operations:

      Insert, delete, replace an element, find the maximum contiguous(non empty) sum in a given interval.

      Input

      The first line of the input contains an integer N.
      The following line contains N integers, representing the starting
      sequence A1..AN, (|Ai| <= 10000).

      The third line contains an integer Q. The next Q lines contains the operations in following form:

      I x y: insert element y at position x (between x - 1 and x).
      D x  : delete the element at position x.
      R x y: replace element at position x with y.
      Q x y: print max{Ai + Ai+1 + .. + Aj | x <= i <= j <= y}.

      All given positions are valid, and given values are between -10000 and +10000.

      The sequence will never be empty.

      Output

      For each "Q" operation, print an integer(one per line) as described above.

      Example

      Input:
      5
      3 -4 3 -1 6
      10
      I 6 2
      Q 3 5
      R 5 -4
      Q 3 5
      D 2
      Q 1 5
      I 2 -10
      Q 1 6
      R 2 -1
      Q 1 6

      Output:
      8
      3
      6
      3
      5

      Added by:Alfonso2 Peterssen
      Date:2009-06-08
      Time limit:2s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:my own









      SPOJ Problem Set (classical)

      4491. Primes in GCD Table

      Problem code: PGCD


      Johnny has created a table which encodes the results of some operation -- a function of two arguments. But instead of a boring multiplication table of the sort you learn by heart at prep-school, he has created a GCD (greatest common divisor) table! So he now has a table (of height a and width b), indexed from (1,1) to (a,b), and with the value of field (i,j) equal to gcd(i,j). He wants to know how many times he has used prime numbers when writing the table.

      Input

      First, t ≤ 10, the number of test cases. Each test case consists of two integers, 1 ≤ a,b < 107.

      Output

      For each test case write one number - the number of prime numbers Johnny wrote in that test case.

      Example

      Input:
      2
      10 10
      100 100
      Output:
      30
      2791

      Added by:Yash
      Date:2009-06-12
      Time limit:10s
      Source limit:11111B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Codechef









      SPOJ Problem Set (classical)

      4523. Binomial Coefficients

      Problem code: UCI2009B

      We all got too excited when we learned (A + B)^2 = A^2 + 2AB + B^2. After solving this problem, maybe you could get even more excited because you will have to calculate (A + B)^N, where (0 <= N <= 1000).

      Follow the rules below when giving the answer:

      1. Consecutive terms must be separated by a '+' character.
      2. At the i-th term, A must be raised to N - i and B must be raised to i (0<=i<=N).
      3. Binomial coefficients must not be printed, print their prime factorization instead.
      4. Use '^' for exponentiation and 'x' for multiplication in step 3.
      5. Avoid the use of number 1 when possible.

      See sample output for clarification.

      Input

      Input starts with an integer T, representing the number of test cases (1<=T<=15). T lines follow, each one consisting of an integer N, (0<=N<=1000).

      Output

      For each test case, print (A + B)^N, on a single line.

      Example

      Input:
      6
      0
      1
      2
      3
      4
      5

      Output:
      1
      A+B
      A^2+2xAB+B^2
      A^3+3xA^2B+3xAB^2+B^3
      A^4+2^2xA^3B+2x3xA^2B^2+2^2xAB^3+B^4
      A^5+5xA^4B+2x5xA^3B^2+2x5xA^2B^3+5xAB^4+B^5

      Warning: Large output. Be careful with certain languages.

      Added by:Yandry Perez
      Date:2009-06-23
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS









      SPOJ Problem Set (classical)

      4525. Digger Octaves

      Problem code: UCI2009D

      After many years spent playing Digger, little Ivan realized he was not taking advantage of the octaves. Oops, sorry! Most of you were not born when Digger came to light!

      Digger is a Canadian computer game, originally designed for the IBM personal computer, back in 1983. The aim of the game is to collect precious gold and emeralds buried deep in subterranean levels of and old abandoned mine.

      We Digger gurus call a set of eight consecutive emeralds an octave. Notice that, by consecutive we mean that we can collect them one after another. Your Digger Mobile is able to move in the four directions: North, South, West and East.

      In a simplified Digger version, consisting only of emeralds and empty spaces, you will have to count how many octaves are present for a given map.

      Input

      Input starts with an integer T, representing the number of test cases (1<=T<=20). Each test case consists of a map, described as follows:

      An integer N (1<=N<=8), representing the side length of the square-shaped map. N lines follow, N characters each. A 'X' character represents an emerald, and a '.' represents an empty space.

      Output

      For each test case print the number of octaves on a single line.

      Example

      Input:
      2
      3
      XXX
      X.X
      XXX
      3
      XXX
      XXX
      XXX

      Output: 1
      5

      Added by:Yandry Perez
      Date:2009-06-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS









      SPOJ Problem Set (classical)

      4528. Frog Wrestling

      Problem code: FROGS

      Billy Jean loves collecting frogs.  Recently, she developed the sport of frog wrestling.  Now she wants to rank her frogs by their wrestling prowess.

      Billy Jean has made a algorithm for sorting her frogs.

      1. She arranges N cages, numbered 1,2,...N, each with one frog.
      2. For each pair of cages in a specified, pre-determined list of K pairs of cages,
        1. she removes the frogs from the two cages,
        2. has the frogs wrestle,
        3. puts the winner in the higher-numbered cage, and
        4. puts the loser in the lower-numbered cage.

      When she is finished, she hopes to have all her frogs sorted from worst to best in the cages 1 to N.  Will her algorithm work regardless of the initial order of the frogs?

      Note:

      • Assume that a strict ordering by wrestling ability is possible.
      • Billy Jean isn't the sharpest tool in the shed.  Sometimes she has written the same two numbers for a pair.  In this case, that frog is simply taken out and then put back.

      Constraints

      1<=N<=20

      1<=K<=1000

      Input

      The first line is the number of test cases.  Each test cases is preceded by a blank line.

      The first line of each test case is N.  The next line is K.  The next K lines are the pairs, separated by a single space.

      Output

      On separate lines, output whether Billy Jean's algorithm is correct.  Output "YES" (without quotes) if it is or "NO" (without quotes) if it is not.

      Example

      Input:
      4

      2
      1
      2 1

      2
      1
      1 1

      1
      1
      1 1

      4
      5
      1 2
      3 4
      1 3
      2 4
      2 3

      Output: YES
      NO
      YES
      YES

      Added by:Paul Draper
      Date:2009-06-24
      Time limit:1s-7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6









      SPOJ Problem Set (classical)

      4533. Determinant of Banded Matrices

      Problem code: BANDMATR


      Computing the determinant of a matrix using Gaussian elimination takes O(n^3).  On the other hand, computing the determinant of tridiagonal matrix is O(n) using a recurrence.  In this problem you will compute the determinant of banded matrices.  A band matrix is a sparse matrix, whose non-zero entries are confined to a diagonal band, comprising the main diagonal and zero or more diagonals on either side.  In this problem, given a banded NxN square integer matrix with M bands on each side of the diagonal, we ask you to compute the determinant of this matrix.  For example a tridiagonal matrix has exactly 1 band on each side, and the 8x8 Matrix in the sample input has 2 bands on each side.  For a good discussion of banded matrices, see Thorson's paper at:

      http://sepwww.stanford.edu/oldreports/sep20/20_11_abs.html

       

      Input

      A total of <10 inputs.  For each input,

      First line has dimension, N (1<N<501), of the matrix, followed by N lines with N integers, each less than 10001, and greater than -10001.  It is guarantteed that the number of bands on each side of the diagonal, M < 51.  That is there are at most 101 bands in total including the diagonal.  Use scanf IO, and avoid stl IO.

      Output

      For each input matrix, output its determinant modulo 10^9+7.

      Hint: Use Montgomery multiplication for fast computation, i.e., see:
      http://everything2.com/title/Montgomery%2520multiplication

      Example

      Input:

      2
      2 0
      0 2
      2
      1 0
      0 1
      8
      1 0 -1 0 0 0 0 0
      -1 1 0 -1 0 0 0 0
      -1 0 -1 1 -1 0 0 0
      0 -1 0 -1 0 -1 0 0
      0 0 -1 0 1 0 -1 0
      0 0 0 -1 -1 1 0 -1
      0 0 0 0 -1 0 -1 1
      0 0 0 0 0 -1 0 -1

      Output:
      4
      1
      36


      Added by:Chen Xiaohong
      Date:2009-06-26
      Time limit:0.5s
      Source limit:20000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:classical numerical analysis









      SPOJ Problem Set (main)

      4546. Tobo or not Tobo

      Problem code: ANARC08A


      The game of Tobo is played on a plastic board designed into a 3X3 grid with cells numbered from 1 to 9 as shown in figure (a). The grid has four dials (labeled 'A' to 'D' in the figure.) Each dial can be rotated in 90 degrees increment in either direction. Rotating a dial causes the four cells currently adjacent to it to rotate along. For example, figure (b) shows the Tobo after rotating dial 'A' once in a clockwise direction. Figure (c) shows the Tobo in figure (b) after rotating dial 'D' once in a counterclockwise direction.

      Kids love to challenge each other playing the Tobo. Starting with the arrangement shown in figure (a), (which we'll call the standard arrangement,) one kid would randomly rotate the dials, X number of times, in order to shuffle the board. Another kid then tries to bring the board back to its standard arrangement, taking no more than X rotations to do so. The less rotations are needed to restore it, the better. This is where you see a business opportunity. You would like to sell these kids a program to advise them on the minimum number of steps needed to bring a Tobo back to its standard arrangement.

      Input

      Your program will be tested on one or more test cases. Each test case is specified on a line by itself. Each line is made of 10 decimal digits. Let's call the first digit Y . The remaining 9 digits are non-zeros and describe the current arrangement of the Tobo in a row-major top-down, left-to-right ordering. The first sample case corresponds to figure (c).

      The last line of the input file is a sequence of 10 zeros.

      Output

      For each test case, print the result using the following format:

      k. R

      where k is the test case number (starting at 1,) is a single space, and R is the minimum number of rotations needed to bring the Tobo back to its standard arrangement. If this can't be done in Y dials or less, then R = -1.

      Example

      Input:
      3413569728
      1165432789
      0000000000


      Output:
      1. 2
      2. -1


      Added by:Ahmed Aly
      Date:2009-07-02
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:ANARC 2008









      SPOJ Problem Set ()

      4549. Adding Sevens

      Problem code: ANARC08B

      A seven segment display, similar to the one shown on the right, is composed of seven light-emitting elements. Individually on or off, they can be combined to produce 127 different combinations, including the ten Arabic numerals. The figure below illustrates how the ten numerals are displayed. 7-seg displays (as they're often abbreviated) are widely used in digital clocks, electronic meters, and calculators.

      A 7-seg has seven connectors, one for each element, (plus few more connectors for other electrical purposes.) Each element can be turned on by sending an electric current through its pin. Each of the seven pins is viewed by programmers as a single bit in a 7-bit number, as they are more comfortable dealing with bits rather than electrical signals. The figure below shows the bit assignment for a typical 7-seg, bit 0 being the right-most bit.

      For example, in order to display the digit 1, the programmer knows that only bits 1 and 3 need to be on, i.e. the 7-bit binary number to display digit 1 is "0001010", or 10 in decimal. Let's call the decimal number for displaying a digit, its display code, or just code for short. Since a 7-seg displays 127 different configurations, display codes are normally written using 3 decimal places with leading zeros if necessary, i.e. the display code for digit 1 is written as 010.

      In a 9-digit calculator, 9 7-seg displays are stacked next to each other, and are all controlled by a single controller. The controller is sent a sequence of 3n digits, representing n display codes, where 0 < n < 10 . If n < 9 , the number is right justified and leading zeros are automatically displayed. For example, the display code for 13 is 010079 while for 144 it is 010106106

      Write a program that reads the display codes of two numbers, and prints the display code of their sum.

      Input

      Your program will be tested on one or more test cases. Each test case is specified on a single line in the form of A+B= where both A and B are display codes for decimal numbers a and b respectively where 0 < a , b < a + b < 1, 000, 000, 000 . The last line of the input file is the word "BYE" (without the double quotes.)

      Output

      For each test case, print A+B=C where C is the display code for a + b .

      Example

      Input:
      010079010+010079=
      106010+010=
      BYE
      
      Output:
      010079010+010079=010106106
      106010+010=106093
      

      Added by:Ahmed Aly
      Date:2009-07-03
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ANARC 2008









      SPOJ Problem Set (classical)

      4551. Match Maker

      Problem code: ANARC08C

      In Computer Science, pattern matching is the act of checking if a certain sequence conforms (matches) a given pattern. Patterns are usually specified using a language based on regular expression. In this problem, we'll use a simple regular expression to express patterns on sequences of decimal digits. A pattern is a sequence of one or more decimal digits '0' ...'9', asterisks '*', and hash signs '#'. A '*' denotes a sequence of an even number of digits, whereas a '#' denotes a sequence of an odd number of digits. For example, the pattern "129" only matches the sequence 129. The pattern "1*3" matches all sequences beginning with 1, ending with 3, and having an even number of decimal digits between the first and last digits. As another example, the pattern "#55" matches the sequences 155, 12355, 1234555, but none of the sequences 55, 1255, 123455. Your task is to write a program to find if a given sequence matches a given pattern.

      Input

      Your program will be tested on one or more data sets. Each data set contains a single pattern and one or more sequences to match. The first line of each data set specifies the pattern, and the remaining lines specify the sequences to match against that pattern. The end of a data set (except the last) is identified by the word "END" (without the double quotes.) The end of the last data set is identified by the word "QUIT". All lines are 100,000 characters long or shorter.

      Output

      k.s. result

      Where k is the test case number (starting at one,) and s is the sequence number (starting at one within each test case,) and result is either the word "match" if the given string matches the pattern, or the word "not" if it doesn't.

      Example

      Input:
      129
      1299
      129
      1129
      END
      1*3
      123
      1223
      END
      #55
      155
      12355
      55
      1255
      QUIT
      
      Output:
      1.1. not
      1.2. match
      1.3. not
      2.1. not
      2.2. match
      3.1. match
      3.2. match
      3.3. not
      3.4. not
      

      Added by:Ahmed Aly
      Date:2009-07-03
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ANARC 2008









      SPOJ Problem Set (classical)

      4552. Adding up Triangles

      Problem code: ANARC08D


      Take a look at the triangle on the left of the figure below. It is made of 9 (unit) triangles arranged in three rows (N = 3 ). Needless to say, a unit triangle is a triangle with N = 1 .

      If you study the figure for few seconds, you'll realize that you can find 13 different triangles (which we'll call sub-triangles.) Of these 13 sub-triangles we have: Nine unit triangle; three with N = 2 , and one with N = 3 . The following table lists the number of sub-triangles in arrangements with N < 5 .

      # of Rows:            N = 1   N = 2   N = 3   N = 4
      # of Sub-triangles: 	1 	5 	13 	27 
      

      Let's define the value of a unit triangle to be the integer value written in that triangle. In general, the value of a triangle is the sum of values in all its unit triangles. The triangle on the right is the same as the other one but with the sub-triangle having the largest value being highlighted. Write a program to determine the sub-triangle with the largest value.

      Input

      Your program will be tested on one or more test cases. Each test case is specified in a single line made of integers (separated by spaces.) The first integer is the number of rows in the test case, and the remaining integers are the values of the unit triangles specified in a top-down, left-to-right order. (the first test case in the example below is the same as the one in the figure.) The last line of the input file contains the number 0 (which is not part of the test cases.)

      The maximum number of rows is 400. The absolute value of a unit triangle is less than 1000.

      Output

      For each test case, print the result using the following format:

      k. V

      where k is the test case number (starting at 1,) is a single space, and V is the maximum value of a sub-triangle in that test case.

      Example

      Input:
      3 6 -24 0 12 -10 12 40 -4 6 4 1 1 -1 1 1 -1 1 -1 1 1 -1 1 -1 1 -1 1 0

      Output:
      1. 54 2. 4

      Added by:Ahmed Aly
      Date:2009-07-03
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ANARC 2008









      SPOJ Problem Set (classical)

      4555. Einbahnstrasse

      Problem code: ANARC08F


      Einbahnstrasse (German for a one-way street) is a street on which vehicles should only move in one direction. One reason for having one-way streets is to facilitate a smoother flow of traffic through crowded areas. This is useful in city centers, especially old cities like Cairo and Damascus. Careful planning guarantees that you can get to any location starting from any point. Nevertheless, drivers must carefully plan their route in order to avoid prolonging their trip due to one-way streets. Experienced drivers know that there are multiple paths to travel between any two locations. Not only that, there might be multiple roads between the same two locations. Knowing the shortest way between any two locations is a must! This is even more important when driving vehicles that are hard to maneuver (garbage trucks, towing trucks, etc.)

      You just started a new job at a car-towing company. The company has a number of towing trucks parked at the company's garage. A tow-truck lifts the front or back wheels of a broken car in order to pull it straight back to the company's garage. You receive calls from various parts of the city about broken cars that need to be towed. The cars have to be towed in the same order as you receive the calls. Your job is to advise the tow-truck drivers regarding the shortest way in order to collect all broken cars back in to the company's garage. At the end of the day, you have to report to the management the total distance traveled by the trucks.

      Input

      Your program will be tested on one or more test cases. The first line of each test case specifies three numbers (N , C , and R ) separated by one or more spaces. The city has N locations with distinct names, including the company's garage. C is the number of broken cars. R is the number of roads in the city. Note that 0 < N < 100 , 0 <= C < 1000 , and R < 10000 . The second line is made of C + 1 words, the first being the location of the company's garage, and the rest being the locations of the broken cars. A location is a word made of 10 letters or less. Letter case is significant. After the second line, there will be exactly R lines, each describing a road. A road is described using one of these three formats:

      A --v-> B
      A <-v-- B
      A <-v-> B

      A and B are names of two different locations, while v is a positive integer (not exceeding 1000) denoting the length of the road. The first format specifies a one-way street from location A to B , the second specifies a one-way street from B to A , while the last specifies a two-way street between them. A , "the arrow", and B are separated by one or more spaces. The end of the test cases is specified with a line having three zeros (for N , C , and R .)

      The test case in the example below is the same as the one in the figure.

      Output

      For each test case, print the total distance traveled using the following format:

      k. V

      Where k is test case number (starting at 1,) is a space, and V is the result.

      Example

      Input:
      4 2 5
      NewTroy Midvale Metrodale
      NewTroy   <-20-> Midvale
      Midvale   --50-> Bakerline
      NewTroy    <-5-- Bakerline
      Metrodale <-30-> NewTroy
      Metrodale  --5-> Bakerline
      0 0 0
      
      Output:
      1. 80
      

      Added by:Ahmed Aly
      Date:2009-07-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ANARC 2008









      SPOJ Problem Set ()

      4556. Think I will Buy Me a Football Team

      Problem code: ANARC08G

      Falling Stocks. Bankrupted companies. Banks with no Cash. Seems like the best time to invest: "Think I'll buy me a football team!"

      No seriously, I think I have the solution to at least the problem of cash in banks. Banks nowadays are all owing each other great amounts of money and no bank has enough cash to pay other banks' debts even though, on paper at least, they should have enough money to do so. Take for example the inter-bank loans shown in figure (a). The graph shows the amounts owed between four banks (A ...D). For example, A owes B 50M while, at the same time, B owes A 150M. (It is quite common for two banks to owe each other at the same time.) A total amount of 380M in cash is needed to settle all debts between the banks.

      In an attempt to decrease the need for cash, and after studying the example carefully, I concluded that there's a lot of cash being transferred unnecessarily. Take a look:

      1. C owes D the same amount as D owes A, so we can say that C owes A an amount of 30M and get D out of the picture.

      2. But since A already owes C 100M, we can say that A owes C an amount of 70M.

      3. Similarly, B owes A 100M only, (since A already owes B 50M.) This reduces the above graph to the one shown in figure (b) which reduces the needed cash amount to 190M (A reduction of 200M, or 53%.)

      4. I can still do better. Rather than B paying A 100M and A paying 70M to C, B can pay 70M (out of A's 100M) directly to C. This reduces the graph to the one shown in figure (c). Banks can settle all their debts with only 120M in cash. A total reduction of 260M or 68%. Amazing!

      I have data about inter-bank debts but I can't seem to be able to process it to obtain the minimum amount of cash needed to settle all the debts. Could you please write a program to do that?

      Input

      Your program will be tested on one or more test cases. Each test case is specified on N + 1 lines where N < 1, 000 is the number of banks and is specified on the first line. The remaining N lines specifies the inter-bank debts using an NXN adjacency matrix (with zero diagonal) specified in row-major order. The ith row specifies the amounts owed by the ith bank. Amounts are separated by one or more spaces. All amounts are less than 1000. The last line of the input file has a single 0.

      Output

      For each test case, print the result using the following format:

      k. B A

      where k is the test case number (starting at 1,) is a space character, B is the amount of cash needed before reduction and A is the amount of cash after reduction.

      Example

      Input:
      4
        0  50 100   0
      150   0  20   0
        0   0   0  30
       30   0   0   0
      0
      
      Output:
      1. 380 120
      

      Added by:Ahmed Aly
      Date:2009-07-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ANARC 2008









      SPOJ Problem Set ()

      4557. Musical Chairs

      Problem code: ANARC08H

      In the traditional game of Musical Chairs, N + 1 children run around N chairs (placed in a circle) as long as music is playing. The moment the music stops, children run and try to sit on an available chair. The child still standing leaves the game, a chair is removed, and the game continues with N children. The last child to sit is the winner.

      In an attempt to create a similar game on these days' game consoles, you modify the game in the following manner: N Children are seated on N chairs arranged around a circle. The chairs are numbered from 1 to N . Your program pre-selects a positive number D . The program starts going in circles counting the children starting with the first chair. Once the count reaches D , that child leaves the game, removing his/her chair. The program starts counting again, beginning with the next chair in the circle. The last child remaining in the circle is the winner.

      For example, consider the game illustrated in the figure above for N = 5 and D = 3 . In the figure, the dot indicates where counting starts and × indicates the child leaving. Starting off, child #3 leaves the game, and counting restarts with child #4. Child #1 is the second child to leave and counting restart with child #2 resulting in child #5 leaving. Child #2 is the last to leave, and child #4 is the winner. Write a program to determine the winning child given both N and D .

      Input

      Your program will be tested on one or more test cases. Each test case specifies two positive integers N and D on a single line, separated by one or more spaces, where N, D < 1,000,000 .

      The last line of the input file contains two 0's and is not part of the test cases.

      Output

      For each test case, write the winner using the following format:

      N D W

      Where N and D are as above, is a space character, and W is the winner of that game.

      Example

      Input:
      5 3
      7 4
      0 0
      
      Output:
      5 3 4
      7 4 2
      

      Added by:Ahmed Aly
      Date:2009-07-04
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ANARC 2008









      SPOJ Problem Set (classical)

      4558. I Speak Whales

      Problem code: ANARC08I

      According to Wikipedia, a Walsh matrix is a specific square matrix, with dimensions equal to a power of 2, the entries of which are +1 or -1, and the property that the dot product of any two distinct rows (or columns) is zero. Below are the first three Walsh Matrices. (The gray lines are imaginary lines for illustration purpose only.)

      A Walsh Matrix of size 2^(N+1) can be constructed as the "union" of 4 Walsh Matrices of size 2^N arranged such that the lower right matrix is inverted whereas the other 3 matrices are not, i.e.:

      Let's number the rows of a given Walsh Matrix from the top starting with row 0. Similarly, let's number the columns of the matrix from the left starting with column 0. Given the four integers N , R , S , and E , write a program that will construct a Walsh Matrix of size 2^N and will print the sum of all the numbers in row #R between columns #S and #E (inclusive.)

      Input

      Your program will be tested on one or more test cases. Each test case is specified using a single line listing four integers in the following order: N , R , S , and E , where 0 <= N <= 60 , 0 <= R < 2^N , 0 <= S <= E < 2N , and E - S <= 10,000 . The last line of the input file has four -1's and is not part of the test cases.

      Output

      For each test case, print the output on a single line.

      Example

      Input:
      2 1 0 1
      48 0 0 47
      -1 -1 -1 -1
      
      Output:
      0
      48
      

      Added by:Ahmed Aly
      Date:2009-07-04
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ANARC 2008









      SPOJ Problem Set (classical)

      4559. A Day at the Races

      Problem code: ANARC08J

      Formula One is the highest class of car racing sports. A typical Formula One season consists of a series of races called "Grands Prix" which constructors like Ferrari, Renault, etc. and others participate with one or more cars driven by the best drivers in the world. During the season, teams compete in two parallel championships: the drivers championship and the teams championship.

      In the drivers championship, drivers compete to achieve the maximum total number of points by the end of the season, the rules of the competition states that the top eight drivers at each Grand Prix receive 10,8,6,5,4,3,2,1 points respectively. In case of points tie, the driver with the highest number of first places leads. If still tied, then the highest second places, and so on till the highest 8th places. If still tied, then drivers are sorted lexicographically by their last and then by their first names.

      After each race, the points received by each driver are added to his team's pocket, and at the end of the season the team with the highest number of points wins the teams championship. To add excitement to the season, team sponsors are allowed to buy drivers from other teams even within the same season. In case of points tie between teams, teams are sorted lexicographically by their names. In this problem, you are given data of a formula one season and you're asked to process these data according to the rules above to determine both the drivers and teams standings.

      Input

      Your program will be tested on one or more data-sets, each representing a Formula One season. All input lines are 255 characters or less. Studying the sample I/O you'll discover that the first line of each season has an integer N , where 0 < N < 32 and representing the number of Grands Prix in that season. For each Grand Prix, the name of the Grand Prix appears on a line by itself (maximum length is 64 characters) followed by a table of the first name, last name and team name of the top eight drivers, from 1 to 8, in that Grand Prix. Each of the first and last names is a sequence of printable ASCII characters, no longer than 12 characters, and contains no spaces. Each team name is a sequence of printable ASCII characters, no longer than 18 characters, and may contain spaces (but no leading or trailing spaces.) Each team name is followed by a single period '.' which is not part of the name. Trailing white space may follow. A line of three -'s follows the listing of each Grand Prix. The last line of the input file contains a single zero.

      Output

      For each data set in the input you must print "Season k :" where k is the data-set number (starting from 1.) The next line must state "Drivers Standing:". On subsequent lines list the drivers standing for that season. For each driver, print their first and last names separated by exactly one space and left justified in a field of width 25, followed by a single space, followed by the total number of points achieved by the driver during the season. The drivers standing should be followed by a blank line.

      The next line must state "Teams Standing:" On subsequent lines list the teams standing for the that season. For each team, print the team name left justified in a field of width 25, followed by a single space, followed by the total number of points the team has scored during the season. The teams standing should be followed by a blank line.

      Example

      Input:
      2 
      FORMULA 1 Gran Premio Telefonica de Espana 2006
      Pos  Driver                    Team
      1    Fernando Alonso           Renault.
      2    Michael Schumacher        Ferrari.
      3    Giancarlo Fisichella      Renault.
      4    Felipe Massa              Ferrari.
      5    Kimi Raikkonen            McLaren-Mercedes.
      6    Jenson Button             Honda.
      7    Rubens Barrichello        Honda.
      8    Nick Heidfeld             Sauber-BMW.
      ---
      FORMULA 1 Grand Prix de Monaco 2006
      Pos  Driver                    Team
      1    Fernando Alonso           Renault.
      2    Jaun-Pablo Montoya        McLaren-Mercedes.
      3    David Coulthard           RBR-Ferrari.
      4    Rubens Barrichello        Honda.
      5    Michael Schumacher        Ferrari.
      6    Giancarlo Fisichella      Renault.
      7    Nick Heidfeld             Sauber-BMW.
      8    Ralf Schumacher           Toyota.
      ---
      0
      
      Output:
      Season 1:
      Drivers Standing:
      Fernando Alonso          20
      Michael Schumacher       12
      Giancarlo Fisichella     9
      Jaun-Pablo Montoya       8
      Rubens Barrichello       7
      David Coulthard          6
      Felipe Massa             5
      Kimi Raikkonen           4
      Jenson Button            3
      Nick Heidfeld            3
      Ralf Schumacher          1
      
      Teams Standing:
      Renault                  29
      Ferrari                  17
      McLaren-Mercedes         12
      Honda                    10
      RBR-Ferrari              6
      Sauber-BMW               3
      Toyota                   1
      

      Added by:Ahmed Aly
      Date:2009-07-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:ANARC 2008









      SPOJ Problem Set (classical)

      4574. Riding in cycles

      Problem code: CYCLERUN

      There are N cities, numbered from 1 to N, in the country you are living. Each pair of the cities is connected with exactly one road. However, each road is a one-way road, so it is either possible to go directly from A to B or from B to A for each pair of cities (A, B).

      You are living in city #1 and you are practicing for upcoming cycling marathon, so you want to construct the following training plan:

      First day you have to ride over 3 roads starting from and finishing in city #1.

      Second day you have to ride over 4 roads in the same manner.

      Third day you have to ride over 5 roads.

      ...

      The last, (N-2)-th, day you have to ride over N roads starting from and finishing in city #1.

      You don't like to visit the same city more than once per day, so you have to find a training route for each day that passes through each city at most once. City #1 should appear only at the start and at the end of each route.

      Write the program that, given the layout of the network, outputs training route for each day, or writes "impossible" if such training plan is not achievable.

      Input

      The first line of input contains the integer N (3 ≤ N ≤ 1000), number of cities.

      Each of the next N lines contains exactly N characters that describes network layout. j-th character in i-th of these lines is '1' if it is possible to ride from city number i to city number j, or '0' otherwise.

      Output

      You should output training route for each day in a separate line. Training route consists of space separated integers - numbers of the cities in order they should be visited. Each training route starts and ends with 1.

      If there is no achievable training plan, output word 'impossible' in a single line, instead.

      Example

      Input:
      5
      01000
      00011
      11001
      10100
      10010
      
      Output:
      1 2 5 1
      1 2 4 3 1
      1 2 4 3 5 1
      

      Added by:Luka Kalinovcic
      Date:2009-07-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      4580. ABCDEF

      Problem code: ABCDEF

      You are given a set S of integers between -30000 and 30000 (inclusive).

      Find the total number of sextuples  that satisfy: 

       

      Input

      The first line contains integer N (1 ≤ N ≤ 100), the size of a set S.

      Elements of S are given in the next N lines, one integer per line. Given numbers will be distinct.

      Output

      Output the total number of plausible sextuples.

      Examples

      Input:
      1
      1
      
      Output:
      1
      Input:
      2
      2
      3
      
      Output:
      4
      Input:
      2
      -1
      1
      
      Output:
      24
      Input:
      3
      5
      7
      10
      
      Output:
      10



      Added by:Luka Kalinovcic
      Date:2009-07-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      4585. Star Wars

      Problem code: GCJ08C

      Near the planet Mars, in a faraway galaxy eerily similar to our own, there is a fight to the death between the imperial forces and the rebels. The rebel army has N ships which we will consider as points (xi, yi, zi). Each ship has a receiver with power pi. The rebel army needs to be able to send messages from the central cruiser to all the ships, but they are tight on finances, so they cannot afford a strong transmitter.

      If the cruiser is placed at (x, y, z), and one of the other ships is at (xi, yi, zi) and has a receiver of power pi, then the power of the cruiser's transmitter needs to be at least:

      (|xi - x| + |yi - y| + |zi - z|) / pi

      Your task is to find the position for the cruiser that minimizes the power required for its transmitter, and to output that power.

      Input

      The first line of input gives the number of cases, T. T test cases follow.

      Each test case contains on the first line the integer N, the number of ships in the test case.

      N lines follow, each line containing four integer numbers xi, yi, zi and pi, separated by single spaces. These are the coordinates of the i-th ship, and the power of its receiver. There may be more than one ship at the same coordinates.

      1 ≤ T ≤ 20
      0 ≤ xi, yi, zi ≤ 10^6
      1 ≤ pi ≤ 10^6
      1 ≤ N ≤ 1000

      Output

      For each input case, you should output:

      Case #X: Y

      where X is the number of the test case and Y is the minimal power that is enough to reach all the fleet's ships. Answers with a relative or absolute error of at most 10-6 will be considered correct.

      Example

      Input:
      3
      4
      0 0 0 1
      1 2 0 1
      3 4 0 1
      2 1 0 1
      1
      1 1 1 1
      3
      1 0 0 1
      2 1 1 4
      3 2 3 2
      
      Output:
      Case #1: 3.500000
      Case #2: 0.000000
      Case #3: 2.333333
      

      Added by:Ahmed Aly
      Date:2009-07-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Google Code Jam 2008









      SPOJ Problem Set (classical)

      4586. Texas Trip

      Problem code: WLOO0707

      After a day trip with his friend Dick, Harry noticed a strange pattern of tiny holes in the door of his SUV. The local American Tire store sells fiberglass patching material only in square sheets. What is the smallest patch that Harry needs to fix his door?

      Assume that the holes are points on the integer lattice in the plane. Your job is to find the area of the smallest square that will cover all the holes.

      Input

      The first line of input contains a single integer T expressed in decimal with no leading zeroes, denoting the number of test cases to follow. The subsequent lines of input describe the test cases.

      Each test case begins with a single line, containing a single integer n expressed in decimal with no leading zeroes, the number of points to follow; each of the following n lines contains two integers x and y, both expressed in decimal with no leading zeroes, giving the coordinates of one of your points.

      You are guaranteed that T <= 30 and that no data set contains more than 30 points. All points in each data set will be no more than 500 units away from (0,0).

      Output

      Print, on a single line with two decimal places of precision, the area of the smallest square containing all of your points. An answer will be accepted if it lies within 0.01 of the correct answer.

      Example

      Input:
      2
      4
      -1 -1
      1 -1
      1 1
      -1 1
      4
      10 1
      10 -1
      -10 1
      -10 -1
      
      Output:
      4.00
      242.00
      

      Added by:Ahmed Aly
      Date:2009-07-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:14 July, 2007 - Waterloo local contest









      SPOJ Problem Set (classical)

      4587. Electric Fences

      Problem code: FENCE3

      Farmer John has decided to construct electric fences. He has fenced his fields into a number of bizarre shapes and now must find the optimal place to locate the electrical supply to each of the fences.

      A single wire must run from some point on each and every fence to the source of electricity. Wires can run through other fences or across other wires. Wires can run at any angle. Wires can run from any point on a fence (i.e., the ends or anywhere in between) to the electrical supply.

      Given the locations of all F (1 <= F <= 150) fences (fences are always parallel to a grid axis and run from one integer gridpoint to another, 0 <= X,Y <= 100), your program must calculate both the total length of wire required to connect every fence to the central source of electricity and also the optimal location for the electrical source.

      The optimal location for the electrical source might be anywhere in Farmer John's field, not necessarily on a grid point.

      Input

      The first line contains F, the number of fences.
      F subsequent lines each contain two X,Y pairs each of which denotes the endpoints of a fence.

      Output

      On a single line, print three space-separated floating point numbers, each with a single decimal place. Presume that your computer's output library will round the number correctly.

      The three numbers are:

      * the X value of the optimal location for the electricity,
      * the Y value for the optimal location for the electricity, and
      * the total (minimum) length of the wire required.

      Example

      Input:
      3
      0 0 0 1
      2 0 2 1
      0 3 2 3
      
      Output:
      1.0 1.6 3.7
      

      Added by:Ahmed Aly
      Date:2009-07-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:USACO









      SPOJ Problem Set (classical)

      4588. SETI

      Problem code: NWERC04H

      For some years, quite a lot of work has been put into listening to electromagnetic radio signals received from space, in order to understand what civilizations in distant galaxies might be trying to tell us. One signal source that has been of particular interest to the scientists at Universit´e de Technologie Spatiale is the Nebula Stupidicus.

      Recently, it was discovered that if each message is assumed to be transmitted as a sequence of integers a0, a1, ...an-1 the function f(k) = (mod p) always evaluates to values 0 <= f(k) <= 26 for 1 <= k <= n, provided that the correct value of p is used. n is of course the length of the transmitted message, and the ai denote integers such that 0 <= ai < p. p is a prime number that is guaranteed to be larger than n as well as larger than 26. It is, however, known to never exceed 30 000.

      These relationships altogether have been considered too peculiar for being pure coincidences, which calls for further investigation.

      The linguists at the faculty of Langues et Cultures Extraterrestres transcribe these messages to strings in the English alphabet to make the messages easier to handle while trying to interpret their meanings. The transcription procedure simply assigns the letters a..z to the values 1..26 that f(k) might evaluate to, such that 1 = a, 2 = b etc. The value 0 is transcribed to ’*’ (an asterisk). While transcribing messages, the linguists simply loop from k = 1 to n, and append the character corresponding to the value of f(k) at the end of the string.

      The backward transcription procedure, has however, turned out to be too complex for the linguists to handle by themselves. You are therefore assigned the task of writing a program that converts a set of strings to their corresponding Extra Terrestial number sequences.

      Input

      On the first line of the input there is a single positive integer N, telling the number of test cases to follow. Each case consists of one line containing the value of p to use during the transcription of the string, followed by the actual string to be transcribed. The only allowed characters in the string are the lower case letters ’a’..’z’ and ’*’ (asterisk). No string will be longer than 70 characters.

      Output

      For each transcribed string, output a line with the corresponding list of integers, separated by space, with each integer given in the order of ascending values of i.

      Example

      Input:
      3
      31 aaa
      37 abc
      29 hello*earth
      
      Output:
      1 0 0
      0 1 0
      8 13 9 13 4 27 18 10 12 24 15
      

      Added by:Ahmed Aly
      Date:2009-07-15
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:NWERC 2004









      SPOJ Problem Set (classical)

      4644. Proving Equivalences

      Problem code: PMATRIX

      Consider the following exercise, found in a generic linear algebra textbook.Let A be an n × n matrix. Prove that the following statements are equivalent:

      • (a) A is invertible.
      • (b) Ax = b has exactly one solution for every n × 1 matrix b.
      • (c) Ax = b is consistent for every n × 1 matrix b.
      • (d) Ax = 0 has only the trivial solution x = 0.

      The typical way to solve such an exercise is to show a series of implications. For instance,one can proceed by showing that (a) implies (b), that (b) implies (c), that (c) implies (d),and finally that (d) implies (a). These four implications show that the four statements are equivalent. Another way would be to show that (a) is equivalent to (b) (by proving that (a) implies (b) and that (b) implies (a)), that (b) is equivalent to (c), and that (c) is equivalent to (d).


      However, this way requires proving six implications, which is clearly a lot more work than just proving four implications! I have been given some similar tasks, and have already started proving some implications. Now I wonder, how many more implications do I have to prove? Can you help me determine this ?

      Input

      On the first line one positive number: the number of testcases, at most 100. After that per testcase:

      • One line containing two integers n (1 ≤ n ≤ 20 000) and m (0 ≤ m ≤ 50 000): the number of statements and the number of implications that have already been proved.
      • m lines with two integers s1 and s2 (1 ≤ s1, s2 ≤ n and s1 = s2) each, indicating that it has been proved that statement s1 implies statement s2.

      Output

      Per testcase:
      One line with the minimum number of additional implications that need to be proved in order to prove that all statements are equivalent.

      Example

      Input:
      2
      4 0
      3 2
      1 2
      1 3

      Output:
      4
      2

      Added by:Hemant Verma
      Date:2009-07-25
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:NWERC 2008









      SPOJ Problem Set (classical)

      4656. Cross Mountain Climb

      Problem code: CCROSS

      Somewhere in the neighborhood we have a very nice mountain that gives a splendid view over the surrounding area. There is one problem though: climbing this mountain is very difficult, because of rather large height differences. To make more people able to climb the mountain and enjoy the view, we would like to make the climb easier. To do so, we will model the mountain as follows: the mountain consists of n adjacent stacks of stones, and each of the stacks is hi high. The successive height differences are therefore hi+1 − hi (for 1 <=  i <=  n − 1). We would like all absolute values of these height differences to be smaller than or equal to some number d.


      We can do this by increasing or decreasing the height of some of the stacks. The first stack (the starting point) and the last stack (the ending point) should remain at the same height as they are initially. Since adding and removing stones requires a lot of effort, we would like to minimize the total number of added stones plus the total number of removed stones. What is this minimum number?

      Input

      On the first line one positive number: the number of testcases, at most 100. After that per testcase:

      • One line with two integers n (2 <= n <= 100) and d (0  <= d <= 10^9): the number of stacks of stones and the maximum allowed height difference.
      • One line with n integers hi (0 <= hi <= 10^9): the heights of the stacks.

       

      Output

      Per testcase:
             One line with the minimum number of stones that have to be added or removed or “impossible” if it is impossible to achieve the goal.

       

      Example

      Input:
      3
      10 2
      4 5 10 6 6 9 4 7 9 8
      3 1
      6 4 0
      4 2
      3 0 6 3

      Output:
      6
      impossible
      4
      Problem text...

       

      Problem text...

      Added by:Hemant Verma
      Date:2009-07-27
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:NWERC 2008 Regionals









      SPOJ Problem Set (classical)

      4657. Gas Wars

      Problem code: GASWARS


      As the result of the gas wars the following agreement was made. The transit of the gas was allowed under the following conditions. There are n transit nodes and m pipes connecting those nodes. There k nodes where the gas enters and l nodes where it should be moved. Each pipe has a carrying capacity of ci cubic meters of gas per day. Gas can go through the pipes in either direction. It is needed to move g cubic meters of gas in total through the pipeline every day. The cost of the transit is defined as maxC*100 thousand dollars, where maxC – maximum of carrying capacities of the used in the transit pipes (even those which are not fully used). You are to find the minimum possible cost of transit for the given pipeline.

      Input

      The first line of the input file contains t – the amount of test cases. The description of each test case follows. The first line of each test case contains five integers separated by spaces – n, m, k, l, g. Then m lines containing three integers a, b, c follow. Each lines means that nodes with numbers a and b are connected by the pipe with the carrying capacity of c. Next line contains k integers – the numbers of nodes where the gas should enter the pipeline. The last line of the test case contains l integers – the numbers of nodes where the gas should be moved. The gas can enter the pipeline in any of the k entrance nodes and can be moved to any of the l exit nodes. The nodes are numbered from 1 to n.

      Constraints

      1 <= t <= 20
      2 <= n <= 100
      1 <= m <= n*(n-1)/2
      1 <= k, l <= n/2
      1 <= g, c <= 1000000

      Output

      For each test case output a single integer on a separate line – the minimum cost of transit in thousands of dollars. If the transit of the needed volume is impossible, then output -1.

      Example

      Input:
      1
      6 8 1 1 1
      1 2 1
      1 3 2
      2 4 3
      2 5 3
      3 4 4
      3 5 2
      4 6 4
      5 6 1
      1
      6
      
      Output:
      200
      

      Added by:Spooky
      Date:2009-07-28
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Advancement Spring 2009, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      4658. Help Hemant Verma

      Problem code: HHEMANT

      Steganography is a method of cryptography where a message or entire document can be hidden inside of another file or image which shows no evidence that there is data hidden in it. Typically, the message or document to be sent is first encrypted and compressed, and then combined with an existing file in the bits that are less significant.

      Hemant Verma is a secret agent who wants to send some classified information to his head office , the amount of data is very large , he needs your help to encode the message into image . You will be given an "image" and you will encode a given message into it and return the new image. The returned image should be in the same format as the original image.


      The image will be in the format of a string of various lines where each three digits represent a number from 0 to 255, inclusive (leading zeros will be added as necessary), which is a pixel value in the image.You will also be given a  message which contains the message you would like to encode into the image.

      You will first encode the message into numbers representing the characters in the message - spaces will be 0, 'A'-'Z' will be 1-26, 'a'-'z' will be 27-52, '0'-'9' will be 53-62, and 63 will be used for any space after the message. All these numbers can be represented in binary with 6 digits. You will put each pair of bits (representing a number between 0 and 3) into the lowest two bits of the values in the image. For each character, you will put in the lowest two bits, then the middle two, then the highest two, and then continue to the next character. You will put them in the lowest two bits of the first pixel on the first row, then the second pixel on the first row, and so on until you get to the end of the first row, then the first pixel on the second row, and so on. Once you are out of characters, continue substituting the lowest two bits of each pixel value as if the current character were represented by number 63.

      Input

      First line contain T representing number of test case , for each test case first line contain message  then follow N the number of lines for image then following N line contain image.


      0<Length(message)<1000
      0 < T,N < 10000

      Output

      For each test case output the image in same format as input.

      Example

      Input:
      2
      hi
      1
      255123212001201222
      hi
      2
      255123212
      001201222

      Output:
      254120214003200222
      254120214
      003200222

      Added by:Hemant Verma
      Date:2009-07-28
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Modified Topcoder Problem









      SPOJ Problem Set (classical)

      4666. Wireless

      Problem code: WIRELESS

      Bob is sitting at home with his computer. He would like to experience more social interaction, so he is planning a trip to a coffee shop with his computer.

      Bob has lots of data about wireless networks and coffee shops in the city. In Bob’s city, there is one coffee shop at every intersection of streets. Specifically, Bob happens to live in a city with M streets (1 ≤ M ≤ 30000) that run east and west, and N streets (1 ≤ N ≤ 1000) that run north and south. As an added benefit, the distance between consecutive parallel streets is 1 metre (it is a very compact city).

      It also turns out that inside K (1 ≤ K ≤ 1000) of the coffee shops, there is a wireless network station. Each wireless network station will have a particular bitrate B (1 ≤ B ≤ 1000) and can reach R metres (1 ≤ R ≤ 30000) from the coffee shop. In other words, a wireless network station from one coffee shop forms a circle with radius R centered at that particular coffee shop. Moreover, if someone is at distance R, the wireless network would be available, but if someone is at a distance larger than R, they cannot access that wireless point.

      You can assume that each coffee shop has at most one wireless network stationed in it, but that multiple wireless networks may be available while sitting in that one coffee shop, due to the proximity of other wireless network stations.

      Bob has a special device in his computer that can use all of the available bitrates of as many wireless networks as he can connect to.

      Bob would like to find out the maximum bitrate he can obtain, and how many coffee shops would have that maximum capacity.

      Input

      On the first line of input, you will be given the integer M, the number of east-west streets. On the second line of input, you will be given the integer N, the number of north-south streets. On the third line of input, you will be given the integer K, the number of coffee shops with a wireless network. On the next K lines, you will have 4 integers per line. The first integer x on each line represents the north-south street on which the coffee shop is located, where 1 ≤ xN. The second integer, y, on each line represents the east-west street on which the coffee shop is located, where 1 ≤ yM. The third integer, R, on each line represents the radius of the wireless network from this particular coffee shop. The fourth integer, B, on each line represents the bitrate of the wireless network from this particular coffee shop.

      Output

      The output will be two lines long. The first line of output will be the integer representing the maximum bitrate that can be obtained over all coffee shops. The second line of output will be the number of coffee shops where this maximum bitrate can be obtained.

      Sample Input:

      3
      5
      3
      1 3 2 5
      3 1 2 7
      5 1 1 5

      Sample Output:

      12
      5

      Explanation:

      In the figure below, notice that the five coffee shops/intersections marked with a dark circle have total bitrates of 12.


      Added by:Brian Bi
      Date:2009-08-03
      Time limit:2s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:2009 Canadian Computing Competition Stage 1 - Question S5









      SPOJ Problem Set (classical)

      4667. Gremlins

      Problem code: GREMLINS

      Gremlins are small funny furry creatures. Once they were considered to be evil but that time has past and most gremlins live a decent family life now. There are N distinct types of gremlins.

      Their origin is rather mysterious. Legend says that T years ago, N gremlins, one of each type, were born in a lab accident.

      Their reproduction method is, however, well studied. No mating ritual is required for gremlins to multiply. All they need is a few drops of water and the magic happens.

      Once a type i gremlin starts its reproduction process, Ki small furry balls are created. For each furry ball we know what is the type of gremlin that will hatch from the furry ball and how long will it take for that to happen. Unfortunately, the original gremlin dies in the process. A type i gremlin will start its reproduction process exactly Yi years after it is born (ie. hatched from the furry ball).

      Knowledge about the ancestors of a gremlin is passed on genetically, so each gremlin knows a list of his ancestors as soon as it is born.

      Write a program that will find the length of the longest list of ancestors among all gremlins that ever lived (gremlins that still live are included, but unhatched furry balls are not), given the information about reproduction process and time elapsed since the lab accident that created initial gremlins, assuming all gremlins that were supposed to hatch this year have already hatched.

      Input

      The first line contains two integers N and T (1 ≤ N ≤ 100, 1 ≤ T ≤ 1015), the number of gremlin types and the number of year that has passed since the lab accident.

      The next 3·N lines give reproduction details for each gremlin type.

      The first line of i-th block contains two integers Ki and Yi (1 ≤ Yi ≤ 1000, 1 ≤ Ki ≤ 1000).

      The second line contains Ki integers representing gremlin type for each furry ball.

      The third line contain Ki integers between 1 and 1000 representing hatching time for each furry ball, in years.

      Output

      Output the length of the longest list of ancestors among all gremlins that ever lived in a single line.

      Examples

      Input:
      1 42
      1 10
      1
      5
      
      
      
      
      
      
      
      Output:
      2
      Input:
      2 42
      1 10
      1
      5
      1 5
      1
      5
      
      
      
      
      Output:
      3
      Input:
      3 8
      4 5
      1 2 3 2
      1 2 1 3
      1 1
      3
      1
      2 1
      1 2
      2 1
      
      Output:
      4

      Added by:Luka Kalinovcic
      Date:2009-08-06
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      4669. Cross Mountain Climb Extreme

      Problem code: CCROSSX


      Somewhere in the neighborhood we have a very nice mountain that gives a splendid view over the surrounding area. There is one problem though: climbing this mountain is very difficult, because of rather large height differences. To make more people able to climb the mountain and enjoy the view, we would like to make the climb easier. To do so, we will model the mountain as follows: the mountain consists of n adjacent stacks of stones, and each of the stacks is hi high. The successive height differences are therefore hi+1 − hi (for 1 ≤ i ≤ n−1). We would like all absolute values of these height differences to be smaller than or equal to some number d.

      We can do this by increasing or decreasing the height of some of the stacks. The first stack (the starting point) and the last stack (the ending point) should remain at the same height as they are initially. Since adding and removing stones requires a lot of effort, we would like to minimize the total number of added stones plus the total number of removed stones. What is this minimum number?

      Input

      On the first line one positive number: the number of test cases, at most 50. After that, for each test case:

      • One line with two integers n (2 ≤ n ≤ 10000) and d (0 ≤ d ≤ 10^9): the number of stacks of stones and the maximum allowed height difference.
      • One line with n integers hi (0 ≤ h≤ 10^9): the heights of the stacks.

      Output

      For each test case, output one line with the minimum number of stones that have to be added or removed, or “impossible” if it is impossible to achieve the goal.

      Example

      Input:
      3
      10 2
      4 5 10 6 6 9 4 7 9 8
      3 1
      6 4 0
      4 2
      3 0 6 3

      Output:
      6
      impossible
      4

      Added by:Lovro Puzar
      Date:2009-08-08
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Problem CCROSS with larger limits (originally from NWERC 2008)









      SPOJ Problem Set ()

      4672. Yanu in Movie theatre

      Problem code: FUNPROB

      Yanu is a great fan of Harry Potter.So on the day of the movie release, Yanu rushes to the movie theatre to watch the movie. On the release of the 6th movie, on reaching the theatre she found a long queue for tickets already.As the distirbution was about to start, the ticket counter did not have any change to start with. There are N+M people in queue,where N have Rs 10.00 and M have Rs 5.00. The ticket costs Rs 5.00.


      Now Yanu is math geek too , now she wonders What is the probability that the theatre can always provide change.

      Input

      Each line contain N and M , seperated by a space , End of Input is marked by 0 0 which should not be processed. Both N and M fits in integer range.

      Output

      For each input , output the respective probability upto 6 decimal digits.

      Example

      Input:
      1 0
      0 1
      41 41
      0 0

      Output:
      0.000000
      1.000000
      0.023810


      Added by:Hemant Verma
      Date:2009-08-15
      Time limit:1s
      Source limit:1024B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:A Classical Probability Problem









      SPOJ Problem Set (classical)

      4681. Twice

      Problem code: TWICE

      Given a string S, find the longest substring that appears at least twice in S (occurrences may overlap).

      Input

      The first line contains an integer L (1 ≤ L ≤ 200000), the length of S.

      The second line contains the string S, consisting of exactly L lowercase letters ('a'-'z').

      Output

      Output the length of the longest substring that appears at least twice in S. If there is no such substring, output 0.

      Example

      Input:
      11
      sabcabcfabc

      Output:
      3

      Input:
      18
      trutrutiktiktappop

      Output:
      4

      Added by:Lovro Puzar
      Date:2009-08-21
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Own problem









      SPOJ Problem Set (classical)

      4717. Grid Points in a Triangle

      Problem code: GPINTRI


      How many points (x, y) with non-negative integer coordinates satisfy y <= ax / b and x <= n?

      Input

      The first line contains an integer T (T <= 100000). T lines follow, each contains three positive integers n, a, b, where n, a, b <= 109 and a <= b.

      Output

      T lines, each contains a single integer denoting to the number of points according to the description.

      Example

      Input:
      5
      8 2 10
      8 4 4
      7 1 5
      713241932 127894722 957823358
      759096725 496666160 980149020

      Output:
      13
      45
      11
      33963383064794976
      145994569610845896

      Warning: enormous input/output data, be careful with certain languages


      Added by:Lox
      Date:2009-08-26
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6
      Resource:Own problem









      SPOJ Problem Set (classical)

      4784. Diophantine equation

      Problem code: HS09EQ


      Sometimes solving a Diophantine equation is very hard. But, for example, the equation 
      a+b2+c3+d4=n has a trivial solution for every value of n. Your task is to determine 
      the number of solutions of the equation for each given n, assuming that in the equation 
      all the values a, b, c and d are non-negative integers.

      Input

      The first line of input contains an integer T, representing the number of test cases (T<20000).

      The following T lines contain one non-negative integer n each, where n < 109.

       

      Output

      Output T lines, each containing the number of solutions of the respective equation for n.

      Example

      Input:
      5
      0
      1
      10
      100
      1000
      
      Output:
      1
      4
      19
      148
      1476

      Added by:Robert Gerbicz
      Date:2009-09-07
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 ERL JS NODEJS PERL 6 SCALA
      Resource:High School Programming League









      SPOJ Problem Set (classical)

      4785. Starship

      Problem code: HS09SHIP

      You are traveling by starship and at any time you are always moving in one of 6 directions: forwards, backwards, up, down, left, or right. In other words, during every second, one of the three coordinates of your position changes by exactly one unit. Let us suppose that you are at (x1,y1,z1) and you would like to reach (x2,y2,z2). Unfortunately, yours is only a first generation starship, which means that all movements are completely random, so at every second you will be moving with probability 1/6 forwards/backwards/up/down/left/right. Could you compute the probability that we will be at the destination in the n-th second?

      Input

      The first line contains integer T, representing the number of test cases. Each test case starts with a positive integer n, the next line gives the starting position of the starship, while the final one is the destination. It is known that: T<30000, 0<n<=1000. The absolute value of the x,y,z coordinates are smaller than 106. There are 5 input sets for 10 points.

      Output

      Output

      T lines, and in the i-th line give the required probability for the i-th test case. Use 10 digits after the decimal point!

      Example

      Input:
      5
      2
      0 0 0
      0 0 0
      4
      0 0 0
      0 0 0
      100
      2 -3 4
      -4 5 6
      100
      2 -3 4
      -4 5 7
      1000
      0 0 0
      0 0 0


      Output:
      0.1666666667
      0.0694444444
      0.0001389381
      0.0000000000
      0.0000208505

      Added by:Robert Gerbicz
      Date:2009-09-07
      Time limit:1s-6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PYTH 3.2.3 n
      Resource:High School Programming League









      SPOJ Problem Set (classical)

      4828. ZSequence

      Problem code: ZSEQ

      You will be given a sequence A containing N positive integers, a1, a2, ..., aN.
      Let S(i, j) = ai + ai + 1 + ... + aj, if i <= j.
      You should find K - 1 indexes, m1 < m2 < ... < mK - 1 such that lb1 <= S(1, m1) <= ub1, ..., lbi <= S(mi - 1 + 1, mi) <= ubi and lbK <= S(mK - 1 + 1, N) <= ubK.
      If the case of multiple solution, print the first lexicographically.

      Input

      The first line of the standard input contains two space-separated integers N (2 <= N <= 5 000) and K (1 <= K - 1 <= N - 1). Next N lines contain integers a1, a2, ..., aN, respectively, 1 <= ai <= 105.
      i-th of the next K lines contain integers lbi and ubi, 1 <= lbi <= ubi <= 109.

      Output

      On the first line of the standard ouput you should print space-separated K - 1 indices of the solution as already explained. If such solution does not exist, you should print only one integer -1.

       

      Note:

      Memory limit is 16MBs.

      Example

      Input:
      4 3
      1
      2
      3
      4
      1 3
      2 4
      3 10

      Output: 1 2


      Input:
      4 3
      1
      2
      3
      4
      1 3
      2 4
      3 4

      Output:
      2 3


      Input:
      4 3
      1
      2
      3
      4
      1 3
      2 4
      3 3

      Output:

      -1

      Added by:Slobodan
      Date:2009-09-19
      Time limit:0.5s-0.600s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS
      Resource:Z-Trening, own problem









      SPOJ Problem Set (classical)

      4871. Bridge

      Problem code: BRI

      Find a place to build a bridge over the river, so as to minimize total cost of the route between two cities A and B, located on opposite sides of the river.

      Input

      There is a single positive integer T on the first line of input (equal to about 100000). It stands for the number of test cases to follow. Each test case is exactly one line, containing six integers a, b, c, h, s1 and s2 (0 < a, b, c, h, s1, s2 < 100), separated by spaces. a - the distance from city A to the river (the length of segment AE in the figure), b - the distance from city B to the river (the length of segment FG in the figure), c - the distance between A and B along the axis parallel to the river (the length of segment BF in the figure) and h - the width of the river (EG in the figure). s1 and s2 are the costs of unit of road and bridge respectively.

      Output

      For each test case your program should write a single number to the standard output, equal to the minimal total cost of the route between A and B, accurate up to two digits after the decimal dot.

      Example

      Input:

      1
      1 1 1 1 1 1


      Output:

      3.16


      Added by:Ruslan Sennov
      Date:2009-09-27
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6
      Resource:Based on HSPL09BRI









      SPOJ Problem Set ()

      4881. Words on graphs

      Problem code: AMBIG

      Input

      The input is a directed (multi)graph.

      The first line gives the number of edges M and the number of nodes N (>=2). Then each edge is described by a line of the form "FROM TO LABEL". Nodes (FROM, TO) are numbers in the range 0.. N-1 and labels are also numbers.

      All numbers in the input are nonnegative integers <2000.

      Output

      Print "YES" if there are two distinct walks with the same labelling from node 0 to node 1, otherwise print "NO".

      Example 1

      Input:
      4 4
      0 2 0
      0 3 0
      2 1 1
      3 1 2

      Output:

      NO

      Example 2

      Input:
      10 9
      0 2 0
      2 1 0
      2 3 0
      3 4 0
      4 2 0
      2 5 0
      5 6 0
      6 7 0
      7 8 0
      8 2 0

      Output:

      YES

      In this case the shortest labelling that appears on two walks is 0 repeated 10 times.

      drawing of example 2 input


      Added by:Radu Grigore
      Date:2009-09-29
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      4882. Counting in a DAG

      Problem code: DAGCNT2

      You are given a weighted DAG. For each vertex, calculate the sum of the weights of the vertices within its reach (including itself).

      Input

      The first line contains an integer T, denoting the number of test cases.

      For each test case, the first line contains two positive integers n and m, denoting the number of vertices and the number of edges in the DAG.

      The second line contains n positive integers w1..wn, denoting the weights of vertices.

      The next m lines contain two positive integers u,v, denoting an edge from u to v.

      Output

      For each test case, print a line consisting of n numbers, denoting the sum for each vertex.

      Example

      Input:
      2
      4 3
      510 713 383 990
      4 1
      4 2
      2 1
      4 4
      450 379 230 520
      3 4
      2 4
      2 3
      2 4

      Output:
      510 1223 383 2213
      450 1129 750 520

      Constraints

      Input Set 1: numberOfTestCases <= 40, n <= 100, m <= 10000

      Input Set 2: numberOfTestCases <= 2, n <= 1000, m <= 500000

      Input Set 3: numberOfTestCases <= 2, n <= 20000, m <= 500000

      The weights are no more than 1000


      Added by:Lox
      Date:2009-09-30
      Time limit:1s-26s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6
      Resource:Own problem









      SPOJ Problem Set (classical)

      4908. Run-Length Mathematics

      Problem code: RLM

      Run-length encoding of a number replaces a run of digits (that is, a sequence of consecutive equivalent digits) with the number of digits followed by the digit itself. For example, 44455 would become 3425 (three fours, two fives). Note that run-length encoding does not necessarily shorten the length of the data: 11 becomes 21, and 42 becomes 1412. If a number has more than nine consecutive digits of the same type, the encoding is done greedily: each run grabs as many digits as it can, so 111111111111111 is encoded as 9161.

      Implement an integer arithmetic calculator that takes operands and gives results in run-length format. You should support addition, subtraction, multiplication, and division. You won't have to divide by zero or deal with negative numbers.

      Input/Output

      The input will consist of several test cases, one per line. For each test case, compute the run-length mathematics expression and output the original expression and the result, as shown in the examples. The (decimal) representation of all operands and results will fit in signed 64-bit integers.

      Example

      Input:
      11 + 11
      988726 - 978625
      12 * 41
      1124 / 1112
      13 * 33
      15 / 16
      
      Output:
      11 + 11 = 12
      988726 - 978625 = 919111
      12 * 41 = 42
      1124 / 1112 = 1112
      13 * 33 = 39
      15 / 16 = 10
      

      Added by:Miorel-Lucian Palii
      Date:2009-10-04
      Time limit:2s
      Source limit:4096B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6
      Resource:University of Florida Local Contest - April 13, 2009









      SPOJ Problem Set (classical)

      4941. Integer Factorization (20 digits)

      Problem code: FACT1

      This is a problem to test the robustness of your Integer Factorization algorithm.

      Given some integers, you need to factor them into product of prime numbers.

      The largest integer given in the input file has 20 digits. FACT2 is a harder version of this problem (the numbers are larger).

      You may need to use a general factorization algorithm since no special numbers (e.g. Fermat numbers) are considered when designing the input data.

      Input

      There are several numbers given, each one in a line.

      The input ends with a number 0.

      The number of test cases is about 10.

      Output

      For each number, print in a line the factorization of it. See examples below for the output format.

      Example

      Input:
      3111989
      13091989
      2432902008176640000
      77145199750673
      0
      
      Output:
      317^1 9817^1
      17^2 89^1 509^1
      2^18 3^8 5^4 7^2 11^1 13^1 17^1 19^1
      328439^1 234884407^1
      

      Added by:Duc
      Date:2009-10-08
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      4942. Integer Factorization (15 digits)

      Problem code: FACT0


      This is a problem to test the robustness of your Integer Factorization algorithm.

      Given some integers, you need to factor them into product of prime numbers.

      The largest integer given in the input file has 15 digits. FACT1 is a harder version of this problem (the numbers are larger).

      You may need to use a general factorization algorithm since no special numbers (e.g. Fermat numbers) are considered when designing the input data.

      Input

      There are several numbers given, each one in a line.

      The input ends with a number 0.

      The number of test cases is about 10.

      Output

      For each number, print in a line the factorization of it. See examples below for the output format.

      Example

      Input:
      3111989
      13091989
      77145199750673
      0
      
      Output:
      317^1 9817^1
      17^2 89^1 509^1
      328439^1 234884407^1
      

      Added by:Duc
      Date:2009-10-08
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      4948. Integer Factorization (29 digits)

      Problem code: FACT2

      This is a problem to test the robustness of your Integer Factorization algorithm.

      Given some integers, you need to factor them into product of prime numbers.

      The largest integer given in the input file has 29 digits.

      You may need to use a general factorization algorithm since no special numbers (e.g. Fermat numbers) are considered when designing the input data.

      Input

      There are several numbers given, each one in a line.

      The input ends with a number 0.

      The number of test cases is about 10.

      Output

      For each number, print in a line the factorization of it. See examples below for the output format.

      Example

      Input:
      3111989
      13091989
      2432902008176640000
      77145199750673
      0
      
      Output:
      317^1 9817^1
      17^2 89^1 509^1
      2^18 3^8 5^4 7^2 11^1 13^1 17^1 19^1
      328439^1 234884407^1
      

      Added by:Duc
      Date:2009-10-08
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      4951. Bridges! More bridges!

      Problem code: BRII


      Problem BRIDGE has shown that you are able to build the cheap bridge through the river very quickly. Now you will not have problems with time limit. You will have problems with number of bridges.

      Input

      There is a single positive integer T on the first line of input. It stands for the number of test cases to follow. Each test case is exactly five lines, containing description of the route between two cities A and B, located on opposite sides of the rivers.

      n
      a0 a1 a2 ... an
      h1 h2 ... hn
      c
      s0 s1 s2 ... sn

      Here n is the number of the rivers which are parallel to each other, ai - the distances between rivers or between rivers and cities, hi - the widths of the rivers, c - the distance between A and B along the axis parallel to the river, si - the costs of the unit of the bridge through ith river and s0 - the cost of the unit of the road. Example for n=2 you can see on the picture.

      All integers in input are positive and less than 50, except c - it is less than 2000.

      Output

      For each test case your program should write a single number to the standard output, equal to the minimal total cost of the route between A and B, accurate up to two digits after the decimal dot.

      Example

      Input:
      1
      2
      1 1 1
      1 1
      1
      1 1 1
      
      Output:
      5.10
      

      Added by:Ruslan Sennov
      Date:2009-10-08
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6
      Resource:BRIDGE









      SPOJ Problem Set (classical)

      4987. Goal for Raúl

      Problem code: GOALFR

      Goal for Raúl

      What would a Madrid programming contest be without some task about Real Madrid? It's a team with a marvellous history of records. For example, the team's topscorer Raúl González has scored 318 goals so far (in 704 games). In this task you are going to help Raúl shoot his 319th.

      Consider a game between Real Madrid and FC Barcelona. The match is in a critical situation: 10 seconds before the end, the score is 3:3 and Raúl has the opportunity of a direct free kick. The question you have to answer is: Is it possible for Raúl to score a goal by kicking the ball in a straight line?

      To model a soccer game, think of the pitch as a rectangle in a coordinate grid, aligned to the axes. The pitch is centred at (0, 0). It is 105m long and 68m wide, thus x ∈ [-52.5, +52.5] and y ∈ [-34, +34]. The goal is 7.32m long and centred on the short side of the field. The coordinates of the four goal posts are thus (±52.5, ±3.66). Real Madrid is on the left side and has to shoot the ball into the right goal (where x>0).

      To simplify things a bit, we think of the ball and the goal posts as points in space without any volume. Players, on the other hand, have an action radius, i.e. the maximum distance from their position where they can still reach the ball.

      Input

      The input consists of several test cases. The first line of the input file contains one integer N, the number of cases that follow.

      Each test case starts with a blank line. Then follow the x and y coordinates of the ball. The third line contains the x coordinate, y coordinate and action radius of the FC Barcelona Goalkeeper.

      Have a look at the images and the corresponding sample input given:

      Sample input 1Sample input 2
      Sample input 1: Goal! Sample input 2: no Goal
      Goal No Goal

       

      Output

      For each test case, print a line containing one of the following words:

      "Goal!" if it is possible to shoot the ball in a straight line into the goal, without the goalkeeper intercepting it.

      "No goal..." if it is not possible to do so.

      Example

      Input:
      2

      15.0 -20.0
      42.5 2.0 5.0

      20.0 11.0
      34.0 6.0 5.0

      Output:
      Goal!
      No goal...

      Added by:Jonas Wagner
      Date:2009-10-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      4988. Madrids One Way Streets

      Problem code: MOWS

      As you know, PolyProg wants to send EPFL's best coders to Madrid. Now an important question that arises is where they should stay. Apart from being a cheap place, it should also be close to the contest location and the main tourist spots.

      Now the problem is that there are mostly one-way streets in Madrid (actually there aren't, but this problem is so nice that we wanted to include it in this contest nevertheless). We would like to get to the contest and back to the hotel without breaking any traffic rules... can you help finding a hotel that allows to do so?

      To be precice, we'd like to find a hotel that allows us to go to each place of interest and back again. If that's not possible, we'd like a hotel that allows us to travel to and from as many places of interest as possible. If the same number of places can be accessed from several hotels, you should choose the hotel with the smallest id.

      Input

      The first line of the input contains 1 ≤ N ≤ 10, the number of test cases. Then follow three numbers 1 ≤ H ≤ 1000, 1 ≤ P ≤ 100'000 and 1 ≤ S ≤ 1'000'000 denoting the number of hotels, places of interest and streets, respectively.

      In order to simplify things, we just represent hotels and places of interests as numbers: Hotels are numbered from 1 to H, whereas places are numbered from 1001 to 1000 + P.

      Each of the following S lines contains two numbers As and Bs, indicating that there is a one-way street from object As to Bs.

      A blank line precedes each test case.

      The sample input corresponds to the following graph:

      Graph for sample input

      Output

      For each testcase, print the id of the best hotel followed by the number of places of interest accessible from this hotel (and vice versa) on a line.

      Example

      Input:
      1

      2 4 10
      1 1001
      2 1001
      2 1002
      2 1003
      2 1004
      1001 1002
      1002 1
      1002 1003
      1004 2
      1004 1001

      Output:
      1 2

      Added by:Jonas Wagner
      Date:2009-10-14
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      4993. Traveling Salesman

      Problem code: FAKETSP

      According to Wikipedia, "The Traveling Salesman Problem (TSP) is a problem in combinatorial optimization studied in operations research and theoretical computer science. Given a list of cities and their pairwise distances, the task is to find a shortest possible tour that visits each city exactly once. The problem was first formulated as a mathematical problem in 1930 and is one of the most intensively studied problems in optimization. It is used as a benchmark for many optimization methods. Even though the problem is computationally difficult, a large number of heuristics and exact methods are known, so that some instances with tens of thousands of cities can be solved."

      Fortunately, you won't have to solve TSP. You're working for a very clever traveling salesman who has already figured out the path he is going to take. All he needs from you is a quick way to figure out how far he traveled after every segment of his tour.

      Input

      The salesman kept detailed records of his travels. You'll be getting a series of lines of the form "Some text (X, Y)." indicating that the salesman has been at the point X kilometers east and Y kilometers north of the origin of a Cartesian plane.

      Output

      For each segment of the trip, output the total distance traveled up to that point as a line in the format "The salesman has traveled a total of D kilometers." Show three digits after the decimal point when printing D. Note that the salesman only travels in straight lines (even after a couple of drinks).

      Example

      Input:
      I started out at (0, 5).
      Then I traveled to (3.7, 5).
      After a couple of drinks I wobbled to (2.7, 4).
      The next morning I woke up near (4, 3).
      I finished my journey in (-.2, 8).
      
      Output:
      The salesman has traveled a total of 3.700 kilometers.
      The salesman has traveled a total of 5.114 kilometers.
      The salesman has traveled a total of 6.754 kilometers.
      The salesman has traveled a total of 13.284 kilometers.
      

      Added by:Miorel-Lucian Palii
      Date:2009-10-15
      Time limit:2s
      Source limit:4096B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 ERL NODEJS PERL 6
      Resource:University of Florida Team Practice 2009









      SPOJ Problem Set (classical)

      5010. Lost in Madrid

      Problem code: LIM


      Lost in Madrid

      Programming contests can be very exhausting. After five hours of intensive programming, you want to get some well-deserved rest and make yourself on the way to your hotel. Unfortunately, you don't quite remember the way to get there... but that doesn't matter: In good spirits (due to a successful contest?) you set out.

      As you don't know the exact way, you decide to walk around in the following fashion: Start at the contest site (denoted by id 0) and choose a street at random. Follow the street to the next intersection, and choose another street at random. Every street at an intersection has the same probability of being chosen. You might even decide to take the street back where you came from. As you're on foot, you can use the streets in both directions, unlike in "Madrid's One Way Streets".

      Your walk stops once you encounter your hotel (id = 300) or one of the tourist information booths (id > 290) where you can ask for the way. You can assume there is at least one path connecting you to either type of object.

      Because you don't speak a lot of spanish (apart from some verbs that you can conjugate thanks to problem "Spanish Verbs"), you'd like to know the probability that you arrive at your hotel directly, without first arriving at a tourist information booth.

      Input

      The input consists of several testcases, separated by an empty line.

      Each testcase starts with S, the number of streets. The following S lines contain two numbers 0 ≤ A, B ≤ 300 each. This means that there is a street connecting intersection A to intersection B. The same street will not appear multiple times in the input.

      The input ends with S=0. This testcase should not be processed.

      Output

      For each testcase, print the probability to arrive directly at the hotel, rounded to three decimal places.

      Example

      Input:
      3
      0 291
      0 292
      0 300

      2
      0 300
      291 300

      2
      0 291
      291 300

      7
      0 292
      0 88
      0 14
      0 300
      292 88
      88 300
      14 300

      0

      Output:
      0.333
      1.000
      0.000
      0.579

      Added by:Jonas Wagner
      Date:2009-10-16
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      5011. Library for Madrid

      Problem code: LFM


      Library for Madrid

      Good preparation is essential for winning programming contests. Thus, if you read this document, you're on the right track ;) Knowing your algorithms and the programming language you use is of prime importance. However, you don't have to learn everything by heart; each team is allowed to bring 25 pages of documentation to the contest.

      Now the difficult question is: What should you put on those 25 pages? You know that you can fit 10 paragraphs of text on a page, but your stock of useful code snippets and handy texts is much larger than that. To make things more complicated, some topics depend on each other. You cannot include the line-circle intersection formula if you do not also include the code for lines, circles and points.

      As a programmer, you decide to let your computer do the hard work for you. Given a set of topics, their space requirements and dependencies, write a program that prints the maximum number of topics that fit into the library.

      Input

      The input consists of several testcases. Each problem description starts with the numbers 1 ≤ M ≤ 100 and 0 ≤ D ≤ 10, the number of topics and the number of dependencies. The following M lines contain the name of a topic (one word) and the number Lt of paragraphs (1 ≤ Lt ≤ 1000) of the topic, separated by a space.  The next D lines each contain two topic names separated by space, indicating that the first topic depends on the second.

      The input file ends with a testcase having M=0, which should not be processed.

      Output

      For each test case, print a single line containing the maximum number of topics that you can fit in the library, followed by the number of free paragraphs that remain. If several solutions yield the same number of topics, choose the one that leaves as much empty space as possible.

      Example

      Input:
      5 4
      Dijkstra 50
      Intersections 30
      Lines 70
      Circles 120
      Points 40
      Intersections Lines
      Intersections Circles
      Lines Points
      Circles Points

      0 0

      Output:
      3 90

      Notes

      The sample output corresponds to choosing Dijkstra's algorithm, lines and
      points.


      Added by:Jonas Wagner
      Date:2009-10-17
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      5014. Crazy Receptionist

      Problem code: CRAZYR

      After having been wandering around Madrid for several hours, you finally reach the NH Zurbano hotel where all competitors will be located for the SWERC weekend. Each team received an ID number when it registered for SWERC. At your arrival, the receptionist at NH Zurbano asks you for that ID number and assigns you a room according to your team’s registration ID and the one of the delegations that arrived prior to you.

      Crazy Receptionist

      The hotel is as long and as high that it would be possible to accommodate all delegations either on the same floor or on different floors each. The elevator is at the reception side (left) and rooms are located at the first floor and above, on the right-hand side to the elevator. Now the receptionist’s room assignment strategy is the following:

      The receptionist takes you with the elevator to the first floor. Then you walk along the corridor until you arrive at a room that currently hosts a delegation with larger ID than yours. If no such team is on that floor, you get the first empty room you come across. In the opposite case, the team that currently occupies the room has to free it for you! Then the receptionist takes this team to the second floor and uses the same method to find a new room for this team. If the receptionist brings a team to a floor on which currently no other team is hosted, it is assigned the first room at that floor.

      Although this placement strategy seems quite unorthodox, some members of the EPFL delegation got used to interlaced travel and rest, especially at airports and railway stations. Instead of being shocked by the fact of having to potentially change the room as further delegations arrive, your coach is even more impressed by that placement strategy and challenges you with the following question:

      Given the current assignment of the rooms, can you list all possible orders of arrival of the teams?

      Input

      The first line contains the number of test cases C (C≤25). Each test case starts with the number of occupied floors F. The following F lines contain information about floors F, …, 1, starting from the top. First on each of these lines is an integer N, the number of teams at that floor. Following that, there are N integers on the line: the ID of the teams on that floor, starting from the elevator side (left). All IDs satisfy (1≤ID≤60). There are never more than T (T≤15) teams in the hotel at the moment your coach challenges you. A blank line precedes each test case.

       

      Output

      For each test case, output first the number of the test case, then the number P of possible arrival orders. See the sample output for the exact format.

      On the following min(10, P) lines, print the lexicographically smallest possible arrival orders.

      Example

      Input:
      2

      3
      1 3
      2 2 9
      3 1 4 5

      2
      1 3
      2 1 2

      Output:
      Case 1 : 16
      3 2 1 4 9 5
      3 2 1 9 4 5
      3 2 4 1 9 5
      3 2 4 9 1 5
      3 2 4 9 5 1
      3 2 9 1 4 5
      3 2 9 4 1 5
      3 2 9 4 5 1
      3 4 2 1 9 5
      3 4 2 9 1 5

      Case 2 : 2
      1 3 2
      3 1 2


      Given the current assignment of the rooms, can you list all possible orders of arrival of the teams?


      Added by:Christian Kauth
      Date:2009-10-17
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      5015. Decode the Castanets

      Problem code: CASTANET

      The contest just finished and you head out to show all the balloons you won to your coach who’s amazed! Contest organizers know that coders can get really excited during the five hours of contest, so they planned to take you to a flamenco performance in order to relax you a bit before the awards ceremony starts. Flamenco is indeed a traditional Spanish musical genre. The music itself is complex, and the footwork is lightning fast and must be executed with extraordinary precision. In addition the dancer may have to dance while using props such as castanets, shawls and fans.

      castanets

      The performer of this afternoon will be none other than Don Quijote de la Mancha! Unfortunately Don Quijote cannot find the scope for the castanets, nor does he remember it by heart. But he has always an encoded version of that scope with him, so that he can have a quick look at it just before the performance. As time is short, he needs your help to decode the encrypted version of the scope.

      The scope can be represented as a binary string b1..bN of N digits. ‘1’ stands for clap the castanet, ‘0’ means leave it quiet. Now the encryption was as follows:

      matrix

      Given the original scope, the below matrix is formed from the rotated versions of the string.

      Then the rows of the matrix are sorted in alphabetical order (‘0’ < ‘1’). The last column of this matrix, read from top to bottom, is the encrypted version of the scope Don Quijote is giving you. Your task would be to find the Fth line of the matrix, which is the original version of the castanet scope.

      Input

      The input consists of no more than T (T≤100) test cases. Each test case starts with two integers, which denote the number of bits N and the desired line F respectively (1≤F≤N≤1’000). The next line contains N binary digits, the encrypted scope.

      Output

      For each test case, output the scope for the castanets.

      Example

      Input:
      2
      2 2
      10
      5 1
      11100

      Output:
      10
      01011

      Note

      The ordered matrices for the sample test cases would be respectively

      01  01011
      10  01101
          10101
          10110
          11010

      Added by:Christian Kauth
      Date:2009-10-17
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      5016. Guernica

      Problem code: GUERNICA

      Guernica is a famous painting by Pablo Picasso, depicting the bombing of the Basque town of Guernica during the Spanish Civil War. It shows the tragedies war inflicts upon individuals, particularly innocent civilians. The work has gained a monumental status, becoming a perpetual reminder of the tragedies of war, an anti-war symbol and an embodiment of peace.



      After you were told that the painting was moved from the Museo del Prado to the Museo Nacional Centro de Arte Reina Sofia in 1992, you are on your way to that place. At your arrival, a creepy sight awaits you: Malicious vandals have cut the Guernica painting into several pieces and distributed them throughout the whole museum. A team already gathered all N pieces they could find. All these pieces have the same dimensions! Observing the dimensions, they conclude that there are far too many pieces to rebuild only Guernica. The vandals did in fact not only disassemble the original painting by Picasso but also several copies of it! Exactly P pieces are needed to reconstruct Guernica (or any of its copies).

      Now experts have to evaluate how probable it is that sets of P pieces belonged to one and the same initial painting and assigned each such combination a matching score. By maximizing the total matching score, they would be able to determine which pieces belonged to the same initial painting. Can you help them calculating the overall maximum matching score for all of the paintings?

      Guernica

      Input

      The input consists of several test cases (T≤10), each of which starts by 3 integers on a line: the number of pieces found N, the number of pieces per painting P and Z, the number of possible combinations. (P, N≤15, Z≤1’000) The next Z lines each contains P+1 positive integers (i1, i2, …, iP, s), that means a score of s is given to the combination (i1, i2, …, iP). (i1,..,iP ≤N, 0<s<10’000) The last test case is followed by a single line with 3 zeros, which should not be processed.

      Output

      For each test case, print the case number and the largest score. If it is impossible to group all pieces so that entire paintings result out of them, print -1.

      Example

      Input:
      9 3 3
      1 2 3 1
      4 5 6 2
      7 8 9 3
      9 3 4
      1 2 3 1
      1 4 5 2
      1 6 7 3
      1 8 9 4
      3 3 1
      1 2 3 9
      5 4 1
      2 1 5 3 10
      0 0 0

      Output:
      Case 1: 6
      Case 2: -1
      Case 3: 9
      Case 4: -1

      Added by:Christian Kauth
      Date:2009-10-17
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      5018. Street Gambler

      Problem code: STRGAMB


      Madrid is a tremendously historic and monumental city that attracts several millions of visitors each year. Where there are tourists, there are also artists that entertain the crowds in the streets and gamblers that challenge pedestrians to often snaky games. One of them is just about to ask you for a game. Although you learned in problem X some basics of Spanish conjugation, you are not proficient enough to understand the rules of the game. This is why you decide to observe first some games, from which you succeede to extract the rules correctly:

      1 2 3 4 5 6 7 8
          O   O O O O

      It is a two player game and players take alternate turns on a board with squares numbered from 1 to N. Some of the squares contain one Spanish 1 cent coin, others don’t. At each turn, the player has to select one square containing a coin and removes the coin from the square, leaving that square empty. At the same time this player may, if he wishes so, select a second square to the left from the first one. In the left square, the player is allowed either to put 1 coin if this square is empty or to empty that box in case it contained a coin. The game finishes when there is no coin left on the board and the player to make the last move wins.

      Here are the turns you observed for the initial game constellation of the above figure:

      XXOXOOOO                Tourist empties 7 and puts a coin in 4
      XXOOOOXO                Gambler empties 8 as well as 4
      XXOXOOXX                Tourist empties 6 and puts a coin in 1
      OXOXOXXX                Gambler empties 5 and puts a coin in 2
      OOOXXXXX                Tourist empties 1
      XOOXXXXX                Gambler empties 3 as well as 2
      XXXXXXXX                Tourist lost the game, as no coin is left

      You are a bit surprised that the gambler wins most of the games. He must indeed have several years of experience and know some tricks. As you are smart, you discover his trick. Supposing that both of you play optimally, that is, once you are in a winning constellation,

      you’ll find the correct moves to win the game, can you tell for a given constellation whether you should make the first move or leave it to the gambler? Of course you want to win!

      Input

      The input consists of several test cases (T300), one per line that describes the initial board constellation as a string of ‘O’s and ‘X’s. Read from left to right, this string describes the board constellation from position 1 to position N (N255). ‘O’ stands for a square with coin, ‘X’ for an empty square. The input terminates on the string “end” that should obviously not be processed.

      Output

      Output “I’d like to play first” or “After you”, so that you will win the game.

      Example

      Input:
      XXOOOX
      OOOXX
      XOOOOOOOO
      XXXXOXXXXXXXOXOXXXXXXOXXXXXXXXX
      end

      Output:
      I'd like to play first
      After you
      After you
      I'd like to play first

      Added by:Christian Kauth
      Date:2009-10-17
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL NODEJS PERL 6









      SPOJ Problem Set (classical)

      5084. Discrete Math Problem

      Problem code: GCD3

      Given N, M and K (1 <= N, M <= 100^200 and 1 <= K <= 16) which

      N = a + b
      M = a^2 + b^2 - (2^K - 2) * a * b

      with a > 0, b > 0 and gcd(a, b) = 1.

      Your task is to find gcd(N, M).

      Input

      The input file consists of several data sets. The first line contains
      the number of data sets T (1 <= T <= 10000). The fallowing T lines
      describe the data sets, one triple (N, M, K) for each.

      Output

      For each data test in the input write the gcd(N, M).

      Example

      Input:

      2
      648570884104668119354133 420644191708310845403065233058235585438328857465 5
      8017723549 59173349743176010825 9
      Output:

      1
      1


      Note: For the first trio a = 648570884104668119354126 and b = 7.
      For the second a = 8016478423 and b = 1245126.

      Added by:Frank Rafael Arteaga
      Date:2009-10-24
      Time limit:0.100s-0.300s
      Source limit:1000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ LISP sbcl LISP clisp F# GO HASK JAVA NODEJS PERL 6 PHP PIKE PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n RUBY SED
      Resource:Discrete Math









      SPOJ Problem Set (classical)

      5091. Feline Olympics - Mouseball

      Problem code: MBALL

      A popular event at the feline Olympics is watching and wagering on the outcome of the house cats playing Mouseball [which has the same scoring rules as American football] but is played with a catnip mouse. Wagers often involved predicting the score and, of course, some scores are more likely to occur than others. Multiples of 7 are good bets, because teams typically go for touchdowns (6 points) then attempt to kick the football between the uprights for an extra point. A score of 4 is unlikely because safeties (2 points each) are rare.

      A score of exactly 1 is nearly (though not) impossible to achieve: suppose Team A has just scored a touchdown; during the extra point attempt, Team A fumbles the ball; it is recovered by a player from Team B, who returns it almost the entire length of the field, but fumbles right before reaching the endzone; the ball is recovered by a player from Team A, who voluntarily enters his own endzone, where he is tackled by Team B; this counts as a safety, but because it was scored during an extra point attempt, Team B will only be awarded 1 point.

      Not surprisingly, such a scenario is not known to have ever occurred in the history of the game. So for simplicity, we will ignore this possibility altogether and consider only the following ways of scoring points:

      • a safety: 2 points, always
      • a field goal: 3 points
      • a touchdown: 6 points

      Additionally, after scoring a touchdown, a team attempts a "try." This may be either an extra point or a two-point conversion and will give, if successful, 1 or 2 points, respectively.

      Write a program that, given a score, outputs the number of ways that score can be achieved. As an example, a team could score 10 points in exactly 5 ways:

      • 5 safeties
      • 2 field goals and 2 safeties
      • a touchdown, extra point good, and a field goal
      • a touchdown, a two-point conversion, and a safety
      • a touchdown with a failed try and 2 safeties

      Note that order is not important: a touchdown followed by a field goal is considered equivalent to a field goal followed by a touchdown.

      Input

      The first line of input will contain an integer N <= 100, indicating the number of test cases. Each of the next N lines will contain an integer S, the number of points scored by a team in a game. S will be between 0 and 100000 inclusive. (Hey, the orange & blue [Flame-point Siamese] team could make it happen.)

      Output

      For each test case, output one line containing a single integer: the number of ways a team can score exactly S points.

      Example

      Input:
      2
      10
      6
      
      Output:
      5
      3
      

      Added by:Miorel-Lucian Palii
      Date:2009-10-26
      Time limit:1s
      Source limit:4096B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 NODEJS PERL 6
      Resource:University of Florida Local Contest - September 27, 2009









      SPOJ Problem Set (classical)

      5093. Pretty Functions

      Problem code: PRETTY


      Let S = {1, 2, 3, ..., N}.
      For a given positive integer K, the function f : S --> S is called "pretty" if, for every X in S, it holds that
      f ( f ( f ( ... f ( X ) ... ) ) ) = X, where f is repeated exactly K times.

      How many pretty functions are there, modulo M?

      Input

      Three natural numbers N, K and M. It holds that 1 <= K <= N <= 30 000 and M <= 10^9.

      Output

      Number of pretty functions modulo M.

      Example

      Input:
      2 1
      1000

      Output:
      1
      Input:
      3 2
      1000

      Output:
      4

      Explanation of the example input 2: there are four pretty functions, namely:
      a) f(1) = 1, f(2) = 2, f(3) = 3;
      b) f(1) = 2, f(2) = 1, f(3) = 3;
      c) f(1) = 3, f(2) = 2, f(3) = 1;
      d) f(1) = 1, f(2) = 3, f(3) = 2.

       


      Added by:Ivan Kataniæ
      Date:2009-10-26
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: NODEJS PERL 6
      Resource:author: Adrian Satja Kurdija









      SPOJ Problem Set (classical)

      5102. Mystic Craft

      Problem code: MYSTIC

      In the Ancient Clash of Mystic Pandas (ACM Pandas) game, the player plays the role of a Panda Knight who needs to defend Panda Land by defeating evil Panda Wizards. As the wizards have special magical powers, they need to be defeated using specific types of Mystic Sticks (regular bamboo sticks are ineffective against them). To obtain a Mystic Stick, Panda Knight needs to craft it by infusing his regular bamboo stick with several different kinds of magic shards according to the known recipe for that particular type of Mystic Stick.

      Normally, all kinds of shards can be purchased for 1 gold/piece from the Panda Magic Store (therefore Panda Knight will have no problem of acquiring the shards, as long as he has enough gold to buy them all from the Store). However due to the recent invasion, to conceal the shards from the incoming Panda Wizards, Panda Magic Store has packaged all the shards into inconspicuous Mystery Boxes. A Mystery Box contains a random piece of magic shard which type can’t be determined prior to buying and opening the box, which Panda Knight can also buy for the same price (1 gold/box).

      As his Panda Knight character is not rich, Mr. Wah is concerned about the possibility that he’s unable to buy all the necessary shards due to not getting the required amount of a specific type of shard. He needs your help! Your task as Mr. Wah’s best programmer friend is to compute the probability that he will be able to get all the shards and craft the Mystic Stick, so that he can plan his playing strategy accordingly. You can safely assume that all the required shards are available on the store via the Mystery Boxes, that the boxes will only contain the needed types of shard, and that each type of shard has equal probability of being contained inside any particular Mystery Box.

      Input

      The first line of input contains an integer T (1 ≤ T ≤ 100), the number of test cases follow. Each test case begins with two integers G and N (1 ≤ N ≤ G ≤ 32) in one line, denoting the amount of Panda Knight’s gold and the number of needed magic shard types respectively. The next line contains N integers, denoting how many magic shards of each type (1 ≤ M1 … MN ≤ 32, M1 + … + MN ≤ G) are needed to craft the Mystic Stick.

      Output

      For each of the test cases, print the test case number followed by the probability (in percentage, correct to 6 decimal places – Mr. Wah is paranoid about this game) that Panda Knight will be able to craft the Mystic Stick, with the format as shown by the sample output.

      Sample Input
      5 
      3 2 
      1 1 
      8 3 
      3 2 2 
      10 3 
      1 2 3 
      7 7 
      1 1 1 1 1 1 1 
      32 8 
      1 1 1 1 1 1 1 1 	
      
      Output for Sample Input
      Case #1: 75.000000 
      Case #2: 23.472032 
      Case #3: 58.934106 
      Case #4: 0.611990 
      Case #5: 89.127753 	 
      

      Explanation for 1st sample test case: There are 23 = 8 possible combinations of shard types that Knight Panda can get by purchasing 3 Mystery Boxes with his available gold:

      1. Type 1, Type 1, Type 1 
      2. Type 1, Type 1, Type 2
      3. Type 1, Type 2, Type 1
      4. Type 1, Type 2, Type 2
      5. Type 2, Type 1, Type 1
      6. Type 2, Type 1, Type 2
      7. Type 2, Type 2, Type 1
      8. Type 2, Type 2, Type 2

      Since there are 6 out of 8 combinations that gives required amount of shards (at least one Type 1 shard and one Type 2 shard), the probability that Panda Knight will be able to craft the Mystic Stick is 6/8 = 75%.


      Added by:VOJ problem setters
      Date:2009-10-28
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 NODEJS PERL 6
      Resource:ACM ICPC - Jakarta 2009









      SPOJ Problem Set (classical)

      5103. Top 10

      Problem code: TOP10


      Given a dictionary containing less than N = 20000 words labeled from 1 to N. Each word consists of lowercase characters (from 'a' to 'z') with arbitrary length. The total number of characters in the dictionary is at most 100,000. Your task is to answer at most Q = 100000 queries. Each query qi is also a word (as defined above). For each query, you have to print the "Top 10" words in the dictionary with the following rules:

      All the words in the "Top 10" have to contain the substring qi.

      All the words in the "Top 10" have to be sorted in this order:

      1. The words with shorter length come first, if they have equal length then

      2. The lexicographically smaller words come first, otherwise

      3. The words with smaller label come first.

      If the number of words in the dictionary that contains the substring qi is less than 10 then print all the words otherwise, print only the top-10 words (note: the words are printed using their labels).

      If there is no word in the dictionary that contains the substring qi then print "-1" (without the quotes).

      Input
      The first line contains the number N. The next N lines contains the N words in the dictionary (the ith line is the word with label i). The next line contains the number Q followed by the Q lines containing the queries.

      Output
      For each query, print one line containing the labels of the "Top 10" words (separated by a space) in the dictionary using the rules defined above.

      Sample Input
      17
      acm
      icpc
      regional
      asia
      jakarta
      two
      thousand
      and
      nine
      arranged
      by
      universitas
      bina
      nusantara
      especially
      for
      you
      5
      a
      an
      win
      b
      z

      Output for Sample Input

      1 8 4 13 5 10 3 7 14 15
      8 10 7 14
      -1
      11 13
      -1


      Added by:VOJ problem setters
      Date:2009-10-28
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 NODEJS PERL 6
      Resource:Problem Setter: Felix Halim
      ACM ICPC - Jakarta 2009









      SPOJ Problem Set (classical)

      5104. Spam Detection

      Problem code: SPAMD


      It is well-known that the number of occurrences of the term "free" can distinguish spam and non-spam emails.
      Your task is to build a spam detection module, based on the number of term "free" in an email.
      The core of this detection module is a spam classifier, which is represented by two variables: Low and High.
      An email that contains X "free" words is classified by this module as a spam if Low ≤ X ≤ High, otherwise it is not.
      To measure the goodness of a classifier, we introduce several information-retrieval terminologies:

      Actual
      Spam Non-Spam
      Predicted Spam TP FP
      Non-Spam FN TN

      TP (true positive) is the number of emails which are truly predicted as spam; FN (false negative) is the number of emails which are wrongly predicted as non-spam, and so on.
      The portion of emails that are correctly identified as spam is denoted as precision (P), which is formulated as P = TP / (TP + FP).
      The portion of spam emails that are successfully identified is denoted as recall (R), which is formulated as R = TP / (TP + FN).
      To balance between precision and recall, we use the F-measure which is formulated as F = 2 x P x R / (P + R).
      For example, when TP = 5, FP = 3, FN = 2, TN = 4, we have R = 5/7, P = 5/8, and F = 2/3.
      When there is no spam, we can report all emails as non-spam with F = 1.0 (perfect classifier).
      Our data mining team has manually analyzed several emails and labeled them as spam or non-spam.
      Your task is to find the values of Low and High that yield the best classifier, i.e., the one that maximizes the F-measure.

      Input

      The input consists of several test cases, where each case contains of two lines:

      N : The maximum number of term “free” in any emails (1 ≤ N ≤ 2 x106)
      a0 A B M : parameters of random number generator. (2 ≤ M ≤ 10; 0 ≤ a0, A, B < M)

      This random number generator generates a sequence of number:
      ai = (A * ai-1 + B) MOD M for i >= 1

      Specifying:
      posi = a2i (0 ≤ i ≤ N) : the number of spam emails with i number of term “free”.

      negi = a2i+1 (0 ≤ i ≤ N) : the number of non-spam emails with i number of term “free”. The input is terminated by EOF.

      Output

      For each simulation print the F-measure of the best classifier (accurate to 6 decimal places).

      Sample Input
      3
      1 1 1 3
      5
      2 3 4 5

      Output for Sample Input

      0.666667
      0.923077

      Explanation for the 1st case: This random number generator generates a sequence of 1, 2, 0, 1, 2, … The number of spam emails is: posi = {1, 0, 2, 1}, and the number of non-spam emails is negi = {2, 1, 0, 2}.

      The optimal classifier treats emails with number of term “free” between 2 and 3 as spam, with R = 3/4 and P = 3/5, resulting F = 2/3. Another way of producing optimal classifier is to consider emails with number of term “free” equals to 2 as spam.


      Added by:VOJ problem setters
      Date:2009-10-28
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 NODEJS PERL 6
      Resource:Problem Setter: ardiankp
      ACM ICPC - Jakarta 2009









      SPOJ Problem Set (classical)

      5107. Playing with Marbles

      Problem code: TUTMRBL

      Playing with marbles is one of the king's favorite pastimes. He especially enjoys a game which was taught to him by Eratosthenes, a visiting mathematician from Greece. The rules are very complicated but it all boils down to arranging marbles in a (filled) rectangular shape to score points. If playing with 24 marbles, for example, King Tut could make a 4 by 6 rectangle, or a 3 by 8 rectangle, or a 2 by 12 rectangle. Even the boring 1 by 24 rectangle is allowed. Other numbers of marbles, however, such as 23, make things difficult for the king. Try as he might, the only rectangle he can make is 1 by 23. (Note that rectangles are equivalent under rotation, so a 23 by 1 rectangle would not be a new shape.)

      King Tut has decided to call numbers n which can form only the unexciting 1 by n rectangle "non-rectangular." Conversely, numbers like 24, which allow for the formation of more than one rectangle, shall henceforth be referred to as "rectangular." Playing with a single marble is not very interesting at all, so the number 1 will by definition considered neither rectangular nor non-rectangular.

      After playing for some time, the king started to notice that every integer greater than 1 could be written as a product of non-rectangular numbers. Were he a mathematician, he would try to prove this claim (which, incidentally, is true). However, the king is more of the engineer type, so he's going to make you verify the claim using brute force! While you're at it, also tell the king how many rectangles can be constructed given a certain number of marbles.

      Input

      There will be several test cases, one per line, each consisting of a single integer between 2 and 107 inclusive. An input of zero will be used to tell your program to stop processing.

      Output

      For each test case, print out two lines! The first should show the given number of marbles written as a product of non-rectangular numbers, following the example of the sample output. Factors must be written in non-decreasing order and separated by multiplication signs. Also print out spaces around the equals and multiplication signs to improve readability. The second line of output for each test case should be in the format: "With X marbles, Y different rectangles can be constructed." Again, don't forget to replace X and Y with the proper values.

      Example

      Input:
      24
      23
      0
      
      Output:
      24 = 2 * 2 * 2 * 3
      With 24 marbles, 4 different rectangles can be constructed.
      23 = 23
      With 23 marbles, 1 different rectangles can be constructed.
      

      Added by:Miorel-Lucian Palii
      Date:2009-10-28
      Time limit:5s
      Source limit:4096B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.3.2 NODEJS PERL 6
      Resource:University of Florida Local Contest - September 9, 2007









      SPOJ Problem Set (classical)

      5115. Two "Ways"

      Problem code: SPHIWAY


      There are N places and M bidirectional way. No two places have more than one direct way. Ana wants to walk from S to T and return to S by a itinerary that satisfy:

      -          No way can be go twice.

      -          Length of itinerary is the minimum.

      Input

      Line 1: 4 integers: N, M, S, T (N <= 104; M <= 105)

      Next M line: Line i include 3 integers ui, vi, ci: distance of two places ui and vi is ci. (ci <= 2000000000).

      Output

      Length of the itinerary if it exists. Else print -1.

      Example

      Input:
      5 7 1 5
      1 2 3
      1 4 8
      2 3 5
      2 4 4
      3 5 5
      4 3 8
      4 5 3

      Output:
      24

      Added by:HNUE
      Date:2009-10-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Mr. Le Minh Hoang - HNUE









      SPOJ Problem Set (classical)

      5117. Wine trading in Gergovia

      Problem code: GERGOVIA


      Gergovia consists of one street, and every inhabitant of the city is a wine salesman. Everyone buys wine from other inhabitants of the city. Every day each inhabitant decides how much wine he wants to buy or sell. Interestingly, demand and supply is always the same, so that each inhabitant gets what he wants.

      There is one problem, however: Transporting wine from one house to another results in work. Since all wines are equally good, the inhabitants of Gergovia don't care which persons they are doing trade with, they are only interested in selling or buying a specific amount of wine.

      In this problem you are asked to reconstruct the trading during one day in Gergovia. For simplicity we will assume that the houses are built along a straight line with equal distance between adjacent houses. Transporting one bottle of wine from one house to an adjacent house results in one unit of work.

      Input

      The input consists of several test cases.

      Each test case starts with the number of inhabitants N (2 ≤ N ≤ 100000).

      The following line contains n integers ai (-1000 ≤ ai ≤ 1000).

      If ai ≥ 0, it means that the inhabitant living in the ith house wants to buy ai bottles of wine. If ai < 0, he wants to sell -ai bottles of wine.

      You may assume that the numbers ai sum up to 0.

      The last test case is followed by a line containing 0.

      Output

      For each test case print the minimum amount of work units needed so that every inhabitant has his demand fulfilled.

      Example

      Input
      5
      5 -4 1 -3 1
      6
      -1000 -1000 -1000 1000 1000 1000
      0

      Output:
      9
      9000

      Added by:HNUE
      Date:2009-10-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:UVA









      SPOJ Problem Set (classical)

      5120. Minimal Possible String

      Problem code: MINSEQ


      Given two strings A and B, your are to find the lexicographically smallest string after inserting B into A.

      For example, string A is "369", and string B is "4799". There are 4 ways that I can insert B into A, and I’ll get 4 different results: 4799369, 3479969, 3647999, 3694799. Thus, 3479969 is the lexicographically smallest one.

      Input

      Input contains several cases. Each case has 2 strings A and B with length no longer than 100000 in 2 lines. Process the input until EOF. The strings consist of only digit 1-9.

      Output

      For each case, output the minimal possible result.

      Example

      Input:
      369
      4799
      666
      12345

      Output:
      3479969
      12345666

      Added by:3xian
      Date:2009-10-30
      Time limit:1s-12s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:GDUT Monthly









      SPOJ Problem Set (classical)

      5128. Bomb the Bridge

      Problem code: BOMB

      You want to destroy a bridge with bombs. The lower-left corner of the bridge is at (0,0) and the upper-right corner is at (w,l). There are already b bombs exploded, the i-th bomb created a hole of radius ri centering at (xi,yi). You want to throw exactly one more bomb so that the bridge is split into two connected parts(though the two parts can share a finite number of points), so that no one can go through the bridge from y = 0 to y = l. Your task is to find the minimal radius of the last bomb to split the bridge, assuming that the last bomb can explode precisely at the position you want (possibly at non-integer coordinates). Note that you are only allowed to use bombs with integer radius. That is, even if a bomb with radius 1.01 is sufficient, you have to use a bomb with radius 2, since you only have bombs with integer radius.

      Input

      The first line contains t (1≤t≤10), the number of test cases followed. Each test case begins with three integers w,l,b(1≤w,1≤100, 0≤b≤10). Each of the following b lines contains three integers integers xi,yi,ri(0≤x≤w, 0≤y≤l, 0<r≤100). The bridge is guaranteed to be connected before the last bomb.

      Output

      For each test case, print the minimal radius of the last bomb.

      Example

      Input:
      

      3
      100 100 2
      15 50 20
      90 50 30
      100 100 1
      50 50 40
      100 100 1
      10 50 10

       

      Output: 13
      50
      40

      Added by:3xian
      Date:2009-10-31
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Zhuhai Contest 2008









      SPOJ Problem Set (classical)

      5142. A Pair of Graphs

      Problem code: PAIRGRPH

      Please click here to download a PDF version of the contest problems. The problem is problem A in the PDF. Remember that you must use stdin/stdout at SPOJ.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      5143. Binary Integer

      Problem code: BNYINT


      Please click here to download a PDF version of the contest problems. The problem is problem B in the PDF. Remember that you must use stdin/stdout at SPOJ.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      5144. Cryptography Reloaded (Act I)

      Problem code: CRYPTO6


      Please click here to download a PDF version of the contest problems. The problem is problem C in the PDF. Remember that you must use stdin/stdout at SPOJ.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      5145. Déjà vu

      Problem code: DEJAVU


      Please click here to download a PDF version of the contest problems. The problem is problem D in the PDF. Remember that you must use stdin/stdout at SPOJ.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:35s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      5146. Experiment on a … Cable

      Problem code: CABLEXPR

      Please click here to download a PDF version of the contest problems. The problem is problem E in the PDF. Remember that you must use stdin/stdout at SPOJ.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      5147. Fire-Control System

      Problem code: FCSYS

      Please click here to download a PDF version of the contest problems. The problem is problem F in the PDF. Remember that you must use stdin/stdout at SPOJ.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:13s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      5148. Get-Together at Stockholm

      Problem code: STCKHOLM

      Please click here to download a PDF version of the contest problems. The problem is problem G in the PDF. Remember that you must use stdin/stdout at SPOJ.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      5149. History of Languages

      Problem code: HISTORY


      Please click here to download a PDF version of the contest problems. The problem is problem H in the PDF. Remember that you must use stdin/stdout at SPOJ.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:17s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      5150. Junk-Mail Filter

      Problem code: JMFILTER

      Please click here to download a PDF version of the contest problems. The problem is problem J in the PDF. Remember that you must use stdin/stdout at SPOJ.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Hangzhou 2008









      SPOJ Problem Set (classical)

      5151. Alice’s Cube

      Problem code: ALICECUB

      Please click here to download a PDF version of the contest problems. The problem is problem A in the PDF.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5152. Brute-force Algorithm EXTREME

      Problem code: BFALG


      Please click here to download a PDF version of the contest problems. The problem is problem B in the PDF. But the data limits is slightly modified: 1≤P≤1000000 in the original description, but in this EXTREME version, 1≤P≤1000000000.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5153. Compressed String

      Problem code: COMPRESS


      Please click here to download a PDF version of the contest problems. The problem is problem C in the PDF.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5154. Cryptography Reloaded (Act II)

      Problem code: CRYPTO7

      Please click here to download a PDF version of the contest problems. The problem is problem D in the PDF.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:21s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5155. Exciting Time

      Problem code: TETRIS2D


      Please click here to download a PDF version of the contest problems. The problem is problem E in the PDF.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5156. Flowers Placement

      Problem code: FLOWERS2

      Please click here to download a PDF version of the contest problems. The problem is problem F in the PDF.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:13s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5157. Game Simulator

      Problem code: TRACTOR

      Please click here to download a PDF version of the contest problems. The problem is problem G in the PDF.

      Since this problem is added as an classical problem in SPOJ, the users who get this problem Accepted (by himself/herself, I'll look at your code) before 2011.10.25 8:00:00 SPOJ time (two years right after the on-site contest's end) will be e-mailed some pictures of the problem setters of this contest - g201513, lcosvse and Blue Mary. [the offer is invalid, it has been presented to Wassim Khalil (Australia).]

      Log:

      (1)Thanks to Thomas Schnattinger, who points out a small bug in the sample input. The corrected sample should be:

      Input:
      1
      
      O Charles 2 2
      S6S6S7S7 SASKSJST STS8S4S4 S3S5SJSQ
      S9S9 H3D3 C3DT SAD3
      DA DQ DK D4
      SKS8S5S3 RJC2D2H2 C6C8CJD9 H3CKDTD5
      H7H7 H6H4 HJHQ H9H9
      DJDJ DKH5 D5D4 D6D6
      D8D8 C4C3 HTH5 D9D7
      C5C5 C6CT H8HQ C7C4
      H8 C7 HA HA
      H2 RJ BJ CK
      DA BJ C8 HK
      S2S2C2 CQCAD2 HTHJHK C9CQCA
      
      Output:
      Case #1:
      50
      3 2 Alice
      

      (2) The bug about '\r\n' has been fixed.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:1s
      Source limit:15000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5158. Heroes Arrangement

      Problem code: HEROARR


      Please click here to download a PDF version of the contest problems. The problem is problem H in the PDF.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:35s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5159. Island Explorer

      Problem code: IEXPOLRE


      Please click here to download a PDF version of the contest problems. The problem is problem I in the PDF.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:17s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5160. Jinyuetuan Puzzle

      Problem code: O2JAM

      Please click here to download a PDF version of the contest problems. The problem is problem J in the PDF.


      Added by:[Trichromatic] XilinX
      Date:2009-11-01
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C99 strict NODEJS PERL 6
      Resource:Blue Mary's gifts of her retirement - ACM/ICPC Regional Contest, Shanghai 2009









      SPOJ Problem Set (classical)

      5161. Factorial vs Power

      Problem code: FACVSPOW

      Consider two integer sequences f(n) = n! and g(n) = an, where n is a positive integer. For any integer a > 1 the second sequence is greater than the first for a finite number of values. But starting from some integer k, f(n) is greater than g(n) for all n >= k. You are to find the least positive value of n for which f(n) > g(n), for a given positive integer a > 1.

      Input

      The first line of the input contains number t – the amount of tests. Then t test descriptions follow. Each test consist of a single number a.

      Constraints

      1 <= t <= 100000
      2 <= a <= 106

      Output

      For each test print the least positive value of n for which f(n) > g(n).

      Example

      Input:
      3
      2
      3
      4
      
      Output:
      4
      7
      9
      

      Added by:Spooky
      Date:2009-11-01
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Autumn 2009, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      5163. Tower of Vientiane

      Problem code: VIENTIAN


      The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks neatly stacked in order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

      • Only one disk may be moved at a time.
      • Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
      • No disk may be placed on top of a smaller disk.

      It is known that the puzzle can be solved in 2n-1 steps for n disks.

      Now consider the puzzle called The Tower of Vientiane. The rules are almost the same as for The Tower of Hanoi. But additionally there are limitations on the allowed moves. Let the initial rod be numbered 1, the target rod - 3, and the auxiliary rod - 2. The matrix of allowed moves is given. For example is can be allowed to move disks from rod 1 to rod 2 only, from rod 2 to rod 3 and from rod 3 to rod 1. You are to find out the minimal number of moves in which the puzzle can be solved given some limitations on the allowed moves.

      Input

      The first line of the input contains number t – the amount of tests. Then t test descriptions follow. The test starts with a 3x3 matrix, consisting of 1s and 0s. The 1 in i-th row and j-th column of the matrix means that the move from rod i to rod j is allowed, otherwise it is not allowed. The next line of each test contains the number n - the amount of disks for the corresponding testcase.

      Constraints

      1 <= t <= 10000
      2 <= n <= 39

      Output

      For each test print the minimal number of moves in which the puzzle can be solved or "Epic Fail..." if it's impossible to solve the puzzle under such limitations.

      Example

      Input:
      3
      011
      101
      110
      5
      010
      101
      010
      5
      010
      001
      010
      5
      
      
      Output:
      31
      242
      Epic Fail...
      
      

      Added by:Spooky
      Date:2009-11-02
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2009, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      5182. Double Sorting

      Problem code: PAIRSORT

      Here we describe a typical problem. There are n balls and n boxes. Each ball is labeled by a unique number from 1 to n. Initially each box contains one of these balls. We can swap two balls in adjacent boxes. We are to sort these balls in increasing order by swaps, i.e. move the ball labeled by 1 to the first box, labeled by 2 to the second box, and so forth. The question is how many swaps are needed.

      Now let us consider the situation where the balls are doubled, that is, there are 2n balls and n boxes, exactly two balls are labeled by k for each 1 ≤ kn, and the boxes contain two balls each. We can swap two balls in adjacent boxes, one ball from each box. We are to move the both balls labeled by 1 to the first box, labeled by 2 to the second box, and so forth. The question is again how many swaps are needed.

      Here is one interesting fact. We need 10 swaps to sort [5; 4; 3; 2; 1] (the state with 5 in the first box, 4 in the second box, and so forth): swapping 5 and 4, then 5 and 3, 5 and 2, 5 and 1, 4 and 3, 4 and 2, 4 and 1, 3 and 2, 3 and 1,and finally 2 and 1. Then how many swaps we need to sort [5, 5; 4, 4; 3, 3; 2, 2; 1, 1] (the state with two 5’s in the first box, two 4’s in the second box, and so forth)? Some of you might think 20 swaps — this is not true, but the actual number is 15.

      Write a program that calculates the number of swaps for the two-ball version and verify the above fact.

      Input

      The input has the following format:

      
             n
             ball1,1 ball1,2
             ball2,1 ball2,2
             ...
             balln,1 balln,2
      

      n is the number of boxes (1 ≤ n ≤ 8). balli,1 and balli,2 , for 1 ≤ in, are the labels of two balls initially contained by the i-th box.

      Output

      Print the minumum possible number of swaps.

      Example

      Input:
      5
      5 5
      4 4
      3 3
      2 2
      1 1
      
      Output:
      15
      

      Added by:Bin Jin
      Date:2009-11-03
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.0.0-8
      Resource:JAG Summer Camp 2009, day2









      SPOJ Problem Set ()

      5196. Monotonous numbers

      Problem code: MONONUM

      Some integers possess interesting quality: each of their digits is not greater than the digit to the right. Let us define such integers as increasing integers. And let's call integers for which each digit is not lesser than the digit to the right decreasing integers. For example 24558 is increasing, 888410 is decreasing and 5 - is both increasing and decreasing. Given n calculate the ratio of the decreasing n-digit integers to the increasing n-digit integers. We consider only positive integers. Leading zeros are not allowed.

      Input

      The first line of the input contains number t – the amount of tests. Then t test descriptions follow. Each test consists of the single integer n

      Constraints

      1 <= t <= 10000
      1 <= n <= 106

      Output

      For each test print the needed ratio with six digits in the fractional part.

      Example

      Input:
      2
      1
      2
      
      Output:
      1.000000
      1.200000
      

      Added by:Spooky
      Date:2009-11-03
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Advancement Autumn 2009, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set (classical)

      5197. Differential Diagnosis

      Problem code: DIFFDIAG

      Daniel enjoys watching TV series. One of his favorite is "Doctor Chaos". In this series the medical genius is saving people by making difficult diagnosis. In his work he employs the differential diagnosis method. Doctor Chaos writes all the symptoms the patient have on the white board and his team tries to find out the disease which explains those symptoms best. Sometimes some symptoms are not caused by the disease itself. Sometimes some symptoms are not revealed yet and are not written on the board. Anyhow the team chooses come candidate-diseases and then runs the tests to identify the right one. Help Doctor Chaos by making a program which find out the diseases that are explaining the set of symptoms the best way. We'll say that the disease explains the set of symptoms the best way if it explains the most symptoms from the set among all known diseases.

      Input

      The first line of the input file contains number n - the amount of diseases known to Chaos and his team. Then n lines follow describing each disease. The description of the disease starts with the name of the disease. Then number k follows, that is the amount of different symptoms caused by the disease. Then there go the names of the symptoms separated by spaces. After the description of all the diseases there is number t - the amount of cases to diagnose. After that t lines follow each containing a set of symptoms. Each set starts with the number q - the amount of different symptoms. Then q names of the symptoms follow separated by spaces. The names of all diseases and symptoms consist of only small latin letters and don't exceed 20 characters. Each symptom in each set is explained by at least one disease.

      Constraints

      1 <= n <= 1000
      1 <= k <= 10
      1 <= t <= 10000
      1 <= q <= 10
      There are no more than 1000 different symptoms.

      Output

      For each case to diagnose first print the line "Diagnosis #x:" where x is the case number starting from one. Then list all the diseases which explains the corresponding set of symptoms best. The diseases should be listed one in line and in the same order in which they were given in the input file.

      Example

      Input:
      3
      migraine 2 headache nausea
      poisoning 3 nausea stomachache fever
      flu 3 fever cough headache
      4
      1 fever
      2 nausea headache
      2 nausea cough
      4 fever nausea cough headache
      
      Output:
      Diagnosis #1:
      poisoning
      flu
      Diagnosis #2:
      migraine
      Diagnosis #3:
      migraine
      poisoning
      flu
      Diagnosis #4:
      flu
      

      Added by:Spooky
      Date:2009-11-03
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Autumn 2009, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      5240. Area of a Garden

      Problem code: GARDENAR

      One rich person decided to make himself a great garden. The garden should have a from of equilateral triangle. There should be a gazebo inside the garden. The gazebo will be connected with the triangle vertexes by roads. The lengths of all three roads are known. Those numbers are sacred for this rich man. The expense of building such a garden will depend on the area of the garden. Help the rich man by calculating what will be the area of his garden.

      Input

      The first line of the input contains number t – the amount of tests. Then t test descriptions follow. Each test consist of three integers a, b, c - the lengths of the roads. It is guaranteed that it's possible to build such a garden.

      Constraints

      1 <= t <= 1000
      1 <= a, b, c <= 1000

      Output

      For each test print the area of the garden with two digits in the fractional part.

      Example

      Input:
      1
      3 4 5
      
      Output:
      19.83
      

      Added by:Spooky
      Date:2009-11-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Autumn 2009, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set (classical)

      5294. Recurrence

      Problem code: REC


      Let F0 = 1. Fn = a*Fn-1 + b for n >= 1. Find Fn (mod M).

      Input

      The first line contains T the number of test cases. Each of the next T lines contains 4 space seperated integers a, b, n and M.

      Constraints

      T <= 20000
      0 <= a, b, n <=  10^100
      1 <= M <= 100000

      Output

      Output T lines, one corresponding to each test case.

       

      Example

      Input:
      3
      1 1 1 10
      2 1 2 5
      5 2 20 30

      Output:
      2
      2
      7


      Added by:abhijith reddy d
      Date:2009-11-14
      Time limit:3s-6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SED









      SPOJ Problem Set (classical)

      5295. Adjacent Bit Counts

      Problem code: GNYR09F

      For a string of n bits x1,x2,x3,...,Xn the adjacent bit count of the string (AdjBC(x)) is given by


      X1*X2 + X2*X3 + X3*X4 + ... + Xn-1 * Xn


      which counts the number of times a 1 bit is adjacent to another 1 bit. For example:
      AdjBC(011101101) = 3
      AdjBC(111101101) = 4
      AdjBC(010101010) = 0

      Write a program which takes as input integers n and k and returns the number of bit strings x of n bits (out of 2ⁿ) that satisfy AdjBC(x) = k. For example, for 5 bit strings, there are 6 ways of getting AdjBC(x) = 2:
      11100, 01110, 00111, 10111, 11101, 11011

      Input

      The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set is a single line that contains the data set number, followed by a space, followed by a decimal integer giving the number (n) of bits in the bit strings, followed by a single space, followed by a decimal integer (k) giving the desired adjacent bit count. The number of bits (n) will not be greater than 100 and the parameters n and k will be chosen so that the result will fit in a signed 32-bit integer.

      Output

      For each data set there is one line of output. It contains the data set number followed by a single space, followed by the number of n-bit strings with adjacent bit count equal to k.

      Example

      Input:
      10
      1 5 2
      2 20 8
      3 30 17
      4 40 24
      5 50 37
      6 60 52
      7 70 59
      8 80 73
      9 90 84
      10 100 90
      Output:
      1 6
      2 63426
      3 1861225
      4 168212501
      5 44874764
      6 160916
      7 22937308
      8 99167
      9 15476
      10 23076518

      Added by:Tamer
      Date:2009-11-14
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ACM Greater New York Regional Contest 2009









      SPOJ Problem Set (classical)

      5296. Air Combat

      Problem code: COMBAT


      An air combat is on the way, you are asked to command this war. Now planes of enemy are full of the sky. A plane is described with three-dimensional coordinate (x, y, z)(1000<x, y, z<1200), and all coordinates are integers. As is show below:

      You have created a missile which can destroy all the planes in a cube whose center is (x, y, z), and the cube can be as large as (x-r, y-r, z-r) (x+r, y+r, z+r). This missile is so fierce that it will destroy not only enemy in that space, but also friends. And after that a position is occupied by a plane belongs to the opposite side before the explosion, that is to say an enemy plane will be replaced by a friend, a friend will be replaced by an enemy.

      You want to reduce our loss, so you need to know which side a plane belongs to in a position.

       

      Input

      The first line contains the number of scenarios.
      For each scenario you are given a line containing x1 y1 z1 x2 y2 z2, defining the two corners A(x1, y1, z1), B(x2, y2, z2) (1000<= x1<x2, y1<y2, z1<z2 <=1200) of the sky. The combat is so fierce that every point in the cube is occupied by an enemy plane at first.

      Next line is a number of operation q.

      Next q lines: (0<q<10000)

      A character ‘U’:  followed by 4 integers, a center point M(xi, yi, zi) ,the range is ri.

      A character ‘Q’:  followed by 3 integers, a position N(xi, yi, zi), if a plane belongs to us, print ”Friend” else print ”Enemy”.

      Points M and N are all in cube given above.

      Output

      Print a line for every ‘Q’ operation.

      Example

      Input:

      1

      1000 1000 1000 1002 1002 1002

      4

      U 1000 1000 1000 0

      U 1001 1001 1001 1

      Q 1000 1000 1000

      Q 1001 1001 1001

      Output:

      Enemy

      Friend


      Added by:Hemant Verma
      Date:2009-11-14
      Time limit:1s
      Source limit:2000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Alkhwarizm 2009









      SPOJ Problem Set (classical)

      5298. Interval Challenge

      Problem code: INTERVA2

      Give you N ( 1 <= N <= 200000 ) intervals, represented as [A, B], for example , interval s represented as [As,Bs].

      For two intervals s and t, we say S covered by T if  At <= As and Bs <= Bt. Now my problem is easy, just tell me the question below: For each interval, how many intervals can cover it but not covered by it ?

      Input

      The input contains multiple test cases.
      For each test case, the first line is an integer N ( 1 <= N <= 200000 ), which is the number of intervals. Then come N lines, the i-th of which contains two integers: Ai and Bi ( Ai , Bi will not exceed the 32-bit integer) specifying the two parameters described above.

      Output

      For each test case, output one line containing n space-separated integers, the i-th of which specifying the number of intervals that can cover it but not covered by it. 

      Example

      Input

      3

      0 1

      -1 2

      -2 3

       

      2

      0 1

      0 1

      Output:

      2 1 0

      0 0


      Added by:Hemant Verma
      Date:2009-11-14
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Alkhwarizm 2009









      SPOJ Problem Set (classical)

      5300. Mexican Standoff

      Problem code: MEXICAN

      The town of San Saba is too small for more than one gunslinger. Unfortunately, all of them turned up on the same day, one fine spring morning. As it turned out, love was in the air and they were all trying to woo Alice, the sheriff's daughter. As only one of them could win her love, they decided to do the only gentlemanly thing left to do - they decided to have a Mexican Standoff.

       

      There are multiple rounds in this standoff. In each round, all gunslingers still alive first form a large circle, with each of them facing the centre of the circle. To prevent a fight for position while forming the circle, the men have decided that they will line up in the lexicographic order of their names, and then connect the ends of the line to form the required circle. Once they have taken their positions Alice drops a scarf from her hand, and the moment it hits the ground all the men simultaneously draw out their two guns (one from the left holster and one from the right) and fire both of them. Each man aims the gun from the left holster at the person to his immediate left in the circle and the other gun at the person to his immediate right. Of course, not all gunslingers are equal - they have different reaction times and hence fire their guns at different times. If a man is fired upon before he can fire, he dies and is thus unable to fire his own gun. If two men fire at each other at exactly the same time, they both die. After the round is over, the bodies of the dead men are removed from the circle by those alive, who then head to the next round. If there is only one man left standing after a round, the standoff is over and the lucky survivor gets to marry Alice. If no one survives after a particular round, then Alice remains single of course.

       

      Unfortunately, Alice only likes some of the men. So she decided that before each round, she would remove a single bullet from the gun in either the left or the right holster (but not both) of at most one of the men. Being a little lazy, she wants to know the minimum number of rounds in which she must remove a bullet so that she gets to marry one of the men she likes. If she does not likes anyone, it means that she wants to remain single.

      Input

      The first line contains T the number of test cases (1 <= T <= 30). The first line of each test case contains N, the number of gunslingers in town (2 <= N <= 60). Each of the next N lines contains the name of the gunslinger (between 1 and 20 lower case letters, each gunslinger will have a unique name), his reaction time in milliseconds (1 <= reaction time <= 1000) and whether Alice likes him or not (Y or N), separated by spaces.

      Output

      For each test case, a line containing a single integer equal to the minimum number of rounds in which Alice needs to remove a bullet, or -1 if it is impossible for her desire to be fulfilled.

      Example

      Input:
      3
      3
      good 100 Y
      bad 200 N
      ugly 100 N
      3
      good 100 N
      bad 200 N
      ugly 100 N
      3
      good 100 Y
      bad 100 N
      ugly 100 N

      Output: 1
      0
      -1

      Explanation
      1. Alice likes only Good, so she removes a bullet from the gun which Ugly will use to fire at Good.
      Good survives while Bad and Ugly are killed.
      2. Alice doesn't like any of them, and she doesn't have to lift a finger to remain single.
      3. Alice likes only Good, but all of them are equally fast, so she can't save him and will remain
      single in his memory.

      Added by:Hemant Verma
      Date:2009-11-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Alkhwarizm 2009









      SPOJ Problem Set (classical)

      5301. Query Problem

      Problem code: QUERYSTR


      McFn interesed in string problem recently.He found a interesing function and he felt he could use this function to invent a new match algorithm.

      For a string S [1 ... n] and i ¡Ê [1, n], define F (i) is the length of the longest common suffix of S and S [1 ... i].
      For example, for the string S [1 ... 11] = zaaxbaacbaa, then F (1) = 0, F (2) = 1, F (3) = 2 (note that S [1 ... 3] = zaa), F (4) = 0, ... ... F (10) = 1, F (11) = 11;
      For the string S [1 ... n], i ¡Ê [1, n], S [i ... n] is its suffix;

      Input

      The first line is a integer T.the number of test cases
      for each test case
      The first line is a string S, composed of only lowercase letters,  len (s) is the length of s,  1 <= len (s) <= 1000000;
      Next line, a number N (1 <= N <= 100000), denote that the number of quiries;
      The next N lines, each line contains a number x (1 <= x <= len (s)).

      Output

      For each x the output F (x);

      Example

      Input:
      1
      zaaxbaacbaa
      11
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11

      Output: 0
      1
      2
      0
      0
      1
      3
      0
      0
      1
      11

      Added by:Hemant Verma
      Date:2009-11-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Alkhwarizm 2009









      SPOJ Problem Set (classical)

      5317. Tetravex Puzzle

      Problem code: TETRAVEX

      TetraVex is a challenging computer brain teaser.  The object of the game is to fill the grid with the tiles so that the numbers on the adjacent edges of each tile match, much like aligning domino tiles.

      Given the 9 tiles, you have to find out whether it is possible to solve the puzzle. Each tile is represented using 4 digits. A tile is given in the order A B C D in the clockwise direction starting from top cell. So the top left tile is denoted as ‘2 1 4 9’ and the bottom right as ‘2 1 6 6’. You cannot rotate the tiles, that is the original order must be preserved.

      Input

      There will be many cases in the input file. The first line gives the number of test cases ( <= 20 ). Each case consists of 9 lines giving 4 integers each. Each line gives the information of a tile in the order A B C D. The tiles are randomly given.

      Output

      For each case, output YES or NO. Follow the sample for exact format

      Example

      Input:
      

      2

      2 8 4 6

      1 1 3 5

      0 4 2 8

      2 5 3 3

      7 6 0 4

      7 3 0 6

      4 8 7 7

      0 3 1 2

      2 2 2 8

       

      1 1 1 1

      2 2 2 2

      3 3 3 3

      4 4 4 4

      5 5 5 5

      6 6 6 6

      7 7 7 7

      8 8 8 8

      9 9 9 9 Output:

      Case 1: YES

      Case 2: NO


      Added by:Hemant Verma
      Date:2009-11-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Alkhwarizm 2009









      SPOJ Problem Set ()

      5373. Four Mines

      Problem code: MINES4

      A Company that Makes Everything (ACME) has entered the surface mining business. They bought a rectangular field which is split into cells, with each cell having a profit value. A mine is a non-empty rectangular region, and the profit of a mine is equal to the sum of the values of all its cells. ACME wants to extract ore from four different non-overlapping mines. You are to choose these mines to maximize the total profit.

      A Company that Makes Everything (ACME) has entered the surface mining business. They bought a rectangular field which is split into cells, with each cell having a profit value. A mine is a non-empty rectangular region, and the profit of a mine is equal to the sum of the values of all its cells. ACME wants to extract ore from <b>four</b> different non-overlapping mines. You are to choose these mines to maximize theA Company that Makes Everything (ACME) has entered the surface mining business. They bought a rectangular field which is split into cells, with each cell having a profit value. A mine is a non-empty rectangular region, and the profit of a mine is equal to the sum of the values of all its cells. ACME wants to extract ore from <b>four</b> different non-overlapping mines. You are to choose these mines to maximize the total profit. 
      A Company that Makes Everything (ACME) has entered the surface mining business. They bought a rectangular field which is split into cells, with each cell having a profit value. A mine is a non-empty rectangular region, and the profit of a mine is equal to the sum of the values of all its cells. ACME wants to extract ore from <b>four</b> different non-overlapping mines. You are to choose these mines to maximize the total profit. 
       total profitA Company that Makes Everything (ACME) has entered the surface mining business. They bought a rectangular field which is split into cells, with each cell having a profit value. A mine is a non-empty rectangular region, and the profit of a mine is equal to the sum of the values of all its cells. ACME wants to extract ore from four different non-overlapping mines. You are to choose these mines to maximize the total profit.A Company that Makes Everything (ACME) has entered the surface mining business. They bought a rectangular field which is split into cells, with each cell having a profit value. A mine is a non-empty rectangular region, and the profit of a mine is equal to the sum of the values of all its cells. ACME wants to extract ore from <b>four</b> different non-overlapping mines. You are to choose these mines to maximize the total profit. 

      Input

      The first line contains an integer T (1 ≤ T ≤ 5), denoting the number of test cases.

      For each test case, the first line contains two positive integers R and C (2 ≤ R,C ≤ 100), denoting the number of rows and columns of a rectangular field.

      Each of next R lines contain C integers between -10000 and 10000, denoting a profit value for each cell in that row.

      Output

      For each test case, print a number on its own line, denoting the maximum total profit that can be extracted from four mines.

      Example

      Input:
      2
      5 5
      10 10 -1 -1 10
      10 -1 -1 -1 10
      -1 -1 -1 -1 -1
      -1 -1 -1 10 10
      10 -1 -1 10 10
      2 3
      -1 -2 -3
      -4 -5 66
      
      Output:
      99
      60
      

      Added by:Luka Kalinovcic
      Date:2009-11-22
      Time limit:16s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ThreeMines from TopCoder SRM 315 extended









      SPOJ Problem Set (classical)

      5446. Fishing Net

      Problem code: FISHNET

      In a highly modernized fishing village, inhabitants there make a living on fishery. Their major tools, fishing nets, are produced and fixed by computer. After catching fishes each time, together with plenty of fishes, they will bring back the shabby fishing nets, which might be full of leaks. Then they have to inspect those nets. If there exist large leaks, they have to repair them before launching out again.

      Obviously, the smaller the leaks in the fishing nets are, the more fishes they will catch. So after coming back, those fishermen will input the information of the fishing nets into the computer to check whether the nets have leaks. The checking principle is very simple: The computer regards each fishing net as a simple graph constructed by nodes and edges. In the graph, if any circle whose length (the number of edges) is larger than 3 must has at least one chord, the computer will output "Perfect" indicating that the fishnet has no leaks. Otherwise, "Imperfect" will be displayed and the computer will try to repair the net.

       


      Note: A circle is a closed loop, which starts from one node, passes through other distinct nodes and back to the starting node. A chord is an edge, which connects two different nodes on the circle, but it does not belong to the set of edges on the circle.

      Input

      The input file contains several test cases representing different fishing nets. The last test case in the input file is followed by a line containing 0 0.

      The first line of each test case contains two integers, n and m , indicating the number of nodes and edges on the net respectively, 1$ \le$n$ \le$1000 . It is followed by m lines accounting for the details of the edges. Each line consists of two integers xi and yi , indicating there is an edge between node xi and node yi .

      Output

      For each test case, display its checking results. The word "Imperfect" suggests that the corresponding fishing net is leaking, while the word "Perfect" stands for a fishing net in good condition.

      Follow the output for each net with a blank line.

      Example

      Input:
      
      4 4
      1 2
      2 3
      3 4
      4 1
      3 3
      1 2
      2 3
      3 1
      0 0
      Output:
      Imperfect
      
      Perfect

      Added by:gogo40
      Date:2009-11-28
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC Shanghai 2001-2002









      SPOJ Problem Set (classical)

      5449. Seinfeld

      Problem code: ANARC09A

      I’m out of stories. For years I’ve been writing stories, some rather silly, just to make simple problems look difficult and complex problems look easy. But, alas, not for this one.

      You’re given a non empty string made in its entirety from opening and closing braces. Your task is to find the minimum number of “operations” needed to make the string stable. The definition for being stable is as follows:

      1. An empty string is stable.
      2. If S is stable, then {S} is also stable.
      3. If S and T are both stable, then ST (the concatenation of the two) is also stable.

      All of these strings are stable: {}, {}{}, and {{}{}}; But none of these: }{, {{}{, nor {}{.
      The only operation allowed on the string is to replace an opening brace with a closing brace, or visa-versa.

      Input

      Your program will be tested on one or more data sets. Each data set is described on a single line. The line is a non-empty string of opening and closing braces and nothing else. No string has more than 2000 braces. All sequences are of even length.

      The last line of the input is made of one or more ’-’ (minus signs.)

      Output

      For each test case, print the following line:

      k. N

      Where k is the test case number (starting at one,) and N is the minimum number of operations needed to convert the given string into a balanced one.

      Example

      Input:
      }{
      {}{}{}
      {{{}
      ---

      Output: 1. 2
      2. 0
      3. 1

      Added by:Mohammad Kotb
      Date:2009-11-28
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: BASH JAR JS
      Resource:http://www.icpc-anarc.org









      SPOJ Problem Set ()

      5450. Tiles of Tetris, Not!

      Problem code: ANARC09B

      You’ve really messed up this time. “Go buy some square tiles” your supervisor told you. But as usual, you were either busy reading that message, answering that e-email, or updating your wall status on facebook. “Go buy some tiles” was all that you could remember. Your supervisor is
      now complaining that the tiles you bought were not squares and you’ll be fired if you don’t fix it! “Fix it? How am I supposed to fix it?” you say to yourself. “I’m a programmer, The only tiles I know are those of the game Tetris!” There is no way you can afford to be fired either. This is your third job in less than a month. “I have to fix it!” you keep repeating.You call the store you bought the tiles from, but they won’t take them back or even exchange. “We cannot cancel orders once the merchandise has left the store”, they tell you. You take a look at the tiles, they’re all rectangle- shaped and all of the same size. You’d be losing a lot if you cut them, not that you’d be able to cut them into perfect squares in the first place. “Wait a minute!” you say to yourself. You grab a bunch of tiles, put them in some arrangement and Voila, that’s a square. But that won’t convince your boss. Tiles are supposed to be small, and what you came-up with is rather big. You take another look at your arrangement, and it hits you again. “I’m on a roll today!” you say proudly to yourself. You just figured out how to find the smallest number of tiles needed to form the smallest possible square.

      You rush and bring your supervisor to show him your discovery. He’s not that much impressed. You’re not making sense anyway (given all the blood rushing in your head trying to explain your algorithm.) You know that the calculation is definitely much simpler than what you’re saying, but you just can’t seem to think clearly. Finally, your supervisor shouts: “First of all, the tiles have to be laid-down in the same orientation. Second, I’m running a construction site here, not a software shop! How do you expect the workers to figure out that number! You either write me a program to do the calculation you’re describing, or you go collect your netbook, your cell, your ipod, and your blackberry, and you get out of here this minute!”

      Input

      Your program will be tested on one or more data sets. Each test set is described on a single line made of two positive numbers: (0 < W, H < 1, 000, 000) which are the width and height of each tile. The last line is made of two zeros.

      Output

      For each test case, write the answer on a separate line.

      Example

      Input:
      2 3
      1 2
      0 0

      Output:
      6
      2

      Added by:Mohammad Kotb
      Date:2009-11-28
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:http://www.icpc-anarc.org









      SPOJ Problem Set (classical)

      5451. Not So Flat After All

      Problem code: ANARC09C

      Any positive integer v can be written as p1a1 ∗ p2a2 ∗ . . . ∗ pnan where pi is a prime number and ai ≥ 0. For example: 24 = 23 ∗ 31 .

      Pick any two prime numbers p1 and p2 where p1 != p2 . Imagine a two dimensional plane where the powers of p1 are plotted on the x-axis and the powers of p2 on the y-axis. Now any number that can be written as p1a1 ∗ p2a2 can be plotted on this plane at location (x, y) = (a1 , a2 ). The figure on the right shows few examples where p1 = 3 and p2 = 2.

      This idea can be extended for any N -Dimensional space where each of the N axes is assigned a unique prime number. Each N -Dimensional space has a unique set of primes. We call such set the Space Identification Set or S for short. |S| (the ordinal of S) is N .

      Any number that can be expressed as a multiplication of pi ∈ S (each raised to a power (ai ≥ 0) can be plotted in this |S|-Dimensional space. The figure at the bottom illustrates this idea for N = 3 and S = {2, 3, 7}. Needless to say, any number that can be plotted on space A can also be plotted on space B as long as SA ⊂ SB .

      We define the distance between any two points in a given N -Dimensional space to be the sum of units traveled to get from one point to the other while following the grid lines (i.e. movement is always parallel to one of the axes.) For example, in the figure below, the distance between 168 and 882 is 4.

      Given two positive integers, write a program that determines the minimum ordinal of a space where both numbers can be plotted in. The program also determines the distance between these two integers in that space.

      Input

      Your program will be tested on one or more test cases. Each test case is specified on a line with two positive integers (0 < A, B < 1, 000, 000) where A ∗ B > 1.
      The last line is made of two zeros.

      Output

      For each test case, print the following line:

      k. X:D

      Where k is the test case number (starting at one,) X is the minimum ordinal needed in a space that both A and B can be plotted in. D is the distance between these two points.

      Example

      Input:
      168 882
      770 792
      0 0

      Output:
      1. 3:4
      2. 5:6

      Added by:Mohammad Kotb
      Date:2009-11-28
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:http://www.icpc-anarc.org









      SPOJ Problem Set ()

      5452. Hop Do not Walk

      Problem code: ANARC09D

      Kermit The Frog is a classic video game with a simple control and objective but requires a good deal of thinking. You control an animated frog that can walk and hop, in both forward and backward directions. The frog stands in a space between an otherwise a contiguous line of tiles. Each tile is painted black on one side, and white on the other. The frog can walk (forward, or backward) over an adjacent tile (in front or behind him.) When the frog walks over a tile, the tile slides to the space where the frog was standing. For example, in the adjacent figure, the frog has two tiles behind him, and three in front. We’ll use the notation BWFBBW to refer to this situation where F refers to the space (where the frog is standing,) B is a tile with its black face showing, while W is a tile with its white face showing. The forward direction is from left to right. If the frog were to walk forward, the resulting situation is BWBFBW. Similar behavior when the frog walks backward, the tile behind the frog slides to where the frog was standing. The frog can also hop over the tiles. The frog can hop over an adjacent tile landing on the tile next to it. For example, if the frog was to hop backward, it would land on the first (left-most) tile, and the tile would jump to the space where the frog was standing. In addition, the tile would flip sides. For example, hopping backward in the figure would result in the situation: FWWBBW. We challenge you to write a program to determine the minimum number of moves (walks or hops) to transform one tile configuration into another.

      Input

      Your program will be tested on one or more test cases. Each test case is specified on a single line that specifies string S representing the initial tile arrangement. S is a non-empty string and no longer than 100 characters and is made of the letters ’B’, ’W’, and exactly one ’F’. The last line of the input file has one or more ’-’ (minus) characters.

      Output

      For each test case, print the following line:
      k. M
      Where k is the test case number (starting at one,) and M is the minimum number of moves needed
      to transform the given arrangement to an arrangement that has no white tile(s) between any of
      its black tiles . The frog can be anywhere. M is -1 if the problem cannot be solved in less than 10
      moves.

      Example

      Input:
      WWBBFBW
      WWFBWBW
      FWBBWBW
      ---

      Output:
      1. 0
      2. 1
      3. 2

      Added by:Mohammad Kotb
      Date:2009-11-28
      Time limit:12s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:http://www.icpc-anarc.org









      SPOJ Problem Set (classical)

      5453. Air Strike

      Problem code: ANARC09F


      General Gee is the commander of a military base. He has just received alarming news from one of his spies: the enemy’s preparing an air missile strike. The base contains two magnetic towers. When activated and given sufficient power, each of the magnetic towers creates a powerful horizontal magnetic disk. If any missile passes through this disk it deflects away from the base. Although those towers seem to be an excellent air defense method, there is a problem: The area of the disk generated by a tower is proportional to the amount of energy it receives. The base has enough power plants to generate a certain amount of energy, which has to be divided among those two towers. That means that the total area of the two disks generated from the towers should not exceed the total energy generated by the power plants. Fortunately, the spy was able to know the exact target co-ordinates of the incoming missiles and he reported them to General Gee. The General needs your help in distributing the energy on the two magnetic towers to minimize the number of missiles that will not get deflected by the magnetic towers and therefore will hit the base. You may assume the following:

      • The towers have different heights and therefore there are no problems associated with the magnetic disks interfering with each other.
      • A missile will deflect if it passes through the magnetic disk of a tower or even if it just touches its boundary.
      • A missile hitting a tower (landing exactly on its location) will deflect, even if the tower is not given any energy.
      • All incoming missiles will go down simultaneously at the exact instant; therefore, there will not be any time available to redistribute the energy amongst the two towers during the strike.

      Input

      Input consists of several test cases. Each test case is specified on N +2 lines. The first line contains an integer (1 ≤ N ≤ 1, 000) representing the number of missiles. The second line contains 5 real numbers X1 , Y1 , X2 , Y2 and T : (X1 , Y1 ) is the coordinates of the first tower, (X2 , Y2 ) is the coordinates of the second tower and (0 ≤ T ) is the total amount of energy generated from the power plants (the total area of the two magnetic disks). Each line of the remaining N lines contains two real numbers representing the landing coordinates of a missile. The absolute value of all the given real numbers is less than or equal to 100 and may include a decimal point followed by up to 3 digits. Any two consecutive numbers on the same line are separated by one or more white-space characters. Zero or more blank lines may appear between test cases.
      The last line of the input file is made of a single zero.

      Output

      For each test case, print the following line:
      k. M
      Where k is the test case number (starting at one,) and M is the minimum number of missiles that will NOT be deflected in the best distribution of energy among the two towers. Use π = 3.141.

      Example

      Input:
      6
      -3 0 3 0 40.833
      -1 4
      -2 2.5
      1 2
      5 2
      -4 0
      -3 -1
      2
      0 0   1 1 0
      0 0
      1 1
      0

      Output:
      1. 2
      2. 0

      Added by:Mohammad Kotb
      Date:2009-11-28
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://www.icpc-anarc.org









      SPOJ Problem Set (acm)

      5463. Bird or not bird

      Problem code: BIRD

      You are studying animals in a forest, and are trying to determine which animals are birds and which are not.


      You do this by taking two measurements of each animal – their height and their weight. For an animal to be a bird, its height needs to be within some range, and its weight needs to be within another range, but you're not sure what the height and weight ranges are. You also know that every animal that satisfies these ranges is a bird.


      You have taken some of the animals you have measured and shown them to biologists, and they have told you which are birds and which are not. This has given you some information on what the height and weight ranges for a bird must be. For the remaining animals, your program should determine if they are definitely birds, definitely not birds, or if you don't know from the information you have.


      Input
      One line containing an integer C, the number of test cases in the input.
      For each of the C test cases:
      • One line containing an integer N, the number of animals you have shown to the
      biologists.
      • N lines, one for each of these animals, each of the format "H W X", where H is the height
      of the animal, W is the weight of the animal, and X is either the string "BIRD" or "NOT
      BIRD". All numbers are positive integers.
      • One line containing an integer M, the number of animals you have not shown to the
      biologists.
      • M lines, one for each of these animals, each of the format "H W", where H is the height
      of the animal and W is the weight of the animal. All numbers are positive integers.


      Output
      For each of the C test cases:
      • One line containing the string "Case #X:" where X is the number of the test case, starting
      from 1.
      • M lines, each containing one of "BIRD", "NOT BIRD", or "UNKNOWN" (quotes are
      just for clarity and should not be part of the output).


      Limits
      1 <= C <= 20
      1 <= all heights and weights <= 1000000
      1 <= N <= 1000
      1 <= M <= 1000

      Sample input
      3
      5
      1000 1000 BIRD
      2000 1000 BIRD
      2000 2000 BIRD
      1000 2000 BIRD
      1500 2010 NOT BIRD
      3
      1500 1500
      900 900
      1400 2020
      3
      500 700 NOT BIRD
      501 700 BIRD
      502 700 NOT BIRD
      2
      501 600
      502 501
      1
      100 100 NOT BIRD
      3
      107 93
      86 70
      110 115


      Sample output
      Case #1:
      BIRD
      UNKNOWN
      NOT BIRD
      Case #2:
      UNKNOWN
      NOT BIRD
      Case #3:
      UNKNOWN
      UNKNOWN
      UNKNOWN


      Added by:sieunhan
      Date:2009-11-29
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Google Code Jam - ACM Vietnam Practice









      SPOJ Problem Set (classical)

      5464. Counting triangles

      Problem code: CT

      Consider a 2D integer grid with lower left corner at (0, 0) and upper right corner at (X, Y). We are interested in isosceles right triangles which all the 3 corners at the grid node (integer coordinates). Your task is to count the number of those triangles.


      Input
      The input begins with C – number of test cases.
      Each test case consists of X, Y.


      Output
      For each test case, output the result in a line.


      Limits
      C <= 20
      0 <= X, Y <= 1000


      Sample input
      2
      0 3
      1 1


      Sample output
      0
      4


      Added by:sieunhan
      Date:2009-11-29
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Le Don Khue - ACM Vietnam Practice









      SPOJ Problem Set (classical)

      5465. Deliver pizza

      Problem code: DP

      Tom McCoffee owns the only pizza delivery place in the mountains. The terrain is represented as a rectangular grid of squares, where each square either contains a building or is empty. Each empty square has an integer height between 0 and 9, inclusive. Today, each building in the area has ordered one pizza, and Tom must use his two delivery boys to fulfill all the orders in the shortest total amount of time possible.


      From each square in the grid, you can only move to adjacent squares. Two squares are adjacent if they share an edge. You can only move between two empty squares if the absolute difference of their heights is less than or equal to 1. If the height difference is 0, it takes 1 minute to make the move, and if the absolute height difference is 1, it takes 3 minutes.

      You can always move to a building from any of its adjacent squares and vice versa, regardless of height. This is because all buildings are taller than the highest terrain, and each building has entrances and exits for all its adjacent squares at the correct heights. Moving to or from a square containing a building takes 2 minutes. The delivery boys are allowed to enter buildings even if they are not their final destinations. Note that the pizza place itself is also a building.


      Each delivery boy can only carry one pizza at a time. This means that after each delivery, the delivery boy must return to the pizza place to pick up another pizza if there are more deliveries left to do.


      Your task is to print the minimum time in minutes at which the last delivery can be made. If it is not possible to deliver all the pizzas, print -1 instead.


      Input
      One line containing an integer C, the number of test cases in the input.
      For each of the C test cases:
      • The first line consists of M and N the size of the grid. M is the number of rows and N is
      the number of columns.
      • The next M lines consists of a string which length is N. Each character could be ‘$’, ‘X’
      or digits from ‘0’ to ‘9’. '$' represents a building from which a pizza was ordered, 'X'
      represents the location of the restaurant, and the digits '0'-'9' represent the heights of
      empty squares.


      Output
      For each test case, print the minimum time in minutes at which the last delivery can be made. If
      it is not possible to deliver all the pizzas, print -1 instead.


      Limits
      1 <= C <= 30
      1 <= M <= 50
      1 <= N <= 50
      There are at most 20 buildings.

      Sample input
      2
      3 7
      3442211
      34$221X
      3442211
      3 7
      001000$
      $010X0$
      0010000


      Sample output
      8
      13


      Added by:sieunhan
      Date:2009-11-29
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Topcoder - ACM Vietnam Practice









      SPOJ Problem Set (acm)

      5466. Electronic queue

      Problem code: EQ

      The train station has just used a new electronic queue system. Now passengers who want to buy tickets have to get the service ordering number and wait until it is his turn.


      In this station, there are N cashers; each can serve one passenger at a time. When it’s your turn, you will go to an assigned cashier to chose a ticket and pay for it. If you want to buy K tickets it will take you 5 minutes to chose the train, the time, the seats, etc and K more minutes for your tickets to be printed. If there are several available cashiers, a passenger would be assigned to the one with the lowest number.


      Given the arrival time of passengers at the station and the amount of tickets they want to buy, your task is to calculate the total time P passengers spend buying their tickets (waiting time and buying time).


      Input
      The first line is C, the number of test cases.
      For each test case:
      • The first line is N – number of cashiers.
      • The next line consists of P – the number of passengers.
      • The next P lines contain a pair of integers: the arrival time and the number of tickets he
      wants to buy.
      • The arrival time of these P passengers will be distinct and will be sorted increasingly.


      Output
      For each test case, print total time of P passengers spend buying their tickets.


      Limits
      1 <= C <= 15
      1 <= N <= 50
      1 <= P <= 10000
      All others numbers in the input are positive and less than 1000.


      Sample input
      1
      2
      3
      1 1
      2 10
      3 2


      Sample output
      32


      Added by:sieunhan
      Date:2009-11-29
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ACM Vietnam Practice









      SPOJ Problem Set (acm)

      5467. Finding password

      Problem code: FP

      Bom has a list of n favorite numbers which are birthday, driving license, passport number, etc After creating an email account, Bom wants to choose a password as the largest number P among all possible numbers generated by the combinations of k (1 <= k <= n) positive numbers in the favorite list so that P is divisible by 9.


      Your task is writing a program to help find P the password for Bom’s email.


      Input
      The first line contains a positive integer T as the number of test cases in the input file. The
      following lines describe information of each test case including:
      • One line containing two positive integers n and k,
      • n following lines are n favorite numbers.


      Output
      The output file contains T lines; each line is the solution of the corresponding test case that is
      either password P or -1 in case of not finding a feasible number.


      Limits
      T <= 30
      1 <= k <= n <= 100
      1 <= all favorite numbers <= 10^6


      Sample input
      2
      3 2
      1
      2
      3
      5 2
      1
      2
      3
      4
      5


      Sample output
      -1
      54


      Added by:sieunhan
      Date:2009-11-29
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Do Duc Dong - ACM Vietnam Practice









      SPOJ Problem Set (classical)

      5468. Going to school

      Problem code: GS

      Your family has just moved to small town with simple transportation system: there are N conjunctions and N - 1 roads connecting the conjunctions. These roads guarantee that it’s possible to travel between any two conjunctions. Each road connects two conjunctions and has a preferred value.


      You are new here and not familiar with the roads. So when you stay at a conjunction which is not your destination, you will choose one of incident roads to walk (even it makes you get farther from your destination). The probability of choosing one road equals to its preferred value divide to total preferred value of all incident roads. For example, if there are three incident roads at current conjunction with preferred value 1, 2 and 3, the probability of choosing each road is 1/6, 2/6 and 3/6, respectively.


      Given the starting conjunction where your house is and the final conjunction where is your school, what is the expected number of roads you have to walk to reach the destination?


      Input
      The input begins with T – number of test cases. For each test case, there will be:
      • The first line consists of N, st, en - number of conjunctions, starting and final
      conjunction.
      • In next N - 1 lines, each line consists of three positive integers u, v and c indicate that
      there is a road between conjunction u and v with preferred value c.


      Output
      For each test case, print the expected number of roads you have to walk, round to exactly 5
      precision digits.


      Limits
      T <= 20
      1 <= N <= 15
      All numbers in input <= 100


      Sample input
      1
      3 2 3
      1 2 1
      2 3 1


      Sample output
      3.00000


      Explanation
      There are 50% chance of going 2-3 directly; 25% chance of going 2-1-2-3, 12.5% of going 2-1-
      2-1-2-3 and so on. The result equals 1 × 50% + 3 × 25% + 5 × 12.5% + … = 3


      Added by:sieunhan
      Date:2009-11-29
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Khuc Anh Tuan - ACM Vietnam Practice









      SPOJ Problem Set (classical)

      5469. Houses

      Problem code: HOUSES2

      You are given three triangle houses. Each house is presented by three points in the 2D coordination. Houses are not overlap but can share points on their border.

      You stay at point (sx, sy) and want to reach (ex, ey) by a shortest path. Your path can not intersect with a house but you can go a long a house’s border. However, you can not “go through” the walls as follow (just an example, please use natural meaning):

      You are to write a program to print the length of the shortest path.


      Input
      The input begins with T – number of test cases. For each test case:
      • The first line of each test case consists of sx, sy, ex, ey.
      • In next three lines, each line consists of 6 numbers x1, y1, x2, y2, x3, y3 denote
      coordinates of a house.


      Output
      For each test case, print the length of the shortest path with exactly 5 precision digits.


      Limits
      T <= 20
      The absolute values of coordinates are less than 1000.


      Sample input
      1
      0 0 3 0
      1 0 2 0 1 1
      2 0 2 -1 3 -1
      2 1 3 1 2 2


      Sample output
      3.65028


      Added by:sieunhan
      Date:2009-11-29
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Khuc Anh Tuan - ACM Vietnam Practice









      SPOJ Problem Set (classical)

      5511. Heavy Sequences

      Problem code: HSEQ

      Given a sequence S of N integers, indexed from 0 to N-1, we define the weight of its continuous subsequence as the product of its length and its number of occurrences in the main sequence, and in case of uniqueness, we say its weight is 0.

         Let's see an example:

         N = 5
         S = { 1, 7, 3, 1, 7 }

      The continuous subsequence S[ 0, 1 ], which is equal to { 1, 7 }, has a weight of 4, by definition. The continuous subsequence S[ 2, 2 ] thus has a weight of 0.

      Your task is to find the continuous subsequence of maximum weight. To break ties, choose the lexicographically smallest of the candidates ( a sequence A is lexicographically smaller than another sequence B if the first element at which they differ is smaller in A, or if A is a prefix of B ).

      If the maximum weight of all the continuous subsequences is 0, we say the sequence is invalid.

      Input

      The first line of input contains a single integer, N ( 1 <= N <= 105 ).
      The second line of input contains a sequence S of N integers, ( 0 <= Si <= 109 ).

      Output

      In case of an invalid subsequence, output -1.
      A continuous subsequence of the input sequence with the property defined above.

      Example

      Input:
      5
      1 7 3 1 7
       
      Output:
      1 7

      Added by:Gustav Matula
      Date:2009-12-02
      Time limit:3s-3.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:co-author: Stjepan Glavina









      SPOJ Problem Set (classical)

      5522. Buy Your House

      Problem code: PHU09H

      You are going to buy a house and hence communicated with a real estate development company, which has just started their business and you are going to be the first buyer. So they are offering you something special. The real estate company has a rectangular shaped land of width W and height H. They are using coordinate system for measuring lands. (0, 0) is the lower left corner of their land and any point which has distance x from lower edge of the land and distance y from left edge of the land is known as (x, y) in the coordinate system.

      The real estate company has already built some houses in that piece of land. All of them are
      rectangular shaped and their edges are parallel to edges of the main land. The location of a house can be addressed by four integers x1, y1, x2, y2. Where (x1, y1) is the lower left corner and (x2, y2) upper right corner of the house.


      The special offer is that you can choose any rectangular shaped region that contains
      exactly one house with any amount of adjacent open space. You may not have enough money to afford open space and choose to buy only the region that a house occupies. If you have enough money, you can keep open space in front of your house for gardening!


      But still there are some restrictions. For the ease of their future use of rest of their land
      you can only choose a rectangular shaped region and the edges of which are parallel to the edges of the main land. The corners of your selected region should be integer coordinates. It can be (3, 2) but cannot be (3.5, 2). You cannot chose a region for which part of a house is inside the region and another part of that house is outside the region. You cannot choose a region having more than one house and a region having no house. How many ways you can choose your land following the above rules?

      Input

      Input will start with an integer T (T is around 500), the number of test cases. Each of the test cases starts with two integers W and H (1 <= W, H <= 1000000000), width and height of the land and the next line contains an integer N (1 <= N <= 50), the number of houses in the land.

      Each of the next N lines will contain four integer x1, y1, x2, y2 ( 0 <= x1 < x2 <= W and
      0 <= y1 < y2 <= H ), which describes the location of the house. Note that no house can overlap with another house and all the given coordinates will be non negative integers.

      Output

      For each input, print a single line of the form “Case #: W”, where ‘#’ will be replaced by the
      case number and W will be replaced by the number of ways you can choose your land. Here W
      can be very large, so you should print the number of ways modulo 1000000007 as W.

      Example

      Input:
      2
      3 3
      1
      1 1 2 2
      10 10
      2
      1 1 4 4
      6 6 8 8

      Output:
      Case 1: 16
      Case 2: 429


      Added by:Mir Wasi Ahmed
      Date:2009-12-03
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ACM ICPC Phuket Regional 2009, Author: Md. Arifuzzaman Arif









      SPOJ Problem Set (classical)

      5523. Highway Patrol

      Problem code: PHU09K

      Crimes in city of Megacity are going high. To fight the crimes, the authorities have created a highway patrol. The city consists of a number of oneway roads. At the ends of each road, there is a base station for the patrol troops. Each base station has a number of troops. At the beginning, each station sends a troop along all the outgoing highways from that station. The troop patrols the highway and whenever it reaches the station on the other side of the highway, it waits there, and the troop that has been waiting there the most, is sent along the highway that has not been patrolled the longest time.

      Soon, they faced some difficulties, cause, the frequency of patrolling a highway is more and more dependent on the number of highways that started and ended at the base station. If the number of highways started at a base station is more than the number of highways ended there, the roads are patrolled less frequently. And if, no highways end at some base station, then, the highways started from there, will not be patrolled more than once. In this situation, the highway patrol decided to remove some highways from the patrolling schedule, so that, at each base station, the number of highways started and ended at any base station will be equal. The rest of the highways will be monitored using video surveillance. But, due to some security issues, there are some highways that have to be patrolled.


      Now, given the cost of patrolling highways, and that of installing video surveillance, find the minimum cost of monitoring the whole city. Please keep in mind that, video surveillance can not substitute the highway patrol completely. So, there has to be at least one highway that will be patrolled.

      Input

      First line of the input contains an integer T(T≤ 70), the number of test cases. This is followed by T test cases. Each test case starts with two integers N(1 ≤ N ≤ 100) and M(1 ≤ M ≤ 1000), the number of base stations and highways. This is followed by M lines, each containing 5 integers, u,v,p,s,x(1 ≤ u,v ≤ N,0 ≤ p,s ≤ 1000000) where u and v means, the highway starts from base station u, and ends at v, p is the cost of patrolling and s is the cost of installing video surveillance. If the highway must be patrolled, then x will be one. Otherwise it will be zero.

      Output

      For each test case, output the case number, followed by the minimum cost to monitor the highways. If it is not possible to patrol satisfying the given constraints, output “impossible” (without quotes).

      Example

      Input:

      2
      4 5
      1 2 10 25 0
      2 3 10 5 0
      3 1 10 5 0
      2 4 10 5 0
      4 3 30 5 0
      4 5
      1 2 10 25 0
      2 3 10 5 0
      3 1 10 5 0
      2 4 10 5 0
      4 3 30 5 1

      Output:

      Case 1: 40
      Case 2: 65

      Added by:Mir Wasi Ahmed
      Date:2009-12-03
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ACM ICPC Phuket Regional 2009 Author: Manzurur Rahman Khan









      SPOJ Problem Set (classical)

      5530. Math with Bases (Easy)

      Problem code: BSMATH1

      Little Ben had just learned different bases in math. He learned very quickly how to add and subtract in multiple bases, so his teacher provided him with a worksheet to work on. Each section provided a different base and gave an example.

      Unfortunately, Little Ben's teacher forgot to write what base each question was in! Please help Little Ben do his homework; he'll be very grateful!

      Input

      The first line of input contains an integer n (1 ≤ n < 36) that indicates the amount of sections (test cases). Each test case is as follows:

      A - B = C
      I
      X1 op Y1 =
      X2 op Y2 =
      ...
      XI op YI =

      where A - B = C is the correct example, I (1 ≤ I ≤ 1000) is the number of questions in that section, Xi and Yi are the operands of each problem (Xi = |Xi|, Yi = |Yi|), and op is either + or -, denoting addition or subtraction.


      Output

      Your program should output in the following format:

      SECTION 1 (BASE b)
      X1 op Y1 = Z1
      X2 op Y2 = Z2
      ...
      Xi op Yi = Zi
      SECTION 2 (BASE b)
      X1 op Y1 = Z1
      X2 op Y2 = Z2
      ...
      Xi op Yi = Zi
      ...
      SECTION N (BASE b)
      X1 op Y1 = Z1
      X2 op Y2 = Z2
      ...
      Xi op Yi = Zi

      where Zi is the solution to Xi op Yi, and b is the base used. (2 ≤ b ≤ 36). If the base is ambiguous, use the smallest base for which the example is correct and the questions are valid. You may assume all solutions fit inside a 64-bit integer and that each base will appear at most once.

       

      Example

      Input:

      4
      110 - 101 = 1
      2
      1111111 + 1 =
      100 - 1 =
      177 + 1 = 200
      2
      7712347 + 7 =
      11111 + 7777 =
      ZAP + DZ = ZOO
      1
      E + PI =
      10 + 1 = 11
      1
      5 + 5 =

      Output:

      SECTION 1 (BASE 2)
        1111111 + 1 = 10000000
        100 - 1 = 11
      SECTION 2 (BASE 8)
        7712347 + 7 = 7712356
        11111 + 7777 = 21110
      SECTION 3 (BASE 36)
        E + PI = PW
      SECTION 4 (BASE 6)
        5 + 5 = 14

      Notes:

      • large input/output data, be careful with certain languages
      • Tricky input/output; please read problem statement carefully

      Added by:Jargon
      Date:2009-12-04
      Time limit:0.5s-1.5s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ADA AWK C# CLOJ LISP clisp ERL F# GO HASK ICON JAR JAVA JS LUA NICE NODEJS PERL PERL 6 PHP PIKE PYTH 3.2.3 PYTH 3.2.3 n SED
      Resource:Own problem









      SPOJ Problem Set (classical)

      5531. Kutevi Hard

      Problem code: KUTH

      One day Mirko was cleaning up his room and found a straightedge and a compass. He went to the school the next day and challenged his friend Slavko to a geometric construction battle. Mirko knows how to construct some angles using the straightedge and compass and knows how to subtract and add any two angels he constructs. Slavko now shouts random angles and Mirko must draw them as fast as possible. You are observing this battle and would like to know if Mirko can construct the angles Slavko shouts at all.

      Input

      The first line of input contains two integers, N (1 ≤ N ≤ 100000), number of angles Mirko knows how to construct initially and K (1 ≤ K ≤ 100000), number of angles Slavko selected. The second line of input contains N positive real numbers with exactly 6 decimal digits, all smaller than 360, the angles Mirko knows how to construct initially. The third line contains K positive real numbers with exactly 6 decimal digits, all smaller than 360, the angles Slavko selected.

      Output

      Output consist of K lines, one for each angle Slavko selected. The i-th line should contain "YES" if Mirko can construct the i-th angle, and "NO" otherwise.

      Example

      Input:
      2 1
      30.000000 70.000000
      40.000000
      
      Output:
      YES
      
      Input:
      1 1
      100.000000
      60.000000
      
      Output:
      YES
      
      Input:
      3 2
      10.000000 20.000000 30.000000
      5.000000 70.000000
      
      Output:
      NO
      YES
      

      Added by:Stjepan Glavina
      Date:2009-12-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:based on problem "Kutevi" (COCI 09/10, #2) authored by Bruno Rahle









      SPOJ Problem Set (classical)

      5541. Sequoiadendron

      Problem code: SEQUOIA

      "Sequoiadendron giganteum (giant sequoia, Sierra redwood, or Wellingtonia) is the sole species in the genus Sequoiadendron, and one of three species of coniferous trees known as redwoods, classified in the family Cupressaceae in the subfamily Sequoioideae, together with Sequoia sempervirens (Coast Redwood) and Metasequoia glyptostroboides (Dawn Redwood). The common use of the name "sequoia" generally refers to Sequoiadendron, which occurs naturally only in the various groves that exist on the western slopes of the Sierra Nevada Mountains of California. " - Wikipedia.

      We'll slightly redefine this beautiful tree to fit our needs:

      We say our tree is infinite, and rooted in 0. We recursively define the tree as follows:

      Let x be the root of a subtree. For all i from [ 0, lg( x - dad(x) )>, we say the children of x are of the form 2i + x, where dad(x) is the index of x's parent. 0 has infinitely many childern. Odd nodes have no children.

       

      You will be given several queries, each consisting of two integers: A and B. You're asked to output the index of the lowest common ancestor of A and B. We define the lowest common ancestor of two nodes to be the node closest to A and B that lies on paths from A to 0 and from B to 0.

      Input

      The first line of input contains an integer N, the number of queries. ( 1 <= N <= 100000 )

      The next N lines contain a pair of integers, A and B. ( 0 <= A, B <= 1018 )

      Output

      You are asked to output N lines, where the i-th line corresponds to the answer to the i-th query.

      Example

      Input:
      2
      15 13
      11 7
      Output: 12
      0

      Added by:Gustav Matula
      Date:2009-12-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      5542. Counting pairs

      Problem code: CPAIR


      You're given a sequence A of N non-negative integers. Answer Q queries, where each query consists of three integers: v, a, b. The answer is number of pairs of integers i and j that satisfy these conditions:

      1 <= i <= j <= N

      a <= j-i+1 <= b

      A[k] >= v for every integer k between i and j, inclusive

      Constraints

      1 <= N <= 100 000

      1 <= Q <= 100 000

      0 <= A[k] <= 1000, for every integer k between 1 and N, inclusive

      0 <= v <= 1000

      1 <= a <= 100 000

      1 <= b <= 100 000

      Input

      The first line of input contains two integers, N and Q. The second line contains the sequence A, consisting of N integers. Each of the next Q lines contains three numbers, v, a and b, defining a query.

      Output

      In the i-th line output only one integer denoting the answer to the i-th query.

      Example

      Input:
      5 3
      5 3 2 7 4
      3 2 3
      2 2 5
      4 1 1
      
      Output:
      2
      10
      3
      

      Added by:Stjepan Glavina
      Date:2009-12-05
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      5566. Math with Bases

      Problem code: BSMATH2

      With your previous help, Little Ben managed to get a perfect score on his homework. He came running home to show his brother, Big Ben. Big Ben had done this type of thing before, you see, so he naturally wasn't too impressed. Big Ben boasted, "Back in my day, we had to multiply and divide as well, the numbers were much bigger, AND we had to do it in base 64."

      Little Ben became intrigued by this and searched the Internet for a worksheet. It turns out that his teacher made a worksheet for one of the higher grades that was just like Big Ben's. She also forgot to write what base each question was in... again!

      According to the worksheet,

      The digits used for Base 64 are the same as that of Base 62, with the single- and double-quotes as the last two; the digits used are 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'".

      Input

      The first line of input contains an integer n (1 < n < 64) that indicates the amount of sections (test cases). Each test case is as follows:

      A - B = C
      I
      X1 op Y1 =
      X2 op Y2 =
      ...
      XI op YI =

      where A - B = C is the correct example, I (1 ≤ I ≤ 5000) is the number of questions in that section, Xi and Yi are the operands of each problem (0 < X, Y ≤ 2100), and op is one of
      [+, -, *, %], denoting addition, subtraction, multiplication, or modulo.


      Output

      Your program should output in the following format:

      SECTION 1 (BASE b)
      X1 op Y1 = Z1
      X2 op Y2 = Z2
      ...
      Xi op Yi = Zi
      SECTION 2 (BASE b)
      X1 op Y1 = Z1
      X2 op Y2 = Z2
      ...
      Xi op Yi = Zi
      ...
      SECTION N (BASE b)
      X1 op Y1 = Z1
      X2 op Y2 = Z2
      ...
      Xi op Yi = Zi

      where Zi is the solution to Xi op Yi, and b is the base used. (2 ≤ b ≤ 64). If the base is ambiguous, use the smallest base for which the example is correct and the questions are valid.

      Example

      Input:

      4
      K72Q - 9C5U = APRR
      3
      11JH4 - BMEB =
      PB04 % DQ9O =
      F0GM - UQR0 =
      A654A - 9A60E = AE3B
      2
      B94BA + 3460A =
      123A29 % 5E065 =
      37CR - olh = 2KSm
      5
      157W % 1bIJ =
      1P56 % 1Eob =
      1C6I * 1"uX =
      1Ktc % 1BMf =
      20ne * 22V" =
      BQfC - 4Kdb = 761H
      2
      9aFL * 3WU3 =
      5fcV + 7fWL =

      Output:

      SECTION 1 (BASE 31)
        11JH4 - BMEB = KS2O
        PB04 % DQ9O = BFLB
        F0GM - UQR0 = -FQA9
      SECTION 2 (BASE 15)
        B94BA + 3460A = EDAC5
        123A29 % 5E065 = 5594E
      SECTION 3 (BASE 64)
        157W % 1bIJ = 157W
        1P56 % 1Eob = AIX
        1C6I * 1"uX = 2O3gS"I
        1Ktc % 1BMf = 9Wz
        20ne * 22V" = 46bA3EO
      SECTION 4 (BASE 42)
        9aFL * 3WU3 = bBafS4L
        5fcV + 7fWL = DfTA

      Notes: large input/output data


      Added by:Jargon
      Date:2009-12-10
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own problem









      SPOJ Problem Set (classical)

      5609. Knight Moves

      Problem code: KMOVES

      A knight is located at the (black) origin of an infinite chessboard. Let f(n) define the number of black squares the knight can reach after making exactly n moves. Given n (0 <= n <= 108), output f(n).

      Input

      The first line of the input contains a single integer T, the number of test cases (1 <= T <= 106). Each test case consists of a single positive integer n.

      Output

      For each value of n in the input, print a single line containing.

      Example

      Input:
      2
      0
      1

      Output:
      1
      0

      Added by:Amlesh Jayakumar
      Date:2009-12-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:Own









      SPOJ Problem Set (classical)

      5637. LL and ErBao

      Problem code: ISUN1

      When LL and ErBao were young, they liked jumping rubber-rope (Tiao Pi Jin) very much. They jumped every day happily. But one day HH came and brought away the peaceful days. HH sometimes threw stones to them, and sometimes pushed them down suddenly. Seeing ErBao crying sadly, LL got angry finally, and decided to give HH some color see see.
      There were n trees on the ground (regarded as points), and LL planed to use his rubber-rope to wrap all the trees and form a big circle, then fooled HH into it and threw stones to him. Before finding out how to fool HH into the circle, LL wants to know how big the rubber-rope circle would be, say, the perimeter.
      But LL found it difficult than expected, because their playing territory and the trees were in a bigger fence (a simple polygon with m vertices). So, the rubber-rope mustn’t be out of the fence either. It’s your turn to help LL find the perimeter of the circle.

       

      sample 1

       

      sample 2

       

       

      Input

      The input contains multiple cases terminated with EOF.
      For each case, first line contains two integers: m, n.
      (3 <= m <= 500, 0 <= n <= 500)
      Next m lines each contain two integers: Xfi, Yfi ----coordinate of the fence’s ith vertex, in Counterclockwise order.
      Next n lines each contain two integers: Xti, Yti ----coordinate of the ith tree.
      It’s guaranteed that all trees were strictly in the fence, and the fence doesn’t intersect or touch itself.
      The absolute value of the coordinates doesn’t exceed 10000.

      Output

      For each case output the perimeter of the rubber-band with three digits after the dot.

      Example

      Input:
      8 2
      0 0
      30 0
      30 20
      20 20
      20 10
      10 10
      10 20
      0 20
      5 15
      25 15

      12 5
      5 5
      5 20
      -5 20
      -5 5
      -20 5
      -20 -5
      -5 -5
      -5 -20
      5 -20
      5 -5
      20 -5
      20 5
      0 0
      0 17
      0 -17
      17 0
      -17 0

      Output:
      Case #1: 48.284
      Case #2: 104.000


      Added by:3xian
      Date:2009-12-19
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Xu Han, HUST Campus 2009









      SPOJ Problem Set (classical)

      5638. Mobile Service Hard

      Problem code: SERVICEH

      A company provides service for its partners that are located in different towns. The company has three mobile service staff employees. If a request occurs at some location, an employee of the service staff must move from his current location to the location of the request (if no employee is there) in order to satisfy the request. Only one employee can move at any moment. They can move only on request and are not allowed to be at the same location. Moving an employee from location p to location q incurs a given cost C(p,q). The cost function is not necessarily symmetric, but the cost of not moving is 0, i.e. C(p,p)=0. The company must satisfy the received requests in a strict first-come, first-serve basis. The goal is to minimize the total cost of serving a given sequence of requests.

      Task

      You are to write a program that decides which employee of the service staff is to move for each request such that the total cost of serving the given sequence of requests is as small as possible.

      Input

      The first line contains two integers, L and N. L (3 <= L <= 300) is the number of locations and N (1 <= N <= 3000) is the number of requests. Locations are identified by the integers from 1 to L. Each of the next L lines contains L non-negative integers. The jth number in the line i+1 is the cost C(i,j), and it is less than 2001.

      The last line contains N integers, the list of the requests. A request is identified by the identifier of the location where the request occurs. Initially, the three service staff employees are located at location 1, 2 and 3, respectively.

      Output

      The first line contains one integer, M, the minimal total cost of serving the input sequence of the requests. The second line contains exactly N integers. The ith number is the identifier of the service staff employee (1, 2 or 3) who will serve the ith request. If there are multiple possibilities, your program should output one sequence only; it does not matter which one.

      Example

      Input:
      5 9
      0 1 1 1 1
      1 0 2 3 2
      1 1 0 4 1
      2 1 5 0 1
      4 2 3 4 0
      4 2 4 1 5 4 3 2 1

      Output:
      5
      1 2 1 2 2 1 3 1 3

      Added by:Frane Kurtoviæ
      Date:2009-12-19
      Time limit:1s-75s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:CEOI 2005, Day 1









      SPOJ Problem Set ()

      5640. Fractions on Tree

      Problem code: NG0FRCTN


      A fraction tree is an infinite binary tree  defined as follows:

      1)Every node of tree contains a fraction

      2)Root of tree contains the fraction 1/1

      3)Any node with fraction i/j has two children : left child with fraction i/(i+j) and right child with fraction (i+j)/j           

      For example , fraction tree upto 3 levels is as shown:

      Fraction tree upto 3 levels

      We number the nodes according to increasing levels ( root is at level 1) and at any same level , nodes are numbered from left to right. So first node holds the fraction 1/1 , second one holds 1/2 , third one holds 2/1 fourth one holds 1/3 and so on.


      Your task is simple. Given a number n , you are to find the fraction at the nth node.

       

      Input

      Every line of the input contains a single number n. You are to find the fraction at nth node of fraction tree. Input file terminates with a 0 which is not to be processed.

       

      Output

      For each input , print numerator and denominator of the lowest form of the fraction seperated by a /. Output of each case to be done in seperate lines.

      Example

      Input:
      1
      2
      3
      7
      0

      Output:
      1/1
      1/2
      2/1
      3/1

      Constraints : 1<= # of test cases <=30000 1<=N<=10^10
      1
      1
      uQs
      +
      Q
      Q
      Q
      Q
      Q
      Q
      Q
      Q
      Q
      
      
      
      
      
      
      
      
      1 
      2 u
      e
      e
      e
      e
      e
      e
      %
      %
      %
      %
      %
      %
      2
      u1
      e
      e
      e
      e
      e
      e
      %
      %
      %
      %
      %
      1 %
      3
      u
      A
      A
      A
      A
      A
      A
      
      
      
      
      
      
      3
      2
      uA
      A
      A
      A
      A
      A
      
      
      
      
      
      
      2
      3
      uA
      A
      A
      A
      A
      A
      
      
      
      
      
      
      3
      1
      uA
      A
      A
      A
      A
      A
      
      
      
      
      
      1 
      4
      uA
      A
      
      
      4
      3
      uA
      A
      
      
      3
      5
      uA
      A
      
      
      5
      2
      uA
      A
      
      
      2
      5
      uA
      A
      
      
      5
      3
      uA
      A
      
      
      3
      4
      uA
      A
      
      
      4
      1
      uA

      Added by:Nikhil Garg
      Date:2009-12-19
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:own









      SPOJ Problem Set (main)

      5649. Divide Polygon

      Problem code: DTPOLY

      Determine the number of ways to cut a convex polygon with N sides if the only cuts allowed are from vertex to vertex, each cut divides exactly one polygon into exactly two polygons, and you must end up with exactly K polygons. Consider each vertex distinct. For example, there are three ways to cut a square - the two diagonals and not cutting at all - but only two ways to cut it to form 2 polygons, and only one way to cut it to form 1 polygon. The order of cuts does not matter. Since the number of ways is very large, you should return the number taken modulo 1000000000 (one billion). If there is no way to cut the polygon into K pieces, return -1.    

      Input

      • Input contains only 2 integers in one line: N (1 ≤ N ≤ 100) and K (1 ≤ K ≤ 100).

      Output

      • Output contains only one integer, the number of different ways to cut the polygon into K pieces.

      Example

      Input:
      4 2

      Output:
      2

      Added by:Nguyễn Xuân Khánh
      Date:2009-12-21
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C++ 4.3.2 PAS fpc









      SPOJ Problem Set (main)

      5652. Snow White and the N dwarfs

      Problem code: PATULJCI

      Snow White and the N dwarfs live in the forest. While the dwarfs mine away Snow White hangs around social networks.

      Each morning the dwarfs form a long line and go whistling away to the mine. Snow White runs around them and snaps pictures to upload onto her favorite social network.

      When dwarfs enter the mine, Snow White goes back to their house and goes through the pictures, selecting pretty ones. Each dwarf has a colored cap, and there are C different colors. A picture is pretty if more than half caps on it are of the same color. In other words, if there are K dwarfs on the picture, it is pretty if strictly more than K / 2 dwarfs have same colored caps.

      Write a program that will check for a set of M pictures if they are pretty, and what color is dominating if they are.

      Input

      First line contains two integers N and C (3 ≤ N ≤ 300000, 1 ≤ C ≤ 100000) number of dwarfs and number of colors.

      Second line contains N integers between 1 and C (inclusive), colors of dwarves hats, ordered the way they formed the line that morning.

      Third line contains M (1 ≤ M ≤ 100000), number of pictures.

      Next M lines contain two integers A and B (1 ≤ A ≤ B ≤ N). Each line describes one picture. On it there are all dwarves starting from A-th all the way to the B-th.

      Output

      Output M lines. For each picture output “no” if Snow White doesn't think the picture is pretty, and “yes X”, where X is the color dominating on the picture, if she does.

      Example

      Input:
      10 3
      1 2 1 2 1 2 3 2 3 3
      8
      1 2
      1 3
      1 4
      1 5
      2 5
      2 6
      6 9
      7 10
      
      Output:
      no
      yes 1
      no
      yes 1
      no
      yes 2
      no
      yes 3
      

      Added by:Luka Kalinovcic
      Date:2009-12-21
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:COCI 2009/2010 Contest #3









      SPOJ Problem Set ()

      5673. Fractions on Tree ( reloaded !)

      Problem code: NG1FRCTN

      A fraction tree is an infinite binary tree  defined as follows:

      1)Every node of tree contains a fraction

      2)Root of tree contains the fraction 1/1

      3)Any node with fraction i/j has two children : left child with fraction i/(i+j) and right child with fraction (i+j)/j           

      For example , fraction tree upto 3 levels is as shown:

      Fraction tree upto 3 levels

      We number the nodes according to increasing levels ( root is at level 1) and at any same level , nodes are numbered from left to right. So first node holds the fraction 1/1 , second one holds 1/2 , third one holds 2/1 fourth one holds 1/3 and so on.


      Your task is simple, as always !. Given two numbers a and b , you are to find the product of  fractions at all those nodes whose number is between a and b both inclusive.

       

      Input

      Every line of the input contains two  numbers a and b seperated by a space. You are to find the product of all fractions which are at node having number between a and b both inclusive. Input file terminates with a 0 0 which is not to be processed.

       

      Output

      For each input , print numerator and denominator of the lowest form of the fraction seperated by a /. Output of each case to be done in seperate lines.

      Example

      Input:
      1 1
      1 2
      2 4
      0 0

      Output:
      1/1
      1/2
      1/3

      Constraints : 1<=T <=30000 1<=a<=b<=10^10
      1
      1
      uQs
      +
      Q
      Q
      Q
      Q
      Q
      Q
      Q
      Q
      Q
      
      
      
      
      
      
      
      
      1 
      2 u
      e
      e
      e
      e
      e
      e
      %
      %
      %
      %
      %
      %
      2
      u1
      e
      e
      e
      e
      e
      e
      %
      %
      %
      %
      %
      1 %
      3
      u
      A
      A
      A
      A
      A
      A
      
      
      
      
      
      
      3
      2
      uA
      A
      A
      A
      A
      A
      
      
      
      
      
      
      2
      3
      uA
      A
      A
      A
      A
      A
      
      
      
      
      
      
      3
      1
      uA
      A
      A
      A
      A
      A
      
      
      
      
      
      1 
      4
      uA
      A
      
      
      4
      3
      uA
      A
      
      
      3
      5
      uA
      A
      
      
      5
      2
      uA
      A
      
      
      2
      5
      uA
      A
      
      
      5
      3
      uA
      A
      
      
      3
      4
      uA
      A
      
      
      4
      1
      uA

      Added by:Nikhil Garg
      Date:2009-12-24
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own









      SPOJ Problem Set (main)

      5699. The last digit re-visited

      Problem code: LASTDIG2

      Pappu was doing the work of his math class about three days but he is tired of make operations a lot and he should deliver his task tomorrow. His math’s teacher gives two numbers a and b. The problem consist in find the last digit of the potency of base a and index b. Help Pappu with his problem. You are given two integer numbers: the base a (number of digits d, such that 1<=d<=1000) and the index b (0 <= b <= 922*10^15). You
      have to find the last digit of a^b.

                                                               Input
      The first line of input contains an integer t, the number of test cases (t <= 30). t test cases follow. For
      each test case will appear a and b separated by space.

                                                               Output
      For each test case output an integer per line representing the result.

      Example
      Input:
      3
      3 10
      6 2
      150 53
      Output:
      9
      6
      0


      Added by:Hari
      Date:2009-12-27
      Time limit:1s
      Source limit:700B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:harrydcoder









      SPOJ Problem Set (classical)

      5703. Primes of Lambda

      Problem code: LPRIME

      Lambda checks primality in a weird way. He checks the following two conditions.

      • All the digits of the number in the decimal system are primes or one, namely 1, 2, 3, 5 or 7.
      • It isn't a multiple of 2, 3, 5, 7, 11 or 47 (Why 47? I don't know).

      In order to estimate the accuracy of his approach, he asks you to calculate the number of decimal integers of a specific length that satisfy the conditions.

      Input

      The first and only line contains an integer n, denoting the length of integers.

      Output

      The only line contains the answer modulo 9973.

      Example

      Input:
      1

      Output:
      1

      Input:
      2

      Output:
      8

      Input:
      4

      Output:
      182

      Input:
      1000000000

      Output:
      4589

      Constraints

      1 <= n <= 109
      In 50% of testcases, n <= 100

      Note: Data corrected and solutions rejudged. Sorry for inconvenience.

      Warning: A naive solution won't terminate in 30s. And be careful with certain languages.


      Added by:Lox
      Date:2009-12-28
      Time limit:1s-13s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own problem









      SPOJ Problem Set (classical)

      5725. 123 Sequence

      Problem code: KSEQ

      A 123 sequence is defined as a non-decreasing sequence of length>=2, where each number is 1 or 2 or 3. The difference between all unique pairs of numbers is given i.e. for a 123 sequence a1, a2, a3, ..., an the differences are aj-ai for 1<=i<j<=n.

      Since the 123 seq contains only 1, 2, 3 the difference between any pair can be 0, 1, 2. Given the number of 0s, 1s, 2s in the difference sequence X, Y, Z respectively, your task is to find the number of distinct 123 sequences that could result in X, Y, Z.

      Two 123 sequences A and B are considered different if there exists atleast one i such that Ai is not equal to Bi.

      Input

      First line of the input contains the number of test cases T. T<=10000. Then follow T lines each containing 3 space separated integer X, Y, Z. 0<=X,Y,Z,<=108. X+Y+Z>0.

      Output

      For each test case output the number of distinct 123 sequences in a separate line.

      Example

      Input:
      3
      0 2 1
      1 2 3
      1 3 2

      Output:
      1
      0
      2

      Explanation

      For the third test case the 123 sequences are 1, 2, 3, 3 and 1, 1, 2, 3.


      Added by:arun
      Date:2010-01-02
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Kurukshetra OPC 2010









      SPOJ Problem Set (classical)

      5732. Paradox

      Problem code: PARADOX

      A paradox is a statement or group of statements that leads to a contradiction. Consider the following two statements.

                "The statement below is false."
                "The statement above is true."

      If we assume that 1st statement is true then according to 1st statement the 2nd statement is false. Since the 2nd statement is false and it says that 1st statement is true, 1st statement must be false which is a contradiction. If we assume that 1st statement is false then the 2nd statement must be true (since 1st statement says 2nd statement is false). Then according to 2nd statement 1st statement must be true which is a contradiction. Thus the statement cannot be classified as true or false. This is a paradox.

      Given N statements of the form "Statement X is true/false", 1<=X<=N, your task is to find if these set of statements are paradoxical or not. A set of statements is paradoxical if one or more statements cannot be classified as true or false.

      Input

      Multiple test cases. Each test cases begins with an integer N representing the number of statements. 1<=N<=100. Then follow N lines, representing N statements in the order 1,2,3, ...,N. Each line contains an integer X and a string S separated by a space. 1<=X<=N. S is either "true" or "false" (quotes for clarity), which means the statement is "Statement X is S". N=0 indicates the end of testcases and should not be processed. There are atmost 10000 testcases.

      Output

      For each test case print "PARADOX" if the set of statements are paradoxical, else print "NOT PARADOX", in a separate line.

      Example

      Input:
      2
      2 false
      1 true
      2
      2 false
      1 false
      0

      Output:
      PARADOX
      NOT PARADOX

      Added by:arun
      Date:2010-01-03
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Kurukshetra OPC 2010









      SPOJ Problem Set (classical)

      5830. Alternating Permutations

      Problem code: ALTPERM

      You are given K indices, A[1], A[2], ... , A[K].

      A[1] < A[2] < ... < A[K].

      A[1] = 1 and A[K] = N.

      A permutation of the numbers between 1 and N is called valid if :

      The numbers in the permutation between indices A[1] and A[2] (inclusive) form an increasing sequence, the numbers in the permutation between indices A[2] and A[3] (inclusive) form a decreasing sequence, those between A[3] and A[4] (inclusive) form an increasing sequence and so on.

      Count the number of valid permutations.

      Input

      There will be multiple test cases. The first line contains the number of test cases T.

      There follow 2*T lines, 2 lines for each test case. The first line for each test case contains the numbers N and K. The second line contains K space seperated numbers, ie. A[1] to A[K].

       

      Output

      Output T lines, one for each test case. All answers should be output MOD 1000000007.

      Example

      Sample Input :
      3 3 3 1 2 3 4 3 1 3 4 10 6 1 2 5 7 8 10

      Sample Output : 2 3 6166


      Constraints

      T <= 111 2 <= N <= 20000 2 <= K <= 22

      K <= N

      A[1] < A[2] < ... < A[K]. A[1] = 1 and A[K] = N.


      Added by:Varun Jalan
      Date:2010-01-10
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own Problem, used for Codechef Snackdown http://www.codechef.com/









      SPOJ Problem Set ()

      5831. Permutation Jumping

      Problem code: PERMJUMP

      John likes playing the game Permutation Jumping. First he writes down a permutation A of the first n numbers. Then, he chooses any cell to start on. If he is currently at cell x and hasnt visited the cell A[x], he jumps to cell A[x]. He keeps doing this till he cannot move to the cell A[x], because he has already visited it. In the end, he counts all the cells that he visited during the game, including the cell on which he started.
       
      He does not want the game to go on for too long, and thus he wishes that irrespective of the choice of his starting cell, he does not ever have to visit more than K cells. On the other hand, he does not want the game to be too short either. Thus, irrespective of the choice of his starting cell, he should be able to visit atleast two cells.
       
      Now he wonders how many permutations could he have chosen in the first place which would allow him to have the game duration as above. i.e. He should visit atleast 2 cells and atmost K cells, no matter which cell he started on.


       
       
      Input


      The first line contains the number of test cases T (T <= 1000). The next T lines contain 2 space seperated integers N and K. (2 <= K <= N <= 100)


      Output

      Output T lines, one corresponding to each test case. For each test case output a single integer which is the answer for the corresponding test case. Since the answer can be very large, output the answer modulo 1000000007.


      Example


      Sample Input :
      2
      4 2
      6 4
       
      Sample Output :
      3
      145
       
      Note :
      For the first case, the valid permutations are {2 1 4 3}, {3 4 1 2} and {4 3 2 1}.


      Added by:Varun Jalan
      Date:2010-01-10
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own Problem, used for Codechef Snackdown http://www.codechef.com/









      SPOJ Problem Set (classical)

      5832. AND Rounds

      Problem code: ANDROUND

      You are given a cyclic array A having N numbers. In an AND round, each element of the array A is replaced by the bitwise AND of itself, the previous element, and the next element in the array. All operations take place simultaneously. Can you calculate A after K such AND rounds ?


      Input


      The first line contains the number of test cases T (T <= 50).
      There follow 2T lines, 2 per test case. The first line contains two space seperated integers N (3 <= N <= 20000) and K (1 <= K <= 1000000000). The next line contains N space seperated integers Ai (0 <= Ai <= 1000000000), which are the initial values of the elements in array A.  


       
      Output


      Output T lines, one per test case. For each test case, output a space seperated list of N integers, specifying the contents of array A after K AND rounds.


       Example


      Sample Input :
      2
      3 1
      1 2 3
      5 100
      1 11 111 1111 11111
       
      Sample Output :
      0 0 0
      1 1 1 1 1


      Added by:Varun Jalan
      Date:2010-01-11
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own Problem, used for Codechef Snackdown http://www.codechef.com/









      SPOJ Problem Set (classical)

      5833. XOR Rounds

      Problem code: XORROUND

      You are given a cyclic array A having N numbers. In an XOR round, each element of the array A is replaced by the bitwise XOR (Exclusive OR) of itself, the previous element, and the next element in the array. All operations take place simultaneously. Can you calculate A after K such XOR rounds ?

       
      Input


      The first line contains the number of test cases T (T <= 50).
      There follow 2T lines, 2 per test case. The first line contains two space seperated integers N (3 <= N <= 500) and K (1 <= K <= 1000000000). The next line contains N space seperated integers Ai (0 <= Ai <= 1000000000), which are the initial values of the elements in array A.  
       

      Output


      Output T lines, one per test case. For each test case, output a space seperated list of N integers, specifying the contents of array A after K XOR rounds.

      Example


      Sample Input :
      2
      3 1
      1 2 3
      5 100
      1 11 111 1111 11111
       
      Sample Output :
      0 0 0
      11117 101 1075 12127 12081


      Added by:Varun Jalan
      Date:2010-01-11
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own Problem, used for Codechef Snackdown http://www.codechef.com/









      SPOJ Problem Set (classical)

      5885. Troops of Sand Monsters

      Problem code: TROOPS

      Under the command of the Evil Vizier there are N unique troops of sand monsters, where each  troop contains Ci sand monsters. The Vizier in his desperate battle against the Prince of Persia has ordered all his troops to attack him simultaneously.
       
      The Prince realizes that he cannot defeat all of the sand monsters, as they are invincible  when they are active. So he uses the Eye of the Storm spell to freeze all the sand monsters of all troops. Now the Prince can kill any monster by stabbing each monster once using the Dagger of Time. Once the monster is killed, it can never become active again and releases a certain quantity of the Sands of Time. It takes one unit of time to kill any monster.
       
      Each troop i, consits of Ci similar monsters, all with the same spell resistance time Ti - after which it becomes active again and therefore invulnerable - and Sand Si - which can be taken by the Prince after killing it.
       
      The spell lasts only for a limited duration of time. So, the Prince has to kill as many sand monsters as possible and take maximum sand from the monsters before they become active again. It is not necessary for The Prince to kill all the monsters in a troop before moving on to next troop.

      Input

      The first line contains K <=70  the number of testcases. Each testcase begins with 'N' (<=1000) the number of troops of monsters. Next N lines contain 3 integers Ci, Ti, Si. 1<i<=N,  1<=Ci<=15000, 1<=Ti<=1000000, 1<=Si<=100,

      Output

      Single Line containing the maximum amount of sand that Prince can get if he kills some or all the monsters.

      Example

      Input:
      1
      4
      2 1 2
      2 3 6
      2 5 5
      2 7 8

      Output:
      40

      Explanation

      (time, troop, sand)
      (0,1,2) (1,2,6) (2,2,6) (3,3,5) (4,3,5) (5,4,8) (5,4,8) = 40

       



      Added by:arun
      Date:2010-01-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Kurukshetra OPC 2010









      SPOJ Problem Set (classical)

      5902. Tri

      Problem code: CEOI09TR

      Task

      You are given K points with positive integer coordinates. You are also given M triangles, each of them having one vertex in the origin and the other 2 vertices with non-negative integer coordinates.

      You are asked to determine for each triangle whether it has at least one of the K given points inside. (None of the K points are on any edge of any triangle.)

      Input

      The first line of the input file will contain K and M. The following K lines will contain 2 positive integers x y separated by one space that represent the coordinates of each point. The next M lines have 4 non-negative integers separated by one space, (x1, y1) and (x2, y2), that represent the other 2 vertices of each triangle, except the origin.

      Output

      The output file should contain exactly M lines. The k-th line should contain the character Y if the k-th triangle (in the order of the input file) contains at least one point inside it, or N otherwise.

      Constraints

      • 1 ≤ K,M ≤ 100 000
      • 1 ≤ each coordinate of the K points ≤ 109
      • 0 ≤ each coordinate of the triangle vertices ≤ 109
      • Triangles are not degenerate (they all have nonzero area).
      • In 50% of the test cases, all triangles have vertices with coordinates x1=0 and
        y2=0. That is, one edge of the triangle is on the x-axis, and another is on the y-axis.

      Sample input 1

      4 3
      1 2
      1 3
      5 1
      5 3
      1 4 3 3
      2 2 4 1
      4 4 6 3

      Sample output 1

      Y
      N
      Y

      Explanation for sample 1

      Explanation for sample 1

      Sample input 2

      4 2
      1 2
      1 3
      5 1
      4 3
      0 2 1 0
      0 3 5 0

      Sample output 2

      N
      Y

      Explanation for sample 2

      Explanation for sample 2


      CEOI 2009 - Tîrgu Mureº, Romania

      Added by:Andrés Mejía-Posada
      Date:2010-01-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:CEOI 2009 - Tîrgu Mureº, Romania









      SPOJ Problem Set (classical)

      5911. Square-free Integers Factorization

      Problem code: SQFFACT

      Given the positive integers N = p1 * p2 * ... * pk and M = (p1-1) * (p2-1) * ... * (pk-1), i.e M = φ(N) (Euler's totient function), where k ≥ 1, pi ≠ pj for all i≠j with i,j=1,2, ..., k and pi is prime number for all i=1,2,...,k, your task is factor n.

      Input

      The first line contains a positive integer T, the number of test cases, where T ≤ 100. The following T lines each contains two numbers N and M in this order, where N < 10100.

      Output

      Output T lines, with prime factorization of N according with example.

      Example

      Input:
      3
      210 48
      983 982
      14351 14112
      
      Output:
      210 = 2 * 3 * 5 * 7
      983 = 983
      14351 = 113 * 127
      
      

      Added by:Paulo Roberto Santos de Sousa
      Date:2010-01-18
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:AWK C C++ 4.3.2 C++ 4.0.0-8 C99 strict JAVA NODEJS PAS fpc PAS gpc PYTH 3.2.3 n SED
      Resource:Own problem









      SPOJ Problem Set (classical)

      5917. Factorial length

      Problem code: LENGFACT

      Given integer n, print length of n! (which is factorial of n).

      Input

      The first line of the standard input contains one integer t (t<10001) which is the number of test cases.

      In each of the next t lines there is number n (0<=n<=5*10^9).

      Output

      For each test, print the length of n! (which is factorial of n).

      Example

      Input:
      3
      1
      10
      100
      Output:
      1
      7
      158

      Added by:Piotr K±kol
      Date:2010-01-19
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Copy of the problem: FACTLENG with different assessment









      SPOJ Problem Set (classical)

      5969. Finding Maximum

      Problem code: FINDMAX

      One way of finding the maximum element in an array is to initialize a variable to the first element in the array, iterate through the remaining array, and update the variable whenever a value strictly greater than it is found. Assuming that the array contains N elements each in the range 1..K, how many such arrays exist such that the above algorithm performs exactly P updates? Initialization of the variable is not counted as an update.

      For example,the possible arrays for N = 4,K = 3 and P = 2 are
      1) {1,1,2,3}
      2) {1,2,1,3}
      3) {1,2,2,3}
      4) {1,2,3,1}
      5) {1,2,3,2}
      6) {1,2,3,3}


      Input


      The first line contains T the number of test cases. There follow T lines, containing 3 space seperated integers N,K and P.


      Output

      Output T lines, one for each test case. On each line, output the answer as asked above. Since the answers can get very big, output the answer modulo 1000000007.

      Example

      Sample Input :
      3
      4 3 2
      2 3 1
      3 4 1

      Sample Output :
      6
      3
      30


      Constraints


      1 <= T <= 100
      1 <= n <= 100
      1 <= K <= 300
      0 <= P < n


      Added by:Varun Jalan
      Date:2010-01-24
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem used for Codechef Snackdown Onsite









      SPOJ Problem Set (main)

      5970. Finding Primes

      Problem code: FINDPRM

      One commonly used method to calculate all primes in the range [2..n] is to start with the number 2, mark it as prime, and mark all its multiples (excluding itself) as not prime. Then, we find the next smallest unmarked number, mark it as prime, and mark all its multiples (excluding itself) as not prime. Continuing this way, we get a list of all primes.

      Now, let us say that we modified the above algorithm, and start with n instead of 2. We mark it as prime, and mark all its factors (excluding itself) as not prime. Then we find the next greatest unmarked number, mark it as prime, and mark all its factors (excluding itself) as not prime. Continuing this way, we get a list of all primes.

      Now you wonder, given a value of n, how many numbers are such that both the above algorithms will mark them as prime?


      Input


      The first line contains T the number of test cases. Each of the next T lines contain an integer n.


      Output

      Output T lines, one for each test case, containing the required answer.

      Example

      Sample Input :
      3
      2
      4
      7

      Sample Output :
      1
      1
      2

      Constraints

      1 <= T <= 100000
      2 <= n <= 10000000


      Added by:Varun Jalan
      Date:2010-01-24
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:own problem used for Codechef Snackdown Onsite









      SPOJ Problem Set (classical)

      5971. LCM Sum

      Problem code: LCMSUM

      Given n, calculate the sum LCM(1,n) + LCM(2,n) + .. + LCM(n,n), where LCM(i,n) denotes the Least Common Multiple of the integers i and n.

      Input


      The first line contains T the number of test cases. Each of the next T lines contain an integer n.


      Output


      Output T lines, one for each test case, containing the required sum.

      Example

      Sample Input :
      3
      1
      2
      5

      Sample Output :
      1
      4
      55


      Constraints

      1 <= T <= 300000
      1 <= n <= 1000000


      Added by:Varun Jalan
      Date:2010-01-24
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:own problem used for Codechef Snackdown Onsite









      SPOJ Problem Set ()

      5972. Maximum Sum Sequences

      Problem code: MAXSUMSQ

      Given an array A having n elements, let X be the maximum sum of any contiguous sequence in the array. How many contiguous sequences in A sum up to X ?



      Input

      The first line contains T the number of test cases. There follow 2T lines, 2 for each test case. The first line contains the n, the number of elements in the array. The second line contains n space seperated integers Ai.


      Output


      Output T lines, one for each test case. On each line, output two space seperated integers; the maximum sequence sum, and the number of sequences which obtain this maximum sum.

      Example

      Sample Input :
      2
      3
      -1 -1 -1
      4
      2 0 -2 2

      Sample Output :
      -1 3
      2 4


      Constraints


      1 <= T <= 35
      1 <= n <= 100000
      -1000 <= Ai <= 1000


      Added by:Varun Jalan
      Date:2010-01-24
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem used for Codechef Snackdown Onsite









      SPOJ Problem Set ()

      5973. Selecting Teams

      Problem code: SELTEAM

      There are n players out of which atmost k players are chosen to form the team squad. Out of those players, some subset of them are selected to form a team, and a player of the selected team is appointed as the captain of the team. Given n and k, determine how many possible configurations exist. Two configurations differ if either the players in the team squad differ, or if the number of players in the team differ, or the players in the team differ, or if the captain differs.

      For example,the possible configurations for n = 2 and k = 2 are :
      1) Team squad : {1}, Team : {1}, Captain : 1
      2) Team squad : {2}, Team : {2}, Captain : 2
      3) Team squad : {1,2}, Team : {1}, Captain : 1
      4) Team squad : {1,2}, Team : {2}, Captain : 2
      5) Team squad : {1,2}, Team : {1,2}, Captain : 1
      6) Team squad : {1,2}, Team : {1,2}, Captain : 2

      Input


      The first line contains T the number of test cases. Each of the next T lines contain 2 integers : n,k


      Output

      Output T lines, one for each test case, containing the required total number of configurations. Since the answers can get very big, output the answer modulo 8388608.

      Example


      Sample Input :
      3
      2 2
      7 1
      5 3

      Sample Output :
      6
      7
      165


      Constraints

      1 <= T <= 10000
      1 <= k <= n <= 100000


      Added by:Varun Jalan
      Date:2010-01-24
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:own problem used for Codechef Snackdown Onsite









      SPOJ Problem Set (classical)

      5975. Travelling Knight

      Problem code: TRKNIGHT

      Your task is simple. A knight is placed on the top left corner of a chessboard having 2n rows and 2n columns. In how many ways can it move such that it ends up at a corner after atmost K moves ?

      Input


      The first line contains T the number of test cases. Each of the next T lines contain 2 integers : n,k


      Output

      Output T lines, one for each test case, containing the required total number of configurations. Since the answers can get very big, output the answer modulo 1000007.

      Example

      Sample Input :
      3
      2 1
      2 2
      3 3

      Sample Output :
      1
      5
      7

      Constraints


      1 <= T <= 20
      2 <= n <= 12
      1 <= k <= 1000000000


      Added by:Varun Jalan
      Date:2010-01-25
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem used for Codechef Snackdown Onsite









      SPOJ Problem Set (easy)

      5976. Traversing Grid

      Problem code: TRGRID

      Starting at the top left corner of an N*M grid and facing towards the right, you keep walking one square at a time in the direction you are facing. If you reach the boundary of the grid or if the next square you are about to visit has already been visited, you turn right. You stop when all the squares in the grid have been visited. What direction will you be facing when you stop ?

      For example : Consider the case with N = 3,M = 3. The path followed will be (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (2,1) -> (2,0) -> (1,0) -> (1,1). At this point, all squares have been visited, and you are facing right.

      Input


      The first line contains T the number of test cases. Each of the next T lines contain two integers N and M, denoting the number of rows and columns respectively.



      Output

      Output T lines, one for each test case, containing the required direction you will be facing at the end. Output L for left, R for right, U for up, and D for down.

      Eample


      Sample Input :
      4
      1 1
      2 2
      3 1
      3 3

      Sample Output :
      R
      L
      D
      R


      Constraints

      1 <= T <= 10000
      1 <= N,M <= 1000000000


      Added by:Varun Jalan
      Date:2010-01-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6 PYTH 3.2.3 n
      Resource:own problem used for Codechef Snackdown Onsite









      SPOJ Problem Set (classical)

      5977. Weird Function

      Problem code: WEIRDFN

      Let us define :
      F[1] = 1
      F[i] = (a*M[i] + b*i + c)%1000000007 for i > 1

      where M[i] is the median of the array {F[1],F[2],..,F[i-1]}.
      The median of an array is the middle element of that array when it is sorted. If there are an even number of elements in the array, we choose the first of the middle two elements to be the median.

      Given a,b,c and n, calculate the sum F[1] + F[2] + .. + F[n].

      Input


      The first line contains T the number of test cases. Each of the next T lines contain 4 integers : a,b,c and n.


      Output

      Output T lines, one for each test case, containing the required sum.

      Example

      Sample Input :
      2
      1 0 0 3
      3 1 2 6

      Sample Output :
      3
      103


      Constraints

      1 <= T <= 100
      0 <= a,b,c < 1000000007
      1 <= n <= 200000


      Added by:Varun Jalan
      Date:2010-01-25
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem used for Codechef Snackdown Onsite









      SPOJ Problem Set (classical)

      5978. Frequent Prime Ranges

      Problem code: FRQPRIME

      A range [L..H] is called a K-Frequent Prime range if there are atleast K primes amongst the numbers L,L+1,..,H. Given N and K, calculate how many subranges of the range [2..N] are K-Frequent Prime.

      Input

      The first line contains the number of test cases T. Each of the next T lines contains 2 integers N and K.


      Output

      Output T lines, one corresponding to each test case, containing the required answer.

      Example


      Sample Input :
      4
      2 1
      5 2
      5 1
      9 3

      Sample Output :
      1
      4
      9
      8

      Note : For the first test case, the only valid subrange is [2..2], whereas for the second test case, the valid subranges are : [2..3],[2..4],[2..5],[3..5].

      Constraints

      1 <= T <= 100

      2 <= N <= 100000

      0 <= K <= 10000


      Added by:Varun Jalan
      Date:2010-01-25
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem used for Technovanza









      SPOJ Problem Set (classical)

      5979. Yet Another Permutations Problem

      Problem code: YAPP

      How many permutations of the first N numbers exist such that the maximum element between the indices [i..j] is either present at index i, or at index j ?


      Input

      The first line contains the number of test cases T. Each of the next T lines contains an integer N


      Output

      Output T lines containing the required answer for the corresponding test case. Since the answers can get really big, output the result modulo 1000000007.

      Example


      Sample Input :
      1
      2

      Sample Output :
      2

       

      Constraints

       

      1 <= T <=10000

      1 <= N <= 1000000000


      Added by:Varun Jalan
      Date:2010-01-25
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem used for Technovanza









      SPOJ Problem Set (classical)

      5980. Matrix Game

      Problem code: MATGAME

      Two players A and B play the following game.
       
      1) First, a matrix M of size N*M is chosen, and filled with non-zero numbers.
      2) Player A starts the game and the players play alternately.
      3) In his turn, a player chooses any row which has atleast one non zero nuumber in it. In this row, the leftmost non zero number is chosen. Let this number be K. The player subtracts any number between 1 and K inclusive from it.
      4) The game ends when all the numbers in the matrix M are 0.
      5) The player who plays last wins the game.
       
       
      Given N,M and the initial matrix, determine who wins the game. Assume that both players play optimally.
       

      Input


       
      The first line contains the number of test cases T.
      Each test case consists of 2 numbers N and M. There follow N lines each having M integers. The jth number on the ith line is the number M[i][j]. There is a blank line between consecutive test cases.
       

      Output


      Output T lines, one for each case. Output "FIRST" if player A wins, else output "SECOND".

      Example


      Sample Input :
      3
      2 2
      1 1
      1 1
       
      1 3
      2 1 1
       
      2 2
      3 2
      3 2
       
      Sample Output:
       
      SECOND
      FIRST
      SECOND


      Constraints

      T <= 1000
      1 <= N,M <= 50
      The initial matrix values are between 1 and 50 inclusive.


      Added by:Varun Jalan
      Date:2010-01-25
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem used for Codechef Snackdown









      SPOJ Problem Set (classical)

      6035. Dinner

      Problem code: DINGRP

      On the way to dinner, the CCC competitors are lining up for their delicious curly fries. The N (1 ≤ N ≤ 100) competitors have lined up single-file to enter the cafeteria.

      Doctor V, who runs the CCC, realized at the last minute that programmers simply hate standing in line next to programmers who use a different language. Thankfully, only two languages are allowed at the CCC: Gnold and Helpfile. Furthermore, the competitors have decided that they will only enter the cafeteria if they are in a group of at least K (1 ≤ K ≤ 6) competitors.

      Doctor V decided to iterate the following scheme:

      • He will find a group of K or more competitors who use the same language standing next to each other in line and send them to dinner.
      • The remaining competitors will close the gap, potentially putting similar-language competitors together.

      So Doctor V recorded the sequence of competitors for you. Can all the competitors dine? If so, what is the minimum number of groups of competitors to be sent to dinner?

      Input

      The first line contains two integers N and K.
      The second line contains N characters that are the sequence of competitors in line (H represents Helpfile, G represents Gnold)

      Output

      Output, on one line, the single number that is the minimum number of groups that are formed for dinner. If not all programmers can dine, output -1.

      Sample Input

      7 2
      GHHGHHG

      Sample Output

      3
      

      Explanation

      There are seven competitors: a Gnold programmer followed by two Helpfile programmers, followed by another Gnold programmer, followed by another two Helpfile programmers followed by a final Gnold programmer. Programmers want to go to dinner in pairs.

      First send the first pair of Hs to dinner, leaving GGHHG. Then send the second pair of Hs to dinner, leaving GGG; finally, send in the group of Gs. It might be coincidental that the two pairs of Helpfile programmers entered the cafeteria successively.


      Added by:Brian Bi
      Date:2010-01-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:2009 Canadian Computing Competition Stage 2 - Problem B









      SPOJ Problem Set (classical)

      6041. Mountain Walking

      Problem code: QCJ1

      In this problem your task is to program a robot that will output some data about a terrain after traversing it. Input will be in the form a 2D picture containing only 4 types of characters :-

    • '/' : Forward slash, indicating ascent
    • '\' : Backward slash, indicating descent
    • '_' : Underscore, denoting horizontal plane
    • Additionally there will be only SPACE (Ascii value = 32) charecters. ( Refer the below figure).

      The robot starts its journey at bottom left corner of the terrain and after traversing stops at the bottom right corner. Also note that the robot will always start and end at the SAME LEVEL.

      Given the picture as input you will have to output 2 things. The "Total Walk Distance" i.e, the total length of the path and the type of steps taken to complete the Journey. For the sake of simplification we will assume that each charecter('/' , '\' & '_') has length = 1.

      Now Consider the following example:

      		   _
      / \/\
      / \
      / \

      The robot starts at the bottom left corner and takes the following path:

    • Ascends 3 steps
    • Moves forward by 1 step
    • Descends 1 step
    • Ascends 1 step
    • Descends 3 steps
    • and robot ends it journey at bottom right corner (At the same level). The Total Walk Distance = 9.

      Input

      First line of input will be an integer N (N<20). The next line will be an empty. Then exactly N lines follow describing the terrain.
      You can assume the following for the input (terrain).

    • Input will contain only four types of characters (" ","_","/","\").
    • The terrain will start and end at the same level.
    • Each line is guarenteed to have atleast one non white space charecter.
    • Maximum width of any line wont be larger than 200.
    • There will be no trailing white spaces.
    • Output

      First line of output should be the Total Walk Distance followed by the description the the the terrain. Each line must be ONE of the following

    • Up xx steps
    • Down xx steps
    • Walk xx steps
    • Where xx is an integer.
      Refer Examples for exact specification.

      Example

      Input:
      3

      /\
      / \
      / \

      Output:
      Total Walk Distance = 6
      Up 3 steps
      Down 3 steps

      Input:
      2

      _____ ___
      / \/ \


      Output:
      Total Walk Distance = 12
      Up 1 steps
      Walk 5 steps
      Down 1 steps
      Up 1 steps
      Walk 3 steps
      Down 1 steps

      Input:
      5

      _
      /\__/ \
      / \
      / \/\_
      / \

      Output:
      Total Walk Distance = 16
      Up 4 steps
      Down 1 steps
      Walk 2 steps
      Up 1 steps
      Walk 1 steps
      Down 3 steps
      Up 1 steps
      Down 1 steps
      Walk 1 steps
      Down 1 steps


      Added by:abhijith reddy d
      Date:2010-02-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own









      SPOJ Problem Set (classical)

      6042. Another Box Problem

      Problem code: QCJ2

      There are N numbered boxes placed on a table, let Bi denote the ith box in the line. Write a program that finds the total number of ways to place N identical balls such that atmost k balls are present in the boxes B1, .... ,Bk for 1<=k<=N. Since the number can be quite large you are supposed to output the answer modulo 761238923.

      Input

      Input will contain multiple testcases, on each line N (1<=N<=100) will be given. The last line contains 0 which should not be processed.

      Output

      For each testcase output exactly one line, the total number possible of ways modulo 761238923.

      Example

      Input:
      1
      2
      0
      Output:
      1
      2

      Added by:abhijith reddy d
      Date:2010-02-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own









      SPOJ Problem Set (classical)

      6043. The Game

      Problem code: QCJ3

      Tom and Hanks play the following game. On a game board having a line of squares labelled from 0,1,2 ... certain number of coins are placed with possibly more than one coin on a single square. In each turn a player can move exactly one coin to any square to the left i.e, if a player wishes to remove a coin from square i, he can then place it in any square which belongs to the set (0,1, ... i-1) . The game ends when all coins are on square 0 and player that makes the last move wins. Given the description of the squares and also assuming that Tom always makes the first move you have tell who wins the game (Assuming Both play Optimally).

      Input

      The first line will contain N the number of test cases and then 2N lines follow. For each test case the first line will have S the size of the board and in the next line S integers follow. The ith integer gives the the number of coins in the ith square (starting from 1) . Atleast one of the S integers will be non zero. All the numbers in the input will be less than 25.

      Output

      For each test case output one line containing either "Tom Wins" or "Hanks Wins".

      Example

      Input:
      2
      1
      1
      1
      2

      Output:

      Tom Wins
      Hanks Wins

      Added by:abhijith reddy d
      Date:2010-02-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own









      SPOJ Problem Set (classical)

      6044. Minimum Diameter Circle

      Problem code: QCJ4

      Given n points in a plane find the diameter of the smallest circle that encloses all the points. A point lying on the circle is also considered to be inside it

      Input

      First line of input contains the n (<301) the number of points in the plane , followed by n lines of input
      Each line gives the coordinates of one point on the plane. Each coordinate is an integer in the range [0,1000]

      Output

      Output consists of a single real number, the diameter of the circle rounded to two decimal places.

      Example

      Input:
      4
      1 1
      1 0
      0 1
      0 0


      Output:
      1.41

      Added by:abhijith reddy d
      Date:2010-02-01
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:CCC [Own Input]









      SPOJ Problem Set (classical)

      6052. PBCGAME

      Problem code: PBCGAME


      The company "PBC" has made a game which consists of small platforms and pipes. There are 3 types of platforms: starting platforms (there are N1 of them), finishing platforms (there are N3 of them) and middle platforms (there are N2 of them). All starting platforms stand at identical height. Finishing platforms stand also at identical height. All heights of middle platforms are various. They have less height than starting, but greater height than finishing platforms. Each platform has an unique number from 1 up to N1+N2+N3. First N1 numbers are starting platforms, next N2 numbers are middle platforms, and the last N3 numbers are finishing platforms. All middle platforms are numbered in order of decrease of height. It means that if number of middle platform A is less than number of platform B, than height of A is greater than height of B.

      There is a ball on each of starting platforms. The ball can move from platform A to platform B if they are connected by a pipe, and height A is greater than height B. Each finishing platform can hold only one ball. If there is a ball on a platform the player can choose a direction of the further way of the ball, it means that he can choose a platform, where the ball will go. Also given a number C for each middle platform which means a maximum quantity of balls which can pass it during the game. The goal of the game is to drive the greatest possible number of ball to the finishing platforms.

      You need to find out what maximum quantity of balls can appear on finishing platforms at the end of the game.

      Input

      The input file has the following order:
      N1 N2 N3
      CN1+1
      ...
      CN1+N2
      K1 A[1,1] ... A[1,K1]
      K2 A[2,1] ... A[2,K2]
      ...
      KN1+N2 A[N1+N2,1] ... A[N1+N2,KN1+N2]
      Where N1, N2, N3 are the amounts of starting, middle and finishing platforms. Cj is the maximum amount of balls, which can pass the middle platform with the number j (N1+1 <= j <= N1+N2) during the game. Ki is the number of pipes, connected with the platform i (1 <= i <= N1+N2). The elements of the array A, are the numbers of platforms where the ball can move from the appropriate platform (platforms with numbers i and A[i] are connected with a pipe).

      Output

      The output file must contain a number, which means the max amount of balls, which can appear at the finishing platforms at the end of the game.

      Example

      Input:
      3 4 3
      3
      2
      1
      2
      1 4
      1 4
      1 4
      2 5 6
      1 7
      1 7
      3 8 9 10

      Output: 2

      Limitations:
      All the numbers are integer.
      0< N1, N3 < 51
      1 < N1+N2+N3 < 201
      0 <= Cj <= 50
      There are no pipes between starting platforms.
      There are no pipes between finishing platforms.

      Added by:Phan Công Minh
      Date:2010-02-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:A.N. Danchenko - belarus









      SPOJ Problem Set (classical)

      6059. Another GCD problem

      Problem code: GCDSQF

      A number is square-free if its prime descomposition contains no repeated factors. For example: 1001 = 7 * 11 * 13 is square-free, but 20 = 2 * 2 * 5 is not square-free.

      Square-free numbers can encoding as binary numbers. Here are examples to illustrate:

      Sequence of prime numbers 2 3 5 7 11 13 17 ...
      42 = 2 * 3 * 7           <=>     1101
      1001 = 7 * 11 * 13    <=>     000111
      10 = 2 * 5                <=>     101

       
      Your task is given two square-free integers A and B in binary representation
      compute gcd (A + B, lcm (A, B)). If the result is a square-free number your answer should
      have the binary format, if the answer is 1 print "relatively prime", and if
      is neither of these two cases print the result in base 10.

      Input

      In the first line an integer T (1 <= T <= 100) the number of test cases.
      The following 2 * T lines will appear integers A and B. The length of the integers
      A and B encoded in binary form must not exceed 1000 characters.

      Output

      For each of the T pairs A, B print in the specified format gcd (A + B, lcm (A, B)).

      Example

      Input: 
      

      2
      000111
      101
      11
      011

      Output:

      relatively prime
      01


      Note: In the input may have unnecessary zeros on the right of the numbers A and B, but
      Your answer only must be with necessary zeros.


      Added by:Frank Rafael Arteaga
      Date:2010-02-07
      Time limit:0.300s
      Source limit:6000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem, Discrete Math









      SPOJ Problem Set (classical)

      6072. Chocolate

      Problem code: SOCOLA

      Chocolate in its many forms is enjoyed by millions of people around the world every day. It is a truly universal candy, available in virtually every country around the world.

      You find that the only thing better than eating chocolate is to share it with friends. Unfortunately, your friends are very picky and have different appetites: some would like more and others less of the chocolate that you offer them. You have found it increasingly difficult to determine whether their demands can be met. It is time to write a program that solves the problem once and for all!

      Your chocolate comes as a rectangular bar. The bar consists of same-sized rectangular pieces. To share the chocolate, you may break one bar into two pieces along a division between rows or columns of the bar. You may then repeatedly break the resulting pieces in the same manner. Each of your friends insists on a getting a single rectangular portion of the chocolate that has a specified number of pieces. You are a little bit insistent as well: you will break up your bar only if all of it can be distributed to your friends, with none left over.

      For example, Figure 9 shows one way that a chocolate bar consisting of 3 x 4 pieces can be split into 4 parts that contain 6, 3, 2, and 1 pieces respectively, by breaking it 3 times. (This corresponds to the first sample input.)

      Figure 9

      Input

      The input consists of multiple test cases, each describing a chocolate bar to share. Each description starts with a line containing a single integer n (1 <= n <= 15), the number of parts into which the bar is supposed to be split. This is followed by a line containing two integers x and y (1 <= x, y <= 100), the dimensions of the chocolate bar. The next line contains n positive integers, giving the number of pieces that are supposed to be in each of the n parts.

      The input is terminated by a line containing the integer zero.

      Output

      For each test case, first display its case number. Then display whether it is possible to break the chocolate in the desired way: display "Yes" if it is possible, and "No" otherwise. Follow the format of the sample output.

      Sample Input

      4 
      3 4
      6 3 2 1
      2
      2 3
      1 5
      0
      

      Sample Output

      Case 1: Yes
      Case 2: No
      

      Added by:Duc
      Date:2010-02-09
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ACM ICPC World Final 2010









      SPOJ Problem Set (classical)

      6168. Building Bridges

      Problem code: BRIDGE

      The tribe soon discovers that just communication is not enough and wants to meet each other to form a joint force against the terminator. But there is a deep canyon that needs to crossed. Points have been identified on both sides on which bridge ends can be made. But before the construction could be started, a witch Chudael predicted that a bridge can only be built between corresponding end points, i.e. a bridge starting from the ith end point on one side can only end on the ith end point on the other side, where the position of end points is seen in the order in which the points were identified. If not, it would lead to the end of the tribe. The tribe just wants to make as many non-cutting bridges as possible, with the constraint in mind. Bridges "cut" if and only if they have exactly one common point that is not an end point.

      Input

      The first line of the input contains test cases t (1<=t<=50). It is followed by 3*t lines, 3 for each test case. The first line of input for each test case contains the number of end points identified on each side, n (1<=n<=103). The second line contains x-coordinates of end points identified on the first side and similiarly the third line contains the x-coordinates of corresponding end points identified on the other side. The end points are inputted in the order in which they were identified. The x-coordinates can range between -103 to 103.

      Output

      You are required to output a single line for each test case. The line contains a single integer – the maximum number of bridges possible with the constraints explained above.

      Example

      Input:
      3

      4

      2 5 8 10

      6 4 1 2

      3

      5 3 10

      6 4 1

      6

      1 2 3 4 5 6

      3 4 5 6 1 2

      Output:

      2

      2

      4

       

      Expalanation: For the first test case, two non-overlapping bridges can be formed between the 3rd and 4th end points on each side.


      Added by:Troika::Bytes
      Date:2010-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ F# GO NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SED









      SPOJ Problem Set (classical)

      6169. Standing Sequence

      Problem code: SSEQ

      Now that the two tribes met, a joint force was formed. Colonel Prateek was ordered to lead the force. He needs to instruct his men on how to stand. The n men in the force have been given ranks from 1(lowest) to n(highest) and on parade they should be lined up from left to right in increasing order of rank. He soon discovered that his elite commandos preferred to do the fighting, and leave the thinking to their superiors. So, when at the first roll call the soldiers lined up in fairly random order it was not because of their lack of discipline, but simply because they couldn’t work out how to form a line in correct order of ranks. Colonel Prateek was not at all amused, particularly as he soon found that none of the soldiers even remembered his own rank. Over the years of service every soldier had only learned which of the other soldiers were his superiors. But Colonel Prateek was not a man to give up easily when faced with a true military challenge. After a moment’s thought a solution of brilliant simplicity struck him and he issued the following order: "men, starting from the left, one by one, do: (step forward; go left until there is no superior to the left of you; get back in line).". This did indeed get the men sorted in a few minutes. The problem was solved... for the time being.

      The next day, the soldiers came in exactly the same order as the day before, and had to be rearranged using the same method. History repeated. After some weeks, Colonel Prateek managed to force each of his soldiers to remember how many men he passed when going left, and thus make the sorting process even faster.

      If you know how many positions each man has to walk to the left, can you try to find out what order of ranks the soldiers initially line up in?

      Input

      The first line of input contains an integer t<=50, the number of test cases. It is followed by t test cases, each consisting of 2 lines. The first line contains a single integer n (1<=n<=200000). The second line contains n space separated integers wi , denoting how far the ith soldier in line must walk to the left when applying Colonel Prateek’s algorithm.

      Output

      For each test case, output a single line consisting of n space separated integers - the ranks of the soldiers, given from left to right in their initial arrangement.

      Example

      Input:
      

      2

      3

      0 1 0

      5

      0 1 2 0 1
      Output:
      

      2 1 3

      3 2 1 5 4


      Added by:Troika::Bytes
      Date:2010-02-18
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6









      SPOJ Problem Set (classical)

      6170. Homecoming

      Problem code: HOMEC

      It was a tough battle but the humans won it comprehensively in the end. It was made possible due to combined efforts of both the human tribes but the 2nd tribe wants to take all the credit and rule the world by killing the first tribe. Now that the war has ended, the tribes would be returning to their cities. The warriors would be travelling over the bridges built earlier, in small groups. It is then that the 2nd tribe wants to execute their plan. The king of the 1st tribe knows this and wants to ensure that this doesn’t happen. So he puts a constraint, that it should never happen at any time that the number of people of the 2nd tribe outnumber the number of people of the 1st tribe either on both sides or on the bridge. Also, it is night time and a torch needs to be carried for travel to be possible. But unfortunately, there’s just one torch available and hence atleast someone would have to come back every time, with the torch. To make matters worse, there’s a restriction on the number of warriors that can cross the bridge in one pass.

      Input

      The first line of input contains test cases t (1<=t<=50). Then t lines follow, one for each test case. It contains three integers, n (1<=n<=100) the number of warriors of first tribe, m (1<=m<=100) the number of warriors of second tribe and c (1<=c<=50) the number of warriors that can cross the bridge in a single pass. 

      Output

      Display a single line for each test case, containing a single integer which gives the total number of times the bridge is crossed. A round trip counts as 2. Output -1 if travel is not possible with the given constraints.

      Example

      Input:
      

      3

      3 3 2

      4 4 2

      100 100 20

      Output:

      11

      -1

      21


      Added by:Troika::Bytes
      Date:2010-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6









      SPOJ Problem Set ()

      6171. Majority

      Problem code: MAJOR

      The human tribe has just discovered some other tribe and wants to communicate with them. To make sure it is not intercepted by the terminators, they ask their chief computer engineer Rohit to design a system for the purpose. In the design that Rohit proposes, data is transmitted n times. If it is received more than half-the times, it is said to be successfully transmitted. If not, the data is said to be lost. Rohit obviously got a lot of fame and respect for his work. Nitish doesn’t like it and wants to challenge Rohit’s supremacy. He wants to check out the system and has hired you for the process.

      Input

      The first line of the input contains test cases t(1<=t<=100). It is followed by 2*t lines, 2 for each test case. The first line of input for each test case contains a number n (0<=n<=106), followed by n elements in the next line. Each number is from -10^3 to +10^3

      Output

      You are required to output ‘YES’ followed by the number transmitted, if it was transmitted successfully, and ‘NO’ otherwise.

      Example

      Input:
      

      3

      4

      2 1 2 2

      6

      1 1 1 2 2 2

      5

      1 2 4 5 1

      Output:

      YES 2

      NO

      NO


      Added by:Troika::Bytes
      Date:2010-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6









      SPOJ Problem Set (classical)

      6172. OAE

      Problem code: OAE

      Having joined forces and preparing for the war with the terminators the humans do know that it will be a tough battle. They plan to strike each base of the terminator and destroy them one by one. A genius computer engineer UD willing to extend his help to his fellow humans found out that each base of the terminator has password protected doors. He was able to recognise the pattern between the passwords. The password is an n character string having even number of zeroes. As you know many strings of this type exist. Help him to find out the total number of such strings. Each character in the password string is a digit from 0 to 9.

      Input

      The first line of input contains an integer t<=50, the number of test cases. Then t test cases follow each containing a line with a single integer n (1<=n<=106).

      Output

      A single line for each test case, containing the answer modulo 314159.

      Example

      Input:
      

      2

      2

      1

      Output:

      82

      9


      Added by:Troika::Bytes
      Date:2010-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6









      SPOJ Problem Set (classical)

      6187. Jane and Tarzan

      Problem code: JANE

      Jane and Tarzan have got cellphones and now they want to be available all the time. They live in a long line of trees and they are available iff the absolute difference between the heights of the two trees which they are on is not greater than D.

      Jane and Tarzan are moving by the following rules: each second both Jane and Tarzan (simultaneously) jump, from the tree which they are on, on one of the adjacent trees (the left or the right one). It is forbidden to stay on the same tree. Moreover, in the very beginning and after each second they have to be available.

      The trees in the line are numbered from 1 to N, respectively. Jane is interested in the pairs of trees (J, T) – let's call them good pairs – for which it holds: if Jane begins on the J-th tree, and Tarzan on the T-th tree, they can swap their positions after some time (moving by the rules) – so that Tarzan ends on the J-th tree, and Jane on the T-th tree.

      Have a look on the first test example. D = 0 means that the heights of the trees which Jane and Tarzan are on have to differ by at most 0 (therefore, have to be equal) all the time. Pair (1, 5) is a good pair since we can take 1-2-3-4-5-6-5 as Jane's route, and 5-6-5-4-3-2-1 as Tarzan's route – this results in Jane and Tarzan swapping their initial positions (and being available all the time).

      Output all the good pairs (J, T) in which J < T.

      Input

      In the first line of input there are integers N (1 ≤ N ≤ 100 000) and D (0 ≤ D ≤ 109).

      In the next N lines there are N natural numbers less than 109 – heights of the trees in the line (from the 1st tree to the N-th tree).

      Output

      Output all the requested pairs in sorted order. We define a pair (A, B) to be smaller than the pair (C, D) iff (A < C) or (A = C and B < D).

      In all of the test data, the number of these pairs will not exceed 100 000.

      Example

      Input:
      6 0
      2
      1
      2
      3
      2
      1
      
      Output:
      1 3
      1 5
      2 6
      3 5
      
      Input:
      5 10
      10
      20
      10
      5
      10
      
      Output:
      1 2
      1 3
      1 4
      2 3
      2 5
      3 4
      3 5
      4 5
      

      Added by:Stjepan Glavina
      Date:2010-02-21
      Time limit:1s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:author: Adrian Satja Kurdija









      SPOJ Problem Set (classical)

      6219. Edit distance

      Problem code: EDIST

       

      You are given two strings, A and B. Answer, what is the smallest number of operations you need to transform A to B.
      Operations are:
      1) Delete one letter from one of strings
      2) Insert one letter into one of strings
      3) Replace one of letters from one of strings with another letter 
      Input
      T - number of test cases
      For each test case:
      String A
      String B
      Both strings will contain only lowercase characters and they won't
      be longer than 2000 characters. 
      Output
      For each test case, one line, minimum number of operations.
      Example
      Input:
      1
      FOOD
      MONEY 
      Output:
      4

      You are given two strings, A and B. Answer, what is the smallest number of operations you need to
      transform A to B?

      Operations are:

      1) Delete one letter from one of strings
      2) Insert one letter into one of strings
      3) Replace one of letters from one of strings with another letter 

      Input

      T - number of test cases

      For each test case:

      String A
      String B

      Both strings will contain only uppercase characters and they won't
      be longer than 2000 characters. 

      There will be 10 test cases in data set.

      Output

      For each test case, one line, minimum number of operations.

      Example

      Input:

      1
      FOOD
      MONEY 

      Output:

      4


      Added by:Mislav Balunoviæ
      Date:2010-02-28
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Internet









      SPOJ Problem Set (classical)

      6221. Increasing Powers of K

      Problem code: INCPOWK


      Let's define Sk as the increasing sequence a1, a2, a3, ... consisting of all those
      positive integers which are powers of K or sums of distinct powers of K.
       
      For example S3 = {1,3,4,9,10,12,13,27,28,30,...}
       
      Your task is given N and K find the Nth term of the sequence Sk.

      Input

      The first line of the input contains a single integer T(1 <= T <= 104) representing the
      number of test cases. The next T lines consist of two numbers each one separated by a single space:  
      K (3 <= K <= 9) and N (1 <= N <= 10200).

      Output

      For each test case print a single line, the Nth term of the sequence Sk.

      Example

      Input:
      8
      3 4
      3 100
      4 3
      5 12
      6 7
      7 239
      8 17
      9 500

      Output:
      9
      981
      5
      150
      43
      958399
      4097
      48426822

      Added by:Angel Paredes
      Date:2010-03-02
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: JAVA NODEJS PERL 6
      Resource:American Invitational Mathematics Examination 1986









      SPOJ Problem Set (classical)

      6236. Matches

      Problem code: FERT21_0

      Upon a table there are two boxes. Each box has N matches inside. We want to know what is the probability of choose N times a random box and take one match from it, at the end have an empty box.

      You have to print all digits.

      Constrains
      1 <= T <= 1000
      1 <= N <= 1000

      Input

      T
      N1
      N2
      ...
      NT

      Output

      P1
      P2
      ...
      PT

      Example

      Input:
      1
      2

      Output:
      0.5

      Added by:Leandro Castillo Valdes
      Date:2010-03-03
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: JS
      Resource:own problem









      SPOJ Problem Set (classical)

      6256. Inversion Count

      Problem code: INVCNT

      Let A[0...n - 1] be an array of n distinct positive integers. If i < j and A[i] > A[j] then the pair (i, j) is called an inversion of A. Given n and an array A your task is to find the number of inversions of A.

      Input

      The first line contains t, the number of testcases followed by a blank space. Each of the t tests start with a number n (n <= 200000). Then n + 1 lines follow. In the ith line a number A[i - 1] is given (A[i - 1] <= 10^7). The (n + 1)th line is a blank space.

      Output

      For every test output one line giving the number of inversions of A.

      Example

      Input:

      2

      3
      3
      1
      2

      5
      2
      3
      8
      6
      1


      Output:

      2
      5


      Added by:Paranoid Android
      Date:2010-03-06
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6









      SPOJ Problem Set (main)

      6264. Rank of a Fraction

      Problem code: FNRANK

      Let us consider a set of fractions x/y, such that 0 <= x/y <= 1, y <= n and gcd (x, y) = 1.

      For example, say n = 5. Then we have the following set in increasing order :

      01, 15, 14, 13, 25, 12, 35, 23, 34, 45, 11

      You are given n, a and b. The task is to find the rank of a/b in a set of fractions as stated above which is in increasing order.


      Input

      The first line of the input contains t (t <= 20), the number of testcases. Then t lines follow. In each of the t lines you are given n, a and b.  (n <= 100000)

      Output

      Print t lines. The ith line contains the rank of a fraction a/b for a given n, a and b in the (i + 1)th line of input. All answers fit within a signed integer.

      Example

      Input:
      2
      5 3 4
      8 5 7
       


      Output:
      9
      17

       


      Added by:Paranoid Android
      Date:2010-03-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Based on the problem FRACTION









      SPOJ Problem Set (classical)

      6285. Another Game With Numbers

      Problem code: NGM2

      Little Chikoo likes to play with numbers. Often he plays the following game :

      1. He chooses a number N and a set of positive integers.
      2. He writes down all the numbers from 1 to N.
      3. He chooses the first number (say x) from the set and cancels out all the multiples of x from 1 to N, including x.
      4. He repeats step 3 for all the numbers from the set.

      One day Little Chikoo was in a mood to play pranks. So his brother asked him to play the game with a certain challenge. He made the game a little harder and asked him to find out the number of integers which aren't cancelled after he completes step 4. If he does that then Little Chikoo gets to play on his brother's Nintendo for one full day. Now Little Chikoo is in a hurry and wants to finish the job as soon as possible. He has asked for your help.

      Input

      The first line of the input contains N and K. (N <= 10^9, K <= 15)

      Then K numbers follow all in a single line. All numbers are <= 100.

      Output

      The output file must contain the number of integers that aren't cancelled after he finishes step 4 of the game.

      Example

      Input:

      10 3

      2 4 5

      Output:

      4

      (The numbers 1, 3, 7 and 9 weren't cancelled).


      Added by:Paranoid Android
      Date:2010-03-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:-









      SPOJ Problem Set (classical)

      6286. Sum of products

      Problem code: SUMMUL

      One boy Petya decided to practice in addition and multiplication of numbers. For this he chose some positive integer n, and ordered all the ways to decompose it into two or more terms of positive integers, and the ways in different order terms are considered to be different (for example, for n = 3 there are three ways: 1 + 2, 2 + 1 and 1 + 1 + 1). Then he replaced all the plus signs with multiplication, and added the results (for n = 3: 1 × 2 + 2 × 1 + 1 × 1 × 1 = 5). After practicing for the day he decided to check the correctness of his calculations. Help Petya find the right answers.

      Input

      The first line contains T (1 <= T <= 1000) - the number of tests. Following T lines contain n (1 <= n <= 10 ^ 9).

      Output

      For each n from the input print the result Petya should get modulo 1000000007.

      Example

      Input:
      3
      1
      2
      3
      
      Output:
      0
      1
      5
      
      

      Added by:Spooky
      Date:2010-03-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set (classical)

      6288. Treeramids

      Problem code: PYRA

      Daniel is building towers. He has a big amount of block of the size 1x1xK (for any K). Out of them he is building towers according to the following rules: the longest block is put in the basement of the tower. Several towers built by the same rules can be put on this block. The distance between the bases of those towers should be 1 and the distance between the bases of the towers and the edges of the common basement should be 1. There should be a block of the length 1 on the top of each tower. Daniel encodes every tower with root tree. For example:

      The root of the tree corresponds to the basement of the tower. Its descendants correspond to the towers standing on it. The leaves correspond to the blocks of the size 1x1x1 on the tops. Given the root tree describing one of those structures, calculate the total volume of the structure.

      Input

      The first line of input contains the number t - the number of tests. Next comes the description of t tests. Each test starts with an integer n - the number of nodes of the tree. This is followed by n-1 line, consisting of two integers a and b - number of nodes connected by an edge. Nodes are numbered from 0 to n-1. The root of the tree will always be a node with number 0. Otherwise the nodes and edges can go in any order.

      Constraints

      1 <= t <= 25
      1 <= n <= 10^4

      Output

      For each test case print the total volume of the structure build according to the rules in the problem statement.

      Example

      Input:
      2
      7
      0 1
      2 0
      0 3
      2 4
      5 2
      6 3
      3
      1 2
      1 0
      
      Output:
      25
      9
      
      

      Added by:Spooky
      Date:2010-03-09
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      6289. Bomberman

      Problem code: BOMBER

      Alice and Bob love to play Bomberman. They decided to upgrade the game. Their version is played on a rectangular board divided into cells. The first player puts a bomb on any cell. The bomb destroys this cell, as well as all consecutive undestroyed cells left, right, above and below it. Then the second player puts his bomb, then again the first and so on. The player who destoys the last cell wins the game. Given the dimensions of the board, determine which player wins the game assuming that both players play optimally.

      Input

      The first line contains T (1 <= T <= 1000) - the number of tests. The next T lines contain two integers m and n (1 <= m, n <= 100) - the size of the board.

      Output

      For each test print 1 if the first player wins the game, or 2 if the second wins.

      Example

      Input:
      1
      2 2
      
      Output:
      2
      
      

      Example of the first two moves of 7x7 board


      Added by:Spooky
      Date:2010-03-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ F# GO NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SED
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set ()

      6290. Robbery 2

      Problem code: ROBBERY2

      k bandits robbed a bank. They took away n gold coins. Being a progressive group of robbers they decided to use the following procedure to divide the coins. First the most respected bandit takes 1 coin, then the second respected takes 2 coins, ..., the least respected takes k coins, then again the most respected takes k+1 coins, ans so on, until one of the bandits takes the remaining coins. Calculate how much gold each of the bandits gets.

      Input

      The first line of the input contains number t – the amount of tests. Then t test descriptions follow. Each test consists of two integers n and k - the amount of coins and bandits respectively.

      Constraints

      1 <= t <= 500
      106 <= n <= 1015
      2 <= k <= 100

      Output

      For each test print the amounts of coins each bandit gets separated by spaces.

      Example

      Input:
      3
      1000000 2
      1234567 3
      123456789 4
      
      Output:
      499849 500151
      411602 411887 411078
      30869901 30858368 30862296 30866224
      
      

      Added by:Spooky
      Date:2010-03-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      6292. Shmoogle Wave

      Problem code: SHMOOGLE

      Shmoogle company developed new protocol <<Wave>> for the multi-user online editing of the text data. Using it, any client can send commands to the server for editing the text and the server would broadcast it to all other connected clients. Each command consists of a sequence of operations of the following type:

      OperationDescription
      R kMoves the cursor k positions right. The cursor is positioned at before the first character of the text at the start of performing the command.
      C k sInserts the string s of length k at the cursor position. After this operation the cursor is positioned to the right of the inserted string.
      D kDeletes k characters right of the cursor.

      When the new client connects the server needs to send it all the command this client missed. In order to save traffic the server merges all the commands in one equivalent command. Help Shmoogle company implement merging of commands effectively.

      The resulting command should consist of the least possible number of operations. The delete operations should precede the insert operations if possible.

      Input

      The first line contains T (1 <= T <= 10) — the number of test cases. The description of T tests follow. The first line of each test case contains the amount of commands n (1 <= n <= 10000). The description of each command follows. The first line of each command contains the amount of operations m (1 <= m <= 10). The next m lines contain the description of each operation in the format given above. 1 <= k <= 100000 for R and D operations, and 1 <= k <= 10 for C operations. The strings in C operations consist of latin letters and digits only.

      Output

      For each test case your program should print the result of merging the commands. The format of the command should be the same as in the input file, except for the limitations on m and k. The result should consist of the least possible number of operations. The delete operations should precede the insert operations if possible. If the result of merging consist of no operations print 0.

      Example

      Input:
      1
      2
      4
      R 4
      C 3 abc
      R 2
      C 3 xyz
      3
      R 7
      C 3 def
      D 3
      
      Output:
      3
      R 4
      D 2
      C 8 abcdefyz
      
      

      Added by:Spooky
      Date:2010-03-09
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set (classical)

      6294. Yodaness Level

      Problem code: YODANESS

      Yoda is the wisest, and perhaps the most powerful Jedi of his time. Yoda is a mysterious figure and he has many oddities. One of them is that Yoda often changes the order of words in the sentence. For example, one of such phrases is "Or I will help you not." Let's call the yodaness level of any statement the number of pairs of words that changed their order, as to the order in which they were supposed to go in a normal statement. Write a program that determines the yodaness level of different statement of Yoda.

       

      Input

      The first line of input contains the number t - the number of tests. Next comes the description of t tests. Each test consists of three rows. The first line of the test contains an integer n - number of words in the statement. The next line contains n words separated by spaces - the statement as Yoda says it. The next line is n words separated by spaces - the same statement as it should be said normally. All the words in the statement are different and consist of small latin letters.

      Constraints

      1 <= t <= 10
      1 <= n <= 30000
      the length of each word does not exceed 20 characters

      Output

      For each test print the yodaness level of the statement.

      Example

      Input:
      2
      6
      in the force strong you are
      you are strong in the force
      6
      or i will help you not
      or i will not help you
      
      Output:
      11
      2
      
      

      Added by:Spooky
      Date:2010-03-09
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      6296. Experiment

      Problem code: EXPER

      The following experiment is taking place. There are n points of a plane. Each point is moving with the uniform velocity. It is needed to determine the minimum circle which encloses all the points after each second of the experiment during the fixed time T.

      Input

      The first line of input contains the number t - the number of tests. Next comes the description of t tests. The first line of each test consists of two integers n - number of points and T - the duration of the experiment in seconds. The next n lines contain four integers separated by spaces x, y, vx, vy - initial coordinates and velocities of each point.

      Constraints

      1 <= t <= 10
      1 <= n <= 2000
      1 <= T <= 50
      -100 <= x, y, vx, xy <= 100

      Output

      For each test case print T real numbers Ri for i from 1 to T rounded to two decimals after the point. Ri should be the radius of the minimal circle which encloses all the points.

      Example

      Input:
      1
      3 5
      1 0 1 0
      3 4 1 2
      5 5 -2 -1
      
      Output:
      3.16
      4.12
      5.41
      7.43
      9.55
      
      

      Added by:Spooky
      Date:2010-03-09
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      6297. Decipher

      Problem code: ROOTCIPH

      Radar scanned the approaching enemy aircraft on the border. However due to some error part of the tranmitted data can't be deciphered. It was possible only to obtain the coefficients of the cubic polynomial, whose roots are the coordinates of the aircraft relative to the radar. Now you need to calculate the distance to the aircraft. Write the program to solve this task.

      Input

      The first line contains T (1 <= T <= 1000) - number tests. The next T lines contain three integers a, b and c - coefficients of the polynomial x3 + ax2 + bx + c, whose roots are the coordinates (the absolute value of the coordinates do not exceed 108).

      Output

      For each test print the square of the distance to the enemy aircraft.

      Example

      Input:
      1
      -6 11 -6
      
      Output:
      14
      
      

      Added by:Spooky
      Date:2010-03-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set ()

      6299. Move Marbles

      Problem code: MOVMRBL

      You have N marbles and K slots. You have to follow the below mentioned rules :

      1. You can put in a marble or take out a marble from slot numbered 1 at any time.
      2. You can put in a marble or take out a marble from slot numbered i only if there exists a marble at the slot i - 1.
      3. The game stops when a marble reaches the slot numbered K for the first time.

      Your task is to finish the game in minimum number of valid moves.

      Input

      The first line contains t, the number of testcases. Then on each line is given two numbers N <= 15, K <= 2^N - 1.

       

      Output 

      Print two numbers namely the number of "put in" moves and the number of "remove from" moves respectively for all the tests such that you move to the Kth slot in minimum number of valid moves. See explanation section below for more details.

      Example

      Input: 

      1

      3 6

      Output:

      6 3

      Explanation :

      The following are the valid moves for the given input:

      PUT IN 1
      PUT IN 2
      PUT IN 3
      REMOVE FROM 2
      REMOVE FROM 1
      PUT IN 4
      PUT IN 5
      REMOVE FROM 4
      PUT IN 6
       


      Added by:Paranoid Android
      Date:2010-03-09
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:-









      SPOJ Problem Set (classical)

      6322. The hunt for Gollum

      Problem code: ARDA1

      Along the skirts of the Dead Marshes I followed it, and then I had him. Lurking by a stagnant mere, peering in the water as the dark eve fell, I caught him, Gollum. He was covered with green slime. He will never love me, I fear; for he bit me, and I was not gentle. Nothing more did I ever get from his mouth than the marks of his teeth.


      “The Lord of the Rings: The fellowship of the Ring”

       

      Hearing Gandalf’s advice, Aragorn has started hunting creature Gollum. After several days following his footprints, he has arrived to the Dead Marshes. He has a map of the marshes, that can be viewed as an M1 * M2 matrix containing lowercase letters form English alphabet (i.e. letters from ‘a’ to ‘z’).

      Being a skilled ranger, Aragorn has been able to fully characterize Gollum preferred place (if you are interested, you should know that it must be dark, wet, creepy and full of fishes!). It can be described as an N1 * N2 matrix containing lowercase letters form English alphabet.

      Your task is simple: write a program that, given Gollum’s preferred place description and Aragorn’s map, output all possible locations of the creature.

      Let’s look at an example: suppose Gollum’s preferred place is described by the following 3 * 3 matrix:

      aba

      bab

      aba

      and that Aragorn’s map looks something like this:

      aababa

      ababab

      bababa

      ababab

      ababab

      bababa

      ababab

      Then your program must output the following: (1,2), (1,4), (2,1), (2,3), (5,1) and (5,3), these being the upper-left corners of all places on the Dead Marshes that match Gollum’s preferred place description. If none match is found, you should output the string “NO MATCH FOUND...” without the quotes.

      Input

      Line 1: Two integers: N1 and N2.

      Lines 2… N1 + 1: A string with N2 characters as described above.

      Lines N1 + 2: Two integers: M1 and M2.

      Lines N1 + 3… N1 + M1 + 3: A string with M2 characters as described above.

      Restrictions


      1 ≤ N1, N2 ≤ 300

      1 ≤ M1 * M2 ≤ 2000

      N1 ≤ M1

      N2 ≤ M2

      Output

      On each line print the upper-left corner of all places that match Gollum’s preferred place description on the form “(x,y)” without the quotes, where x stands for the row and y for the column. They should be lexicographically sorted, i.e. imagine them as an ordered pair. Then (x1,y1) < (x2,y2) if and only if x1 < x2 or, if they are equal, y1 < y2.

      Example

      Input:

      3 3

      aba

      bab

      aba

      7 6

      aababa

      ababab

      bababa

      ababab

      ababab

      bababa

      ababab


      Output:

      (1,2)

      (1,4)

      (2,1)

      (2,3)

      (5,1)

      (5,3)


      Added by:Camilo Bravo Valdés
      Date:2010-03-11
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      6325. Many polygons

      Problem code: NGON

      There is a regular n-gon. We mark some points on its sides: a1 points on the first side, a2 on the second ... an on the last. Marked points do not coincide with the vertices n-gon. The question is, how many different convex nondegenerate (n-1)-gons you can build, using marked points as vertices?

      Input

      The first line of input contains the number t - the number of tests. Next comes the description of t tests. Each test consists of two lines. The first line of the test contains an integer n - number of vertices of original n-gon. Second line of the test lists n integers a1, a2, ..., an - number of points marked on each side.

      Constraints

      1 <= t <= 20
      4 <= n <= 1000
      1 <= ai <= 100

      Output

      For each test, print out the answer to the problem modulo 1000000007.

      Example

      Input:
      3
      4
      2 2 2 2
      5
      2 2 2 2 2
      5
      10 20 30 40 50
      
      Output:
      56
      210
      16207125
      
      

      Added by:Spooky
      Date:2010-03-12
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      6340. ZUMA

      Problem code: ZUMA

      One day Mirko, while he was walking through the high grass, stumbled upon a sequence of N colored marbles. Soon he noticed that if he touches K or more consecutive marbles of the same color, they start to twinkle and then he could wish them to magically vanish, although he doesn't have to do that immediately (see 2. sample). Fortunately, Mirko brought an inexhaustible supply of marbles from home, so he can insert a marble of any color
      anywhere in the array (at the beginning, between any two existing marbles, or at the end). Help Mirko find the smallest number of marbles he must insert into the sequence before he could make all of the marbles vanish

      Input

      The first line of input contains two integers N (1 ≤ N ≤ 100) and K (2 ≤ K ≤5) - the number of marbles in the initial sequence and the minimal number of consecutive marbles of the same color he could wish to vanish. The next line contains exactly N integers between 1 and 100 (inclusive),separated by one space. Those numbers represent colors of marbles in the sequence Mirko found.

      Output

      The output should contain only one line with a single integer number - the minimal number of marbles Mirko has to insert to achive the desired effect.

      Example

      Input:
      2 5
      1 1
      Output:
      3

      Input
      10 4
      3 3 3 3 2 3 1 1 1 3

      Output:

      4

      Added by:Phan Công Minh
      Date:2010-03-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:COCI 2009-1010









      SPOJ Problem Set (classical)

      6356. Rock-Paper-Scissors-Lizard-Spock

      Problem code: RPSSL

      Daniel enjoys watching TV series. One of his favorite is "The Big Bang Theory". The main characters of this series are: Sheldon – genius theoretical physicist, his friend Leonard – talented experimental physicist, their attractive, blonde neighbor Penny, and also their friends an aerospace engineer Howard and a particle astrophysicist Rajesh.
      One time Rajesh tells Sheldon:
      “I'll tell you what. How about we go rock-paper-scissors?”
      “Ooh”, – Sheldon replies – “I don't think so. Anecdotal evidence suggests that in the game of rock-paper-scissors, players familiar with each other will tie 75 to 80% of the time due to the limited number of outcomes. I suggest rock-paper-scissors-lizard-Spock”.
      “What?”
      “It's very simple. Scissors cuts paper. Paper covers rock. Rock crushes lizard. Lizard poisons Spock. Spock smashes scissors. Scissors decapitates lizard. Lizard eats paper. Paper disproves Spock. Spock vaporizes rock. And as it always has, rock crushes scissors”.
      “Okay, I think I got it”.
      And the friends decided to play rock-paper-scissors-lizard-Spock. And we would determine what the probability that Rajesh beats Sheldon in this game. We know the probabilities that any of the friends choose any object in the game. Also we know that they play till two wins, so the winner of the game is the person who first wins two rounds.

      Input

      The first line of input contains the number t - the number of tests. Next comes the description of t tests. Each test case consists of two lines. The first line contains five integers RR, RSc, RP, RL, RSp – the probabilities that Rajesh chooses rock, scissors, paper, lizard or Spock respectively. The second line contains five integers SR, SSc, SP, SL, SSp – the probabilities that Sheldon chooses rock, scissors, paper, lizard or Spock respectively. (Note: the order of the objects in the input is rock, scissors, paper, lizard, Spock. The original problem is in Russian and we have scissors before paper in Russian variant of the game. Otherwise the rules are the same.)

      Constraints

      1 <= t <= 500
      0 <= RR, RSc, RP, RL, RSp <= 100, RR + RSc + RP + RL + RSp = 100
      0 <= SR, SSc, SP, SL, SSp <= 100, SR + SSc + SP + SL + SSp = 100

      Output

      For each test case print the probability that Rajesh beats Sheldon in percent rounded to the nearest integer.

      Example

      Input:
      2
      10 20 30 40 0
      10 10 10 10 60
      20 20 20 20 20
      20 20 20 20 20
      
      Output:
      66
      50
      
      

      Added by:Spooky
      Date:2010-03-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Advancement Spring 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      6377. Two Array Problem

      Problem code: SAMTWARR

      You are given two arrays each of length N(1 <= N <= 100000) which are initially filled with zeros. You have to apply M (1 <= M <= 100000) queries of three kind: 

      0 arr left right :  calculate and output sum of elements from left to right in array arr (arr = 0 -- first array, arr = 1 -- second     array); 
      1 arr idx newValue : change value of element at index idx of array arr on newValue;
      2 left right :  swap range of elements of two arrays from left to right ( for i = left to right do swap(a[i], b[i]) );

      Input

      The first line of input contains two integers - N, M. The folowing M lines contains information about queries.
      On each query - one line:
      First integer number cmd contains 0, 1 or 2 (type of query described above).
      if cmd equals 0, then following 3 integers arr, left, right - 0 <= arr <= 1, 0 <= left <= right <= N - 1.
      if cmd equals 1, then following 3 integers arr, idx, newValue - 0 <= arr <= 1, 0 <= idx <= N - 1, -10000 <= newValue <= 10000.
      if cmd equals 2, then following 2 integers left, right - 0 <= left <= right <= N - 1.

      Output

      On each query with cmd equals 0 you should output corresponding value described above.

      Example

      Input:
      5 10
      1 0 0 1
      1 1 4 2
      0 0 0 4
      0 1 0 4
      2 0 0
      0 0 0 4
      0 1 0 4
      2 0 4
      0 0 0 4
      0 1 0 4

      Output:
      1
      2
      0
      3
      3
      0


      Added by:rajeshsr
      Date:2010-03-21
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:https://www.spoj.pl/users/cmd/









      SPOJ Problem Set (acm)

      6408. Counting Triangles 2

      Problem code: KKKCT2

      This is a new version of problem CT with the new limit: X,Y<=10000, and the result will be written in modulo 2009

      Input

      The input begins with C – number of test cases.
      Each test case consists of X, Y.

      Output


      For each test case, output the result in a line.

      Limit

      C <= 200
      0 <= X, Y <= 10000

      Example

      Input:
      2
      0 3
      1 1

      Output:
      0
      4

      Added by:Alex, DE & Friends
      Date:2010-03-26
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:From CT problem









      SPOJ Problem Set (classical)

      6450. PP numbers

      Problem code: MB1


      PP numbers are prime numbers and palindromes in decimal notation at once. Your task is to find n-th PP number in ascending order. Then calculate product of its non-zero digits - let's call it m - and find m-th prime number in ascending order.

      Input

      In the first line of input there is one positive integer Z (1 ≤ Z ≤ 1000) which states the number of test cases. Following Z lines contain test cases.

      Each test case consists of one positive integer n (1 ≤ n ≤ 113) which states the number of PP number to find.

      Output

      For each test case print in separate line two numbers: n-th PP number and m-th prime number.

      Example

      Input:

      3
      1
      5
      2
      

      Output:

      2 3
      11 2
      3 5
      

      Added by:Maciej Boniecki
      Date:2010-04-02
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:2nd Warsaw School of Computer Science Programming Championship









      SPOJ Problem Set (classical)

      6470. Finding the Kth Prime

      Problem code: TDKPRIME

      The problem statement is really simple. There are some queries. You are to give the answers.

      Input

      An integer stating the number of queries Q(equal to 50000), and Q lines follow, each containing one integer K between 1 and 5000000 inclusive.

      Output

      Q lines with the answer of each query: the Kth prime number.

      Example

      Input:
      8
      1
      10
      100
      1000
      10000
      100000
      1000000
      
      Output:
      2
      29
      541
      7919
      104729
      1299709
      15485863
      

      Added by:Alfonso2 Peterssen
      Date:2010-04-06
      Time limit:10s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ASM BF CLPS LISP sbcl LISP clisp ERL HASK ICON ICK JAR JS LUA NEM NICE CAML PHP PIKE PRLG SCALA SCM guile SCM qobi ST TCL WSPC
      Resource:Thanks to TDuke









      SPOJ Problem Set (classical)

      6471. Printing some primes

      Problem code: TDPRIMES

      The problem statement is really simple. You are to write all primes less than 10^8

      Input

      There is not input

      Output

      To make the problem less output related write out only the 1st, 101st, 201st, ... 1st mod 100.

      Example

      Input:
      
      Output:
      2
      547
      1229
      ...
      99995257
      99996931
      99998953
      
      

      Added by:Alfonso2 Peterssen
      Date:2010-04-06
      Time limit:10s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ASM BF CLPS LISP sbcl LISP clisp ERL HASK ICON ICK JAR JS LUA NEM NICE CAML PHP PIKE PRLG SCALA SCM guile SCM qobi ST TCL WSPC
      Resource:Thanks to TDuke









      SPOJ Problem Set (classical)

      6477. Bowling

      Problem code: BOWLING1


      It is well known that programmers enjoy bowling. Bowling is a competitive sport in which a player (the “bowler”) rolls a bowling ball down a wooden or synthetic lane with the objective of scoring points by knocking down as many pins as possible.

      For a beginner, scoring is probably the part of bowling which people find hard to understand. Fortunately, but it is not as hard as it seems.

      As most bowling centers have a scoring computer, you do not usually have to score yourself. I am sure that this makes people lazy and there are probably some regular bowlers who would not be able to score manually if they had to. One day, when it all breaks down, or you are needed to correct a mistake (yes, computers do make mistakes sometimes), an understanding of the scoring rules are necessary.

      The most difficult part of bowling scoring to comprehend is when a strike or spare is scored, as the score on the scorecard does not get updated immediately.

      A game consists of ten frames, which start with a full rack of ten pins. In each frame, you have two deliveries of your ball, in which to knock down as many of the ten pins as you can.

      If you knock down all the pins on your first ball, it is called a strike. The score doesn't get added on straight away because for a strike, you get the values of your next two balls as a bonus. For example, if you score a strike in the first frame, then an 7 and 1 in the second frame, you would score 18 (10+7+1) for the first frame, and 8 for the second frame, making a total of 26 after two frames. If you knock down some of the pins on the first ball, and knocked down the remainder of the pins in the second ball, it is known as a spare. Again, the score doesn't get added on straight away because for a spare, you get the values of your next ball as a bonus. For example, you if score a spare in the first frame, say an 6 and a 4, then got an 8 and a 1 in the second frame, you would score 18 (6+4+8) for the first frame, and 9 for the second frame, making a total of 27 after two frames.

      When it comes to the final frame, it is slightly different. In the final frame, you get bonus balls if you strike or spare, to a maximum of three deliveries. If you strike in the first delivery you have the opportunity to strike in the remaining two and have three deliveries in total. If you scored strikes in each of your final three deliveries, the score for the final frame would be 30 (10+10+10). If you spare the final frame, you get the third delivery as a bonus. So, a spare, 9 and 1, followed by a strike would equal 20 (9+1+10).

      You have to write a program which will calculate the score the player gets for the game given the information about the pins knocked down after each delivery of the ball.

      Input

      The first line of the input contains number t <= 1000 – the amount of test cases. Then the description of each of t test cases follow one per line. Each test case consists of several integers 0 <= a <= 10 – the amount of pins knocked down after each delivery of the ball. Each test case describes a full game for one player. All the games in the input file are correct.

      Output

      For each test case output the number of points the player gets in a game on a separate line.

      Example

      Input:
      3
      10 10 10 10 10 10 10 10 10 10 10 10
      3 5 1 5 7 1 10 1 6 10 6 2 1 2 0 5 8 1
      9 1 5 0 3 0 8 1 6 4 7 2 7 1 6 3 10 4 4
      
      Output:
      300
      89
      101
      
      

      Added by:Spooky
      Date:2010-04-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Open All-Ukrainian Collegiate Contest Semi-Final, 2010









      SPOJ Problem Set (classical)

      6478. Hamster Flight 2

      Problem code: HAMSTER2


      There is a competition of flying hamsters in Hamsterburg. Each competing hamster is thrown from a sling. The initial speed of the hamsters is V0 m/s. Free fall acceleration is g = 10 m/s2. There is no air friction. The size of the hamster and the sling are negligible. When the hamster is thrown from the sling its altitude is 0 meters. There is a number of vertical gates in the air. Each gate has a lower and an upper bound. If we mark the points directly under each of the gates on the ground – those points are positioned in one line and on one side from the starting point. A hamster gets as many points as the amount of gates he flies through. You have to calculate the maximal amount of points that a hamster can get in one flight. It is considered that a hamster flies through the gate if he touches the bounds of the gate during the flight or flies between the bounds.

       

      Input

      The first line of the input contains number 0 < t <= 10 the amount of test cases. The description of each test case follows. Each test starts with two integers 0 < V0 <= 1000 – the initial speed of the hamster ans 0 < n <= 20000 – the total amount of gates. Each of the next n lines contains the description of one of the gates: three integers 0 < x <= 10000 – the distance from the starting point to the point directly under the gate, 0 < y1 <= y2 <= 10000 – lower and upper bound of the gate.

      Output

      For each test case output the maximal amount of gates a hamster can fly through in one flight on a separate line.

      Example

      Input:
      3
      10 2
      3 1 2
      3 2 3
      10 3
      1 1 1
      2 2 3
      3 4 6
      10 3
      1 1 2
      2 3 4
      3 5 6
      
      Output:
      2
      1
      2
      
      

      Added by:Spooky
      Date:2010-04-09
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Open All-Ukrainian Collegiate Contest Semi-Final, 2010









      SPOJ Problem Set (classical)

      6479. The Very Greatest Common Divisor

      Problem code: VGCD

      Given two integers a and b find their greatest common divisor.

      Input

      The first line of the input file contains number 0 < n < 1000 the amount of tests. The description of n test cases follow. The description of a test case consists of two lines. The first line contains integer a (0 < a < 10^12540), the second – integer b (0 < b < 10^12540). It is also known that all the numbers in the input file are the determinants of the square matrix of the form:

      Output

      For each test case print the greatest common divisor of integers a and b on a separate line.

      Example

      Input:
      3
      2
      3
      3
      21
      6765
      610
      
      Output:
      1
      3
      5
      
      

      Added by:Spooky
      Date:2010-04-09
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Open All-Ukrainian Collegiate Contest Semi-Final, 2010









      SPOJ Problem Set (classical)

      6488. Printing some primes (Hard)

      Problem code: PRIMES2

      The problem statement is really simple (the constraints maybe not). You are to write all primes less than 10^9

      Input

      There is not input

      Output

      To make the problem less output related write out only the 1st, 501st, 1001st, ... 1st mod 500.

      Example

      Input:
      
      Output:
      2
      3581
      7927
      ...
      999978527
      999988747
      999999151
      

      Added by:Alfonso2 Peterssen
      Date:2010-04-09
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:Thanks to TDuke









      SPOJ Problem Set (classical)

      6489. Finding the Kth Prime (Hard)

      Problem code: KPRIMES2

      The problem statement is really simple (the constraints maybe not). There are some queries. You are to give the answers.

      Input

      An integer stating the number of queries Q(equal to 100000), and Q lines follow, each containing one integer K between 1 and 50000000 inclusive.

      Output

      Q lines with the answer of each query: the Kth prime number.

      Example

      Input:
      8
      1
      10
      100
      1000
      10000
      100000
      1000000
      10000000
      
      Output:
      2
      29
      541
      7919
      104729
      1299709
      15485863
      179424673
      
      

      Added by:Alfonso2 Peterssen
      Date:2010-04-09
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PAS gpc
      Resource:Thanks to TDuke









      SPOJ Problem Set (classical)

      6499. Breaking Chocolates

      Problem code: BCHOCO

      Bored of setting problems for Bytecode, Venkatesh and Akhil decided to take some time off and started to play a game. The game is played on an R*C bar of chocolate consisting of Black and White chocolate cells. Both of them do not like black chocolate, so if the bar consists only of black chocolate cells, it is discarded (Discarding the bar is not considered as a move). If the bar consists only of white chocolate cells, they do not break it further and the bar can be consumed at any time (Eating the bar is considered as a move). If the bar consists of both black and white chocolate cells, it must be broken down into two smaller pieces by breaking the bar along any horizontal or vertical line (Breaking the bar is considered as a move). The player who cannot make a move on any of the remaining bars loses.

      Assuming Venkatesh starts the game and both players are infinitely intelligent, determine who wins the game.

      Input

      The first line of input contains a number 't', the number of test cases.

      For each testcase, first line contains two space separated integers 'R' and 'C'. The following R lines contain C space separated integers which are either 0 (White) or 1 (Black).

      Output

      For each testcase output “Venkatesh wins” or “Akhil wins” (quotes for clarity).

      Example

      Input:
      4

      3 3

      0 0 0

      0 0 0

      0 0 0

      3 3

      1 1 1

      1 1 1

      1 1 1

      1 2

      1 0

      3 3

      1 0 1

      0 1 0

      0 0 1

      Output:

      Venkatesh wins

      Akhil wins

      Akhil wins

      Venkatesh wins

      Explanation:

      Case 1: Venkatesh can win in one move by eating all the 0's, which is the only move possible.

      Case 2: The initial bar consists only of Black chocolate cells, so it has to be discarded. So no move is possible in the game.


      Case 3: Venkatesh is forced to cut the bar into two. Now Akhil can eat the White chocolate cell and the black cell is discarded.


      Constraints:

      t <= 25

      1 <= R, C <= 30


      Added by:suhash
      Date:2010-04-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ByteCode 2010









      SPOJ Problem Set (classical)

      6500. Counting Diameter

      Problem code: DCOUNT


      Given an integer 'K', construct a set 'S' containing all integers from 1 to 2*K-1 (both inclusive). Construct a graph 'G' with vertices represented by all the K-1 element subsets of 'S'. There is an  edge from vertex 'u' to vertex 'v' in 'G', if the corresponding subsets of 'u' and 'v' do not have any element in common. The distance d(u,v) between a vertex 'u' to a vertex 'v' is defined as the shortest path from 'u' to 'v' in 'G'. The diameter of 'G' is defined as the longest distance between any two vertices in 'G'. Output the diameter of the graph and the number of pairs of vertices which have distance equal to the diameter.

      Input

      The first line of input contains a number 't', the number of test cases.

      Each of the following 't' lines contains an integer 'K'.

      Output

      For each testcase output two space separated integers, the diameter and the number of pairs. Since the numbers can be huge, output all the numbers modulo 1,000,000,007.

      Example

      Input:

      2

      2

      3

      Output:

      1 6

      2 60
      Explanation:

      For Case 1:

      The graph is a triangle, so  the diameter is 1 and the distance between any 2 pairs of different  vertices is 1. The 6 pairs are: ({1},{2}), ({2},{1}), ({1},{3}),({3},{1}),  ({2},{3}), ({3},{2}).

      Constraints:

      t <= 25

      2 <= K <= 100,000


      Added by:suhash
      Date:2010-04-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ByteCode 2010









      SPOJ Problem Set ()

      6503. Travelling Salesman Again !

      Problem code: TSPAGAIN

      There are N cities numbered from 0..N-1. A salesman is located at city 0. He wishes to visit all cities exactly once and return back to city 0. There are K toll booths. Each toll booth has a certain range of functioning. The parameters for toll k are given as x_k and y_k. If the salesman travels from city i to j, he has to pay 1 dollar toll fee to each toll p having x_p >= i and y_p <= j. Calculate the cheapest way for the salesman to complete his tour.


      Input :

      The first line contains T the number of test cases. T test cases follow. The first line of each test case contains two space seperated integers N and K. Each of the next K lines contains 2 integers, the ith line containing x_i and y_i (0 <= x_i,y_i < N). A blank line seperates two test cases.


      Output :

      Output T lines, one for each test case, containing the required answer.


      Sample Input :

      2
      3 2
      2 0
      0 2

      3 4
      1 0
      2 1
      0 1
      1 2

      Sample Output :

      3
      6

      Constraints :

      1 <= T <= 50
      2 <= n <= 1000
      1 <= K <= 10000


      Added by:Varun Jalan
      Date:2010-04-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:own problem used for Codechef APRIL10 contest









      SPOJ Problem Set (classical)

      6517. Farmer Sepp

      Problem code: JOCHEF

      Chief Farmer Josef aka Sepp needs to crop hay several times through the summer. Due to high petrol costs he can currently use his truck exactly once to drive to a spot where he will harvest the dried grass. Lazy by nature, John does not want to harvest those parts of the field which contain cows, since this would involve too much energy. Furthermore, John just crops a rectangular part of the field.

      Input

      Input contains multiple test cases. You are given three integers M,N,F (0<M,N<=4000), (0<=F<=1000000) which describe the size of the field (M rows, N columns, F unit area of such a field). Then follows the actual map which consists of M lines, each line containing N times the letters 'H' or 'C' standing for "Hay" or "Cow". Input terminates with M=N=0.

      Output

      Print the size of the largest field, which "Sepp" would harvest.

      Example

      Input:
      9 10 1
      CHCHHHCCCC
      CCHCHCHHHC
      CCHCHHCCCC
      CHHHHHCHHH
      CHCHHHCCCH
      CCCCHHHCHH
      HHHCCHCCCC
      HCHHHHCCCH
      CHHCCCCHHC
      0 0
      
      Output:
      8

      Added by:Josef Ziegler
      Date:2010-04-15
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Josef Ziegler









      SPOJ Problem Set (classical)

      6556. N DIV PHI_N

      Problem code: NDIVPHI

      Given an integer N <= 1040 find the smallest m <= N such that m/phi(m) is maximum.

      Input

      N1
      N2
      .
      .
      .
      N20

      Output

      m1
      m2
      .
      .
      .
      m20

      Example

      Input:
      10
      .
      .
      Output:
      6
      .
      .

      Added by:Frank Rafael Arteaga
      Date:2010-04-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ProjectEuler









      SPOJ Problem Set (classical)

      6560. N DIV PHI_N (Hard)

      Problem code: NDIVPHI2


      Given an integer N <= 1025000 find the smallest m <= N such that m/phi(m) is maximum. Where phi is euler's totient function.

      Input

      The first line in the input gives the number of test cases T (T<=200), and then T lines follow each containing an integer N.

      Output

      Output the smallest required value of m.

      Example

      Input:
      1
      10

      Output:
      6


      Added by:SALVO
      Date:2010-04-23
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ F# GO NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SED
      Resource:Frank Rafael Arteaga









      SPOJ Problem Set (classical)

      6562. Esferas

      Problem code: PRUBALL


      Balls

      The classic Two Glass Balls brain-teaser is often posed as: "Given two identical glass spheres, you would like to determine the lowest floor in a 100-story building from which they will break when dropped. Assume the spheres are undamaged when dropped below this point. What is the strategy that will minimize the worst-case scenario for number of drops?" Suppose that we had only one ball. We'd have to drop from each floor from 1 to 100 in sequence, requiring 100 drops in the worst case. Now consider the case where we have two balls. Suppose we drop the first ball from floor n. If it breaks we're in the case where we have one ball remaining and we need to drop from floors 1 to n-1 in sequence, yielding n drops in the worst case (the first ball is dropped once, the second at most n-1 times). However, if it does not break when dropped from floor n, we have reduced the problem to dropping from floors n+1 to 100. In either case we must keep in mind that we've already used one drop. So the minimum number of drops, in the worst case, is the minimum over all n. You will write a program to determine the minimum number of drops required, in the worst case, given B balls and an M-story building.

      Input

       The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set consists of a single line containing three (3) decimal integer values: the problem number, followed by a space, followed by the number of balls B, (1 ≤ B ≤ 50), followed by a space and the number of floors in the building M, (1 ≤ M ≤ 1000).

       Output

       For each data set, generate one line of output with the following values: The data set number as a decimal integer, a space, and the minimum number of drops needed for the corresponding values of B and M.

      Sample Input

      4

      1 2 10

      2 2 100

      3 2 300

      4 25 900

      Sample Output

      1 4

      2 14

      3 24

      4 10


      Added by:Alvaro Javier Medina Balboa
      Date:2010-04-23
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      6576. Divide and Conquer

      Problem code: DIVCON


      Anne and Brenda found some cookies scattered on the lattice points in the 2D coordinate system. They agreed to divide them in the following manner.

      First, Anne draws a vertical line (that is, a line with the equation x = c, for any real number c) somewhere in the plane. Then Brenda draws a horizontal line (y = d) somewhere in the plane. Now they have divided the plane in four quadrants.

      Anne gets all the cookies lying in the upper right and the lower left quadrant, and Brenda gets all the cookies lying in the upper left and the lower right quadrant. Cookies which lie on the vertical or the horizontal line are ignored.

      Anne's goal is to maximize the number of cookies she gets, knowing that Brenda plays optimally (in order to maximize her number of cookies).

      Input

      In the first line of input there is an integer T (1 ≤ T ≤ 600), the number of test cases.

      Each test case starts with an integer N (1 ≤ N ≤ 1000), the number of cookies. In the next N lines there are coordinates (Xi, Yi) of the cookies, integers in the interval [1, 1000]. There can be multiple cookies at the same point.

      Output

      For each of the T cases, output in a separate line the maximal number of cookies Anne can surely get.

      Example

      Input:
      2
      5
      1 1
      4 1
      4 5
      5 1
      3 3
      11
      7 10
      7 11
      7 10
      7 11
      6 6
      5 5
      4 8
      1 5
      1 6
      1 4
      7 1
      Output: 2
      5

      Added by:Stjepan Glavina
      Date:2010-04-26
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: NODEJS PERL 6
      Resource:authors: Filip Pavetiæ, Adrian Satja Kurdija









      SPOJ Problem Set (classical)

      6578. Segment Tree

      Problem code: SEGTREE

      It was Arbor Day. Alice implemented an RB-tree, Bob composed a segment tree, I made a binary tree - we all have a bright outlook.

      Lambda is always making mistakes while implementing segment trees (See his history of submissions). He then decides to draw a "segment tree". He puts n points on a plane, link certain pairs of them to form segments and all the segments form a tree. As a normal tree, it satisfies the following conditions:

      1. Consider points as vertices, segments as edges, it forms a rooted tree.
      2. Each node u is strictly higher than its parent, namely yu > yparent_of_u.
      3. Segments may only intersect on their endpoints.

      Lambda wants to minimize the total length of segments. The tree can be rotated to satisfy above conditions.

      Input

      First line of input contains single integer n (1 ≤ n ≤ 500).
      Next n lines each contain two integers xi, yi denoting the coordinate of i-th point (0 ≤ xi, yi ≤ 1000). Points are distinct.

      Output

      The one and only line contains a real number representing the minimum length.
      Your answer must be rounded up to 4 digits after the decimal point.

      Example 1

      Input:
      6
      0 1
      1 0
      2 1
      4 1
      5 0
      6 1

      Output:
      7.6569

      Illustration:
      sample1

      Example 2

      Input:
      10
      0 0
      0 1
      1 2
      2 3
      1 4
      3 4
      -1 2
      -2 3
      -1 4
      -3 4

      Output:
      12.3137

      Illustration:
      sample1
      This is just a sample test case. There's no negative in the real test data.

      Added by:Lox
      Date:2010-04-27
      Time limit:1s-3.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own problem. Description by Lambda









      SPOJ Problem Set (classical)

      6622. Islands and Hotel Chains

      Problem code: HCHAINS

      In Croatia there are N small islands. For the purposes of further tourism development, the government has decided to build exactly one hotel on the each island. The government has contracts with two hotel chains: let's call them A and B. Unfortunately, there is a problem since each hotel chain wants to build as many hotels as possible.

      Thus, the following agreement has been made: the hotels will be built such that, for each horizontal or vertical line (that is, if we imagine the problem in the 2D coordinate system, for each line with the equation y = c or x = c), the absolute difference between the number of hotels (on that line) of the chain A and the number of hotels (on that line) of the chain B is at most 1.

      Write a program that will, for each small island, determine the hotel chain (A or B) which will build the hotel on that island, such that the upper agreement holds.

      Input 

      In the first line of input there is an integer T, the number of test cases.

      For each test case, in the first line there is an integer N, the number of islands.

      In the next line there are eight integers: X(1), Y(1), Ax, Bx, Mx, Ay, By, My; each from the interval [1, 100 000], except for X(1) and Y(1) which are from the interval [0, Mx-1] and [0, My-1], respectively.

      2D coordinates of the i-th island (for 2 ≤ i ≤ N) are:

      X(i) = ( Ax * X(i-1) + Bx ) mod Mx;

      Y(i) = ( Ay * Y(i-1) + By ) mod My.

      It is guaranteed that no two islands will have the same position and the solution, not necessarily unique, will always exist.

      Note: Author's solution doesn't depend on properties of pseudo-random generator.

      Data set is divided into 2 parts:
           First part:     1 <= T <= 100, 1 <= N <= 5000
           Second part: 1 <= T <= 10, 1 <= N <= 100 000

      Output 

      For each test case, output in a separate line a string of size N, containing only the letters A and B. The i-th letter of the string denotes the hotel chain which will build the hotel on the i-th island.

      Example 

      Input:

      1
      10
      2 4 8 2 5 6 9 5


      Output:

      AAAABBBBBA

       

      The points in this example are:

      2 4
      3 3
      1 2
      0 1
      2 0
      3 4
      1 3
      0 2
      2 1
      3 0


      Added by:Ivan Kataniæ
      Date:2010-05-07
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:derived from the problem of International Mathematical Olympiad. prepared by I. Kataniæ, A. S. Kurdija and S. Glavina









      SPOJ Problem Set (classical)

      6624. Snowball Game

      Problem code: SNOWGAME


      Farmer John's N (1 <= N <= 1018) cows went for a trip around the world. Now they are at the North Pole. They decided to play a snowball game. Each of the cows made one snowball. As it is known, heavier snowballs make more harm. FJ is sure that cows' snowballs are of the same weight except one snowball, which is heavier. FJ has one balance scale. With it he can know which of two snowball groups is heavier. Snowballs get damaged when weighed, so each snowball can take part in a weighing at most K (1 <= K <= 10000) times. Help FJ find the minimal number of weighings after which he can find the heaviest snowball.

      Input

      The only line of input file contains numbers N and K.

      Output

      The only line of output file contains minimum number of weighings.

      Example

      Input:
      19 2
      Output:
      3

      Added by:Hayk Saribekyan
      Date:2010-05-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ F# GO NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SED
      Resource:RAU School Contest 2010 (Own task)









      SPOJ Problem Set (classical)

      6650. Consecutive sequence

      Problem code: SEQ6


      We define consecutive sequence as a sequence of integer numbers {n, n+1, n+2, ..., n+m}. For each given positive integer N ≤ 107 calculate number of such sequences which sum is equal to N.

      Input

      The input file consists of multiple lines (about 103 in the first data set and 105 in the second), each line contains integer N. The input is terminated with N = 0, which should not be processed.

      Output

      Expected number in each line

      Example

      Input:
      
      500
      0
      
      Output:
      
      8
      

      Added by:Ruslan Sennov
      Date:2010-05-14
      Time limit:9s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: PERL 6









      SPOJ Problem Set (classical)

      6665. Easy Longest Common Substring

      Problem code: ELCS

      In this problem, a string only consists of lowercase letters.

      Substring, is a consecutive sequence of characters occurrences at least once in a string.

      Common substring means a substring of two strings.

      After getting TLE on LCS and LCS2, lqp18_31 felt really depressed. So he came up with an interesting idea. He want to modify the definition of LCS and call it ELCS.

      ELCS: for two given strings s1[0…n-1] and s2[0…m-1], the ELCS of them is a string p[0…k-1]  k<=min(n,m) so that s1[i]=s2[i]=p[i] ( for 0<=i<k ) and s1[k]!=s2[k] or k==n or k==m .

      Now your task is easy.

      You are given N strings and Q queries.

      Each query consists two intergers a and b. You must answer the length of the ELCS of the a-th string and b-th string.

      Input

      Firtst line consists one interger N.

      Next N lines consist N strings.

      Next one line consists one interger Q.

      Next Q lines consist two intergers a and b. (0<=a,b<N)

      30% of the testdata : N<=100 Q<=10000 length(string[i])<=100

      100% of the testdata : the number of total characters<=500000 N<=100000 Q<=100000

      Output

      Q lines. Each line consists the length of the ELCS of the a-th string and b-th string

      Example

      Input:

      5

      dy

      ljq

      lqp

      ws

      jzt

      3

      0 1

      1 2

      0 2

      Output:

      0

      1

      0


      Added by:刘启鹏
      Date:2010-05-18
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:my own problem









      SPOJ Problem Set (classical)

      6678. Load Testing

      Problem code: GCJ101C

      Problem

      Now that you have won Code Jam and been hired by Google as a software engineer, you have been assigned to work on their wildly popular programming contest website.

      Google is expecting a lot of participants (P) in Code Jam next year, and they want to make sure that the site can support that many people at the same time. During Code Jam 2010 you learned that the site could support at least L people at a time without any errors, but you also know that the site can't yet support P people.

      To determine how many more machines you'll need, you want to know within a factor of C how many people the site can support. This means that there is an integer a such that you know the site can support a people, but you know the site can't support a * C people.

      You can run a series of load tests, each of which will determine whether the site can support at least X people for some integer value of X that you choose. If you pick an optimal strategy, choosing what tests to run based on the results of previous tests, how many load tests do you need in the worst case?

      Input

      The first line of the input gives the number of test cases, T. T lines follow, each of which contains space-separated integers L, P and C in that order.

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of load tests you need to run in the worst case before knowing within a factor of C how many people the site can support.

      Limits

      1 ≤ T ≤ 1000.
      2 ≤ C ≤ 10.
      L, P and C are all integers.

      Small dataset

      1 ≤ L < P ≤ 103.

      Large dataset

      1 ≤ L < P ≤ 109.

      Input

      4
      50 700 2
      19 57 3
      1 1000 2
      24 97 2

      Output

      Case #1: 2
      Case #2: 0
      Case #3: 4
      Case #4: 2

      Explanation

      In Case #2, we already know that the site can support between 19 and 57 people. Since those are a factor of 3 apart, we don't need to do any testing.

      In Case #4, we can test 48; but if the site can support 48 people, we need more testing, because 48*2 < 97. We could test 49; but if the site can't support 49 people, we need more testing, because 24 * 2 < 49. So we need two tests.


      Added by:Kumar Anurag
      Date:2010-05-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Google Code Jam 2010 Round 1C









      SPOJ Problem Set (classical)

      6690. A - Comparison Expressions

      Problem code: BOCOMP

      PROBLEM A

      COMPARISON EXPRESSIONS

      Automated Compilers Manufacture, is developing a new, inteligent compiler. One of the problems its scientists are facing is how to determine whether two expressions are equivalent. An expression consists of one or more alphabetic lowercase letters, representing variables, separated by addition and multiplication signs, respectively + and *, totally parenthesized. Recursively, an expression is either a variable, or a string of the form (E1 + E2) or (E1 * E2), where E1 and E2 are both expressions. Examples of expressions: a, (a+b), ((a*b)*b). Examples of non-expressions: ab, a*(b+c).

       

      Two expressions are equivalent if, for every integer assignment to their variables, both expressions assume the same value. For example, ((a+b)*c) and ((b*c)+(c*a)) are equivalent, whereas (a+(b*c)) and ((a+b)*c) are not equivalent. Your task is to write a program that decides whether two given expressions are equivalent.

      Input

      The input contains several test cases, each case consists of one line, containing two expressions separated by precisely one space. The variables of the expressions are represented by lowercase alphabetic letters. The number of occurrences of variables in an expression is at most 20 (for example, ((a+b)*a) has three occurrences of variables). Thus, an expressions consists of at most 77 characters, including variables, parentheses, plus and multiplication signs. The end of the input is indicated by a line containing only one zero.

      Output

      For each test case in the input, your program must print a single line, containing one single character, a Y if the two expressions are equivalent, an N otherwise. 

      Sample Input   

      (a+(b*c)) ((a+b)*c)

      ((a+b)*c) ((c*b)+(a*c))

      0                                            

      Sample Output

      N

      Y


      Added by:Alvaro Javier Medina Balboa
      Date:2010-05-25
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      6691. Picking Up Chicks

      Problem code: GCJ101BB

      A flock of chickens are running east along a straight, narrow road. Each one is running with its own constant speed. Whenever a chick catches up to the one in front of it, it has to slow down and follow at the speed of the other chick. You are in a mobile crane behind the flock, chasing the chicks towards the barn at the end of the road. The arm of the crane allows you to pick up any chick momentarily, let the chick behind it pass underneath and place the picked up chick back down. This operation takes no time and can only be performed on a pair of chicks that are immediately next to each other, even if 3 or more chicks are in a row, one after the other.

      Given the initial locations (Xi) at time 0 and natural speeds (Vi) of the chicks, as well as the location of the barn (B), what is the minimum number of swaps you need to perform with your crane in order to have at least K of the N chicks arrive at the barn no later than time T?

      You may think of the chicks as points moving along a line. Even if 3 or more chicks are at the same location, next to each other, picking up one of them will only let one of the other two pass through. Any swap is instantaneous, which means that you may perform multiple swaps at the same time, but each one will count as a separate swap.

      Input

      The first line of the input gives the number of test cases, CC test cases follow. Each test case starts with 4 integers on a line -- NKB and T. The next line contains the Ndifferent integers Xi, in increasing order. The line after that contains the N integers Vi. All distances are in meters; all speeds are in meters per second; all times are in seconds.

      Output

      For each test case, output one line containing "Case #x: S", where x is the case number (starting from 1) and S is the smallest number of required swaps, or the word "IMPOSSIBLE".

      Limits

      1 ≤ C ≤ 100;
      1 ≤ B ≤ 1,000,000,000;
      1 ≤ T ≤ 1,000;
      0 ≤ Xi < B;
      1 ≤ Vi ≤ 100;
      1 ≤ N ≤ 50;
      0 ≤ K ≤ N;

      All the Xi's will be distinct and in increasing order.

      Example

      Input:
      3
      5 3 10 5
      0 2 5 6 7
      1 1 1 1 4
      5 3 10 5
      0 2 3 5 7
      2 1 1 1 4
      5 3 10 5
      0 2 3 4 7
      2 1 1 1 4 Output: Case #1: 0
      Case #2: 2
      Case #3: IMPOSSIBLE

      Added by:Mohammad Kotb
      Date:2010-05-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: JS
      Resource:Google Code Jam 2010









      SPOJ Problem Set (classical)

      6692. B - Esperanto Lessons

      Problem code: BOLESSON

      Problem B

       Esperanto Lessons

      In a Latin American high school the directors had decided to implement esperanto lessons, because they have observed many of their students started studying the universal language on their own. Because of this, all kids have really different levels before the courses are implemented. The directors decided to implement two levels: basic and advanced. Because of bureaucracy, they cannot put students of different divisions in the same English course. Also, to be fair, the basic and advanced levels have to be equal among all divisions of the school.

      Therefore, each division will be partitioned in two subgroups, one for the basic level and one for the advanced level (note that it is possible that a division does not contain any students in one of the levels). To determine the levels, an Esperanto test has been taken by all students of all division, each getting a grade between 0 and 1000, inclusive. To accomplish their mentioned goals, the directors have decided that all students with a score greater than or equal to T will be assigned the advanced level and all students with a score less than T will be assigned the basic level.

      However, they cannot decide on the best value of T. They decided to choose the value that better splits all divisions. For this, they have come up with a metric: They want the value of T that minimizes the accumulated difference. That is, the sum of the difference of the number of students in the two groups (basic and advanced) within each division.

      Input

      Each test case will be given in several lines. The first line contains a single integer N (1<= N<= 106), the number of divisions in the school. 2N lines follow, with each division being described in 2 consecutive lines. The first line of each group of two contain a single integer K (1<=K<=106) the number of people on the division. The second line contains K integers separated by single spaces with the scores of each of the students in the division. The scores will all be between 0 and 1000, inclusive. Total number of students within each test case (that is, the sum of the values of all K lines) will not be greater than 106.

      Output

      For each test case, output a single line with a single integer representing the value of the accumulated difference if T is chosen optimally.

      Sample Input

      2

      2

      1 2

      2

      3 4

      2

      2

      1 4

      2

      2 3

      3

      4

      1 10 100 1000

      3

      5 55 555

      5

      4 16 64 256 1000

      1

      4

      500 500 500 500

      -1

      Sample Output

      2

      0

      2

      4


      Added by:Alvaro Javier Medina Balboa
      Date:2010-05-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      6693. C - Karaoke

      Problem code: BOKO

      PROBLEM C

       KARAOKE

      “But I sing awfully!” - Gonzo kept saying. “Come on! Nobody cares, it just for fun!” – was the common reply of his friends. “And we’ll give you all our support!”. But Gonzo was not convinced. Although he was an accomplished shower singer, he didn’t like to do it in public. He had played karaoke games before and his problems were always the same: he could pronounce the words and keep a note very well, but typically it was not the right one, and not at the correct time. That’s why in these games his scores were always poor.

      But there was something in his pocket to save the day. He had a friend who just came from a programming contest and had given him a pendrive with the solution: A Corrector for Music (ACM), a program that can adjust the notes that the game detects, so that he could achieve the a better score. Gonzo was relieved. For once he wouldn’t be the worst singer of the group. Now he had just to use the program properly. The karaoke game displays a screen with several horizontal bars, representing words of the song, at different heights over a time axis. The y-coordinate of each bar indicates the pitch of that word. This is, the note that the game expects to detect from the singer. The game receives the voice of the singer from the microphone, and detects the pitch and the time interval where the note was detected. By comparison with the original song, the game displays a new set of horizontal bars in the same graph of the originals, and calculates the score according to the following rules:

      • The singer starts the game with 0 points.

      • If the song pitch and the singer pitch coincides, the singer wins 100 points by each second that the coincidence continues.

      • If the song pitch and the singer pitch differ, the singer loses the absolute difference between the pitches each second that such difference exists.

      • If there is no song pitch, but the singer sings; or inversely, if there is a song pitch, but the singer doesn’t make a sound, the singer loses 100 points each second that this happens.

      • While there is no song pitch, and no input from the microphone, the score remains the same.

      ACM modifies the pitch of all the singer words by adding an integer to all of them. There is no possibility of modifying just an specific part of the singer’s notes. The pitch is always a positive number. If by any chance a pitch number drops to zero or less, the game interprets that no sound has been received. The program can also delay the time when the song begins or the time when the singer’s voice begins to be read, by adding an integer number of seconds in order to better adjust the intervals. The figure shows an example with the song words (solid lines) and the singer’s words (dashed lines).

      Figura1

      You will receive the details of the song that is stored in the game, and the words detected by the microphone. With that information you must determine the maximum possible score that can be obtained by adjusting the pitch of the singer’s words, and delaying the song or the voice.

      Input

      The input contains several test cases. The first line of a test case contains one integer N indicating the number of words that are included in the song (1<=N<=200). Each of the next N lines contain six integers si1, fi1, pi1, si2, fi2 and pi2. The first three of those integers represent the continuous interval of time [si1, fi1), where the word i must be sung with pitch pi1. The following three integers represent the continuous interval [si2, fi2), where the word i of the singer is detected with pitch pi2. For all cases, 0 < si1 < fi1, 0 < si2 < fi2, 20 < pi1, pi2 < 120. The end of input is indicated by a line containing only one zero.

      Output

      For each test case in the input, your program must print a single line, containing the maximum score that can be achieved in the game by using the ACM program. 

      Sample Input

      1

      1 4 60 6 9 70

      1

      1 4 60 6 8 70

      2

      0 2 50 1 3 40

      3 6 80 4 7 60

      0

      Sample Output

      300

      100

      280


      Added by:Alvaro Javier Medina Balboa
      Date:2010-05-25
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      6694. D - Playing with Marbles

      Problem code: BOMARBLE

      PROBLEM D

       PLAYING WITH MARBLES

      Pablo was assigned in his class to construct pentagons inside pentagons with marbles but he doesn’t know how many marbles he will need. He knows that for one pentagon he needs 5 marbles

      Imagen2 

      The only way he knows to insert a second pentagon is putting a marble in the middle of each segment and drawing three lines as shown. He puts a marble in the intersecting lines and removes them. To insert a third pentagon inside he first divides all segments in two including the ones that are not needed, and repeats the procedure. Drawing a second pentagon will require 12 marbles. A third pentagon will require 22 marbles. Given the information of how many pentagons will be created, write a program to calculate the number of marbles needed.

      Input

      The input contains several test cases. Each test case contains one integer N indicating the number of pentagons to create (1<=N<=103). The end of input is indicated by a line containing only one zero.

      Output

      For each test case in the input, your program must print a single line, containing one single integer, the number of marbles required. 

      Sample Input

      1

      2

      3

      0

      Sample Output

      5

      12

      22


      Added by:Alvaro Javier Medina Balboa
      Date:2010-05-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      6695. E - Publish of Perish

      Problem code: BOPERISH

      PROBLEM E

       PUBLISH OF PERISH

      “Publish or perish” is the academic life’s fundamental motto. It refers to the fact that publishing your work frequently is the only way to guarantee access to research funds, bright students and career advances. But publishing is not enough. It is necessary that your work is referenced (or cited). That is, your papers must be mentioned as source of information in other people’s publications, to attest the quality and relevance of your research. The more citations a paper receives from other authors, the more it is considered influential.

      In 2005 Jorge E. Hirsch, a physicist at the University of California at San Diego, proposed a way to evaluate the scientific impact of a researcher, based on the citations his or her papers have received. The h-index, as Hirsch’s proposal became known, is a number based on the set of a researcher’s most cited papers. It is defined in Hirsch’s own words as: A scientist has index h if h of his Np papers have at least h citations each, and the other (Np − h) papers have at most h citations each.

      Albert Einstein, for example, published 319 papers in scientific journals and has an h-index equal to 46. It means 46 of his papers have received 46 or more citations each, and all of his remaining 273 papers have 46 citations or less each. Given the information of how many citations each paper from a given researcher has received, write a program to calculate that researcher’s h-index.

      Input

      The input contains several test cases. The first line of a test case contains one integer N indicating the number of papers a researcher has published (1<=N<=103). The second line contains a list of N integers Mi, separated by one space, representing the number of citations each of the N papers from that author has received (0<=Mi <=103, for 1<= i <= N). The end of input is indicated by a line containing only one zero.

      Output

      For each test case in the input, your program must print a single line, containing one single integer, the h-index for the given list of citations.

      Sample Input

      4

      1003 1 200 2

      10

      1 1 1 0 1 1 0 1 1 1

      7

      6 5 4 3 2 1 0

      0

      Sample Output

      2

      1

      3


      Added by:Alvaro Javier Medina Balboa
      Date:2010-05-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      6700. Make it Smooth

      Problem code: GCJ101AB


      You have a one-dimensional array of N pixels. Each pixel has a value, represented by a number between 0 and 255, inclusive. The distance between two pixels is the absolute difference of their numbers.

      You can perform each of the following operations zero or more times:

      1. With cost D, delete any pixel, so its original neighbors become neighboring pixels.
      2. With cost I, insert one pixel of any value into any position - either between two existing pixels, or before the first pixel, or after the last pixel.
      3. You can change the value of any pixel. The cost is the absolute difference of the old value of the pixel and the new value of the pixel.

      The array is smooth if any neighboring pixels have distance at most M. Find the minimum possible cost of a sequence of operations that makes the array smooth.

      Note: The empty array - the array containing no pixels - is considered to be smooth.

      Input

      The first line of the input gives the number of test cases, T. T test cases follow, each with two lines. The first line is in the form "D I M N", the next line contains N numbers ai: the values of the pixels from left to the right.

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is the minimum cost to make the input array smooth.

      Limits

      All the numbers in the input are integers.
      1 ≤ T ≤ 100
      0 ≤ D, I, M, ai ≤ 255
      1 ≤ N ≤ 100

      Example

      Input:
      2
      6 6 2 3
      1 7 5
      100 1 5 3
      1 50 7
      
      Output:
      Case #1: 4
      Case #2: 17
      

      Added by:Ruslan Sennov
      Date:2010-05-26
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Google Code Jam 2010









      SPOJ Problem Set (classical)

      6706. Making Chess Boards

      Problem code: CT101CC

      The chess board industry has fallen on hard times and needs your help. It is a little-known fact that chess boards are made from the bark of the extremely rare Croatian Chess Board tree, (Biggus Mobydiccus). The bark of that tree is stripped and unwrapped into a huge rectangular sheet of chess board material. The rectangle is a grid of black and white squares.

      Your task is to make as many large square chess boards as possible. A chess board is a piece of the bark that is a square, with sides parallel to the sides of the bark rectangle, with cells colored in the pattern of a chess board (no two cells of the same color can share an edge).

      Each time you cut out a chess board, you must choose the largest possible chess board left in the sheet. If there are several such boards, pick the topmost one. If there is still a tie, pick the leftmost one. Continue cutting out chess boards until there is no bark left. You may need to go as far as cutting out 1-by-1 mini chess boards.

      Here is an example showing the bark of a Chess Board tree and the first few chess boards that will be cut out of it.

       

      Input

      The first line of the input gives the number of test cases, T. T test cases follow. Each one starts with a line containing the dimensions of the bark grid, M and N. N will always be a multiple of 4. The next M lines will each contain an (N/4)-character hexadecimal integer, representing a row of the bark grid. The binary representation of these integers will give you a strings of N bits, one for each row. Zeros represent black squares; ones represent white squares of the grid. The rows are given in the input from top to bottom. In each row, the most-significant bit of the hexadecimal integer corresponds to the leftmost cell in that row.

      Output

      For each test case, output one line containing "Case #x: K", where x is the case number (starting from 1) and K is the number of different chess board sizes that you can cut out by following the procedure described above. The next K lines should contain two integers each -- the size of the chess board (from largest to smallest) and the number of chess boards of that size that you can cut out.

      Limits

      1 ≤ T ≤ 100;
      N will be divisible by 4;
      Each hexadecimal integer will contain exactly N/4 characters.
      Only the characters 0-9 and A-F will be used.

      The input file will be at most 200kB in size.

      Example

      Input:
      4
      15 20
      55555
      FFAAA
      2AAD5
      D552A
      2AAD5
      D542A
      4AD4D
      B52B2
      52AAD
      AD552
      AA52D
      AAAAA
      5AA55
      A55AA
      5AA55
      4 4
      0
      0
      0
      0
      4 4
      3
      3
      C
      C
      4 4
      6
      9
      9
      6


      Output:
      Case #1: 5
      6 2
      4 3
      3 7
      2 15
      1 57
      Case #2: 1
      1 16
      Case #3: 2
      2 1
      1 12
      Case #4: 1
      2 4


      Added by:Phan Công Minh
      Date:2010-05-28
      Time limit:0s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Google Code Jam 2010









      SPOJ Problem Set (classical)

      6709. Multiplying by Rotation

      Problem code: MBR

      Multiplication of natural numbers in general is a cumbersome operation. In some cases however the product can be obtained by moving the last digit to the front.

      Example: 179487 * 4 = 717948

      Of course this property depends on the numbersystem you use, in the above example we used the decimal representation. In base 9 we have a shorter example:

      17 * 4 = 71 (base 9)
      as (9 * 1 + 7) * 4 = 7 * 9 + 1

      Input

      The input for your program is a textfile. Each line consists of three numbers separated by a space: the base (<=36) of the number system, the least significant digit of the first factor, and the second factor. This second factor is one digit only hence less than the base. The input file ends with the standard end-of-file marker.

      All Numbers in input are greater than 1 and will fit in the standard "int" data type. For base > 10 you can assume the digits to be 'A' ... 'Z'.

      Note: Numbers in Input may or may not be expressed using the above digits (refer example)

      Output

      Your program determines for each input line the number of digits of the smallest first factor with the rotamultproperty. The output-file is also a textfile. Each line contains the answer for the corresponding input line.

      Example


      Input

      10 7 4
      9 7 4
      17 14 12
      17 E C


      Output: 

      6
      2
      4
      4

      The Last two inputs are actually the same.


      Added by:SALVO
      Date:2010-05-29
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:UVA (own input)









      SPOJ Problem Set (classical)

      6711. Transform a Sequence

      Problem code: BLOCK


      An integer sequence is called block iff it is made of two identical and neighboring sequences. For example, (3, 3) and (5, 2, 5, 2) are blocks, while (9, 6, 6, 9) and (1, 1, 1) are not blocks.

      An integer sequence is called non-descreasing iff its each element (except the last one) is less than or equal to the next one. A sequence containing one or zero elements is also non-decreasing.

      You are given an integer sequence and you are to transform it into a non-decreasing sequence by multiple using of two types of operations:

      Type 1: removing a block from the sequence (if that block is a consecutive subsequence);

      Type 2: inserting a block into the sequence (so that it becomes a consecutive subsequence).

      In all of the test data there will be at least one solution.

      Input

      In the first line there is an integer N (3 ≤ N ≤ 40), the size of the given sequence.

      In the next line there are N space-separated integers (of size 0 - 100), the elements of the sequence (in order).

      Output

      Output at most 2340 operations.

      For each operation, write two or three lines (depending on the type of operation). In the first line write the type of the operation (1 or 2).

      If the type of the operation is 1 (removing the block), in the next line write the two numbers: positions in the sequence of the first and the last element of the block you are removing.

      If the type of the operation is 2 (adding the block), in the second line write the two numbers: positions in the sequence of the first and the last element of the block after it is added to the sequence. In the next line, write all the elements of the added block (in order). The elements must be integers from the interval [-1000, 1000].

      There must be less than 1000 elements in the sequence at any time.

      Example

      Input:

      6

      10 20 70 20 70 80


      Output:

      1

      2 5

       

      Input:

      6

      0 4 0 4 4 0


      Output:

      2

      3 4

      4 4

      1

      3 8


      Added by:Adrian Satja Kurdija
      Date:2010-05-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: PERL 6
      Resource:derived from the problem of Polish Mathematical Olympiad









      SPOJ Problem Set (classical)

      6717. Two Paths

      Problem code: TWOPATHS


      In Flatland there are N cities, connected by N-1 two-way roads. The cities are numbered from 1 to N. You can get from one city to another moving along the roads.

      The "Two Paths" company, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).

      It is known that the profit, the "Two Paths" company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.

      Input

      The first line contains an integer N (2 ≤ N ≤ 100000), where N is the amount of cities in the country. The following N-1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road a and b (1 ≤ a, b ≤ N)

      Output

      Output the maximum possible profit.

      Example

      Input:
      4
      1 2
      2 3
      3 4

      Output:
      1

      Added by:Oleg Chernyakhovskiy
      Date:2010-05-31
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Codeforces round 14 with larger limits









      SPOJ Problem Set (classical)

      6720. Paper Fold

      Problem code: PFOLD


      Sedrak likes making various things from paper (and he's very good at that). But after he finishes the job, his table is covered with a lot of useless creased, scrappy paper. Can he use them somehow?

      Imagine a thin strip of paper marked with creases at regular intervals, which we can think of as a line segment divided into equal-length subsegments. Each crease point is marked with as mountain, valley, or flat to specify the orientation of the crease (⋀,⋁,-). For example the input might look as follows:

      Sedrak thinks, he can use the scrap, if it is possible to fold it using all the marked creases with the specified orientations. The operations he is allowed are as follows.  Given a particular crease (⋀ or ⋁)simple fold rotates the portion of the segment to the left of the crease around the portion of the segment to the right of the crease. The rotation is counterclockwise for a mountain fold, and clockwise for a valley fold. When multiple layers of paper come in contact, they become inseparable; in other words, each simple fold must fold all layers of paper. For example, here is how he might fold the example above:

      Notice that when a subsegment is folded, the crease turns upside-down, inverting ⋀↔⋁. Thus, for a simple fold to be valid, the inversions of the creases to the left must match the creases to the right.

      Input


      The first line of input file contains the number  1≤N≤20 - the number of paper scraps on Sedrak’s table.  Next lines contain descriptions of paper scraps as a string containing symbols ‘^’, ‘v’ and ‘-‘. The length of a single description does not exceed 10^6.


      Output


      For each description line of the input file, output a single line containing “Yes”, if Sedrak can use the scrap, and “No” otherwise.


      Example


      Input:

      6

      -^vv-

      --v-

      -vv-

      ^vv^

      v-v^-^^

      --^-v^^-v--


      Output:

      Yes

      Yes

      No

      Yes

      No

      Yes


      NOTE: The last example corresponds to the scrap in the figure.


      Added by:Narek Saribekyan
      Date:2010-06-01
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:RAU School Contest 2010









      SPOJ Problem Set (classical)

      6726. Goldbach graphs

      Problem code: GOLDG

      Christian Goldbach sent a letter to Leonhard Euler in 1742 in which he made the following conjecture:

      "Every even number greater than 4 can be written as the sum of two odd prime numbers"

      To find the solutions of Goldbach's conjecture for a given even number n (n > 0), let us define the directed graph GG(n) (the Goldbach Graph of n) as follows:

      Nodes are prime numbers p such that 1 < p < n.
      For each node p there are zero or more outgoing edges, determined by the following rules:
      If p + q = n and q = 1, then no outgoing edges are related to p.
      If p + q = n and q = p1 p2 p3 .... pk is the prime factorization of q (asuming q > 1), then for each i = 1..k an edge p->pi is added to graph GG(n). Notice that each pi must be a prime number. Besides, if k = 1 then q is prime and we have a solution to Goldbach's conjecture.

      For example:

      • GG(2) is empty (it has zero nodes)
      • GG(4) has two nodes and one edge.
              nodes = {2, 3}
              edges = {2->2}
      • GG(6) has three nodes and three edges
              nodes = {2, 3, 5}
              edges = {2->2, 2->2, 3->3}
        Notice that edge 2->2 appears twice in GG(6) because when p = 2 then q = 4 = 2*2

      Solutions to Goldbach's conjecture are cycles in graph GG(n) of the following types:

      • Single-node cycles (Type I): a node p with only one outgoing edge p->p.
      • Double-node cycles (Type II): two nodes p1 and p2, such that each one has a unique outgoing edge (p1->p2, p2->p1).

      Your task is to inspect the directed graph GG(n) starting from a given node x and searching every node reachable from x for a solution to Goldbach's conjecture.  The procedure is successfull if a node belonging to a Type I or Type II cycle is found. In such a case the minimum distance from x to the first node of the cycle found must be reported. Otherwise it should be stated that a solution can not be found.

      Your algorithm should take into account that GG(n) can contain other types of cycles besides the ones described here. Otherwise, it can run forever.

      Input

      The input contains several lines each one with a different test case. Each line includes a pair of numbers representing the values n and x. You should assume that n is even and also that 2 <= n <= 1000. Although 0 < x < n is true, do not assume that x is a valid node of GG(n). The last line of the input contains the number 0 (it is not a test case).

      Output

      For each test case output a single line with one of the following:

      • Solution found at distance D.
      • Solution not reachable.
      • x is not a node!

      Where D is the minimum distance from x to the solution found, as described before.

      Example

      Input:

      2 1
      4 2
      6 2
      6 3
      12 3
      12 11
      14 7
      20 5
      38 11
      50 17
      540 340
      540 31
      540 33
      0

      Output:

      1 is not a node!
      Solution found at distance 0.
      Solution not reachable.
      Solution found at distance 0.
      Solution not reachable.
      Solution not reachable.
      Solution found at distance 0.
      Solution found at distance 1.
      Solution found at distance 2.
      Solution found at distance 1.
      340 is not a node!
      Solution found at distance 0.
      33 is not a node!

       

      Added by:Coach UTN FRSF
      Date:2010-06-01
      Time limit:2s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Author: Pablo A. Marchetti (FRSF-UTN)









      SPOJ Problem Set (classical)

      6731. Coeficientes

      Problem code: COEF

      The problem is to calculate the coefficients in expansion of polynomial (x1+x2+...+xk)n.

      Input

      The input will consist of a set of pairs of lines. The first line of the pair consists of two integers n and k separated with space (0<K,N<13). This integers define the power of the polynomial and the amount of the variables. The second line in each pair consists of k non-negative integers n1, ..., nk, where n1+...+nk=n.

      Output

      For each input pair of lines the output line should consist one integer, the coefficient by the monomial x1n1x2n2...xknk in expansion of the polynomial (x1+x2+...+xk)n.

      Example

      Input:
      2 2
      1 1
      2 12
      1 0 0 0 0 0 0 0 0 0 1 0



      Output:

      2
      2



      Added by:Coach UTN FRSF
      Date:2010-06-02
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:http://uva.onlinejudge.org/external/101/10105.html









      SPOJ Problem Set (classical)

      6732. Camels

      Problem code: CT14E


      Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps,representing them as polylines in the plane. Each polyline consists of n vertices withcoordinates (x1, y1), (x2, y2), ..., (xn, yn). The first vertex has a coordinate x1 = 1, the second— x2 = 2, etc. Coordinates yi might be any, but should satisfy the following conditions:

      • there should be t humps precisely, i.e. such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 < yj > yj + 1,
      • there should be precisely t - 1 such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 > yj < yj + 1,
      • no segment of a polyline should be parallel to the Ox-axis,
      • all yi are integers between 1 and 4.

      For a series of his drawings of camels with t humps Bob wants to buy a notebook, but he doesn'tknow how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with t humps for a given number n.

      Input

      The first line of input contains the number of testcases , Ntest.

      Each testcase contains a pair of integers n and t (3 ≤ n ≤ 20, 1 ≤ t ≤ 10).

      Output

      For each testcase ,output the required amount of camels with t humps.

      Example

      Input:
      1
      6 1
      Output:
      6

      Note
      In the first sample test sequences of y-coordinates for six camels are: 123421, 123431,
       123432, 124321, 134321 и 234321 (each digit corresponds to one value of yi).



      Added by:Phan Công Minh
      Date:2010-06-02
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Codeforces.









      SPOJ Problem Set (classical)

      6738. Nice Quadrangles

      Problem code: CHEFMAY


      There are n points with integer coordinates. We can form different quadrangles out of them by taking four different points and connecting them with lines. Let’s call a quadrangle ABCD nice if and only if:

      • Ax > 0 and Ay > 0;
      • Bx > 0 and By < 0;
      • Cx < 0 and Cy < 0;
      • Dx < 0 and Dy > 0;
      • ABCD has an integer area.

      Your task is to count all different nice quadrangles that can be formed on the given points.

      Input

      The first line of input file contains number t – the number of test cases. Then the description of each test case follows. The first line of each test case contains number n – the number of points. Then n lines follow each consisting of two integers x, y – the coordinates of a point. No two points in the same test case coincide.

      Constraints

      1 <= t <= 10
      1 <= n <= 30000
      -30000 <= x, y <= 30000

      Output

      For each test case print the number of nice quadrangles that can be formed using given points.

      Example

      Input:
      1
      6
      1 1
      2 2
      -1 -1
      -2 2
      2 -1
      -3 -4
      
      Output:
      2
      
      

      Added by:Spooky
      Date:2010-06-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:CodeChef May Challenge









      SPOJ Problem Set (classical)

      6767. Sequence Function

      Problem code: SEQFUN

      We define a sequence {x}: {x}={x_0, x_1, … , x_n-1 } where x_i is a interger.

      We have a function f: {x}->{x’} where {x} is a finite sequence.

      After we have a finite sequence {x}, we can get f({x}) follow these rules :

       

      (1). Remove all 0 in x : a 0 b 0 c d 0 e f 0 g => a b c d e f g

      (2). Turn 1 into 100 and -1 into -100 : a 1 b 1 -1 c d e f g => a 100 b 100 -100 c d e f g

      (3). Add all 2^k (k>1) at the end of the sequence : a 2 b 8 c d e 1024 f g => a 2 b 8 c d e 1024 f g 2 8 1024

      (4). Add any positive odd prime x at the end of the sequence x-1 times: a 3 b c 7 d e f 5 g => a 3 b c 7 d e f 5 g 3 3 7 7 7 7 7 7 5 5 5 5

      (5). For any positive composite number (not 2^k, k>1 ), we just keep it once: a 6 b 6 c d 6 e 4 4 f g => a 6 b c d e 4 4 f g

      (6). Keep any t (t<-1) in the sequence.

      For a example:

      {x}={-5 1 0 2 9 16 7 5 3 2 9 9 -1}

      f({x})={-5 100 2 9 16 7 5 3 2 -100 2 2 16 7 7 7 7 7 7 5 5 5 5 3 3}

       

      We define g({x}) is the sum of all the element in sequence x.

      We define h({x}) = g(f({x}))-g({x}).

       

      A consecutive sequence of x is a sequence {x_i, x_i+1, x_i+2, … , x_j} where 0<=i<=j<n.

       

      Now I will give you a sequence {x} .

      I want to ask you the maximal h({y}) where {y} is a consecutive sequence of {x}.

      Input

      One line consists one interger N, the length of {x}.   (N<=10^5, |x_i|<=10000)

      Next N lines, each line consists one interger.

       

      Output

      The maximal h({y}) where {y} is a consecutive sequence of {x}. ( |h({y})|<=2^63-1 )

      Example

      Input:
      

      5

      1

      2

      6

      6

      3

      Output:
       101
      

      Added by:刘启鹏
      Date:2010-06-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:ALL41 CONTEST #2









      SPOJ Problem Set (classical)

      6772. Happy Coins

      Problem code: HC

                                   Happy Coins

      A line of coins are given, some belongs to lxh while others belongs to hhb. Now the two guys are about to play a game. In every round of game, each player can select any two consecutive coins and change them into one coin, if the two coins belongs to the same person, the new one will be gained to hhb, or else it will belongs to lxh. The two guys take turns playing this game, lxh always play first. The game runs round by round. You can easily make sense that we will get only one coin at the end of game. Now the question is, suppose the two players perform optimally in the game, which person does the final coin belongs to?

      Input

      The first line of the input contains one integer T, which indicate the number of test cases.

      Following each test, the first line contains an integer N (N ≤ 105), the number of coins. Following N lines, each line contains a name, lxh or hhb, the name of whom this coins belongs to.

      Output

      For each case, output a line contains the name of whom the final coin belongs to.

      Sample Input

      1
      2
      lxh
      hhb

      Sample Output

      lxh


      Added by:Kumar Anurag
      Date:2010-06-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:TJU









      SPOJ Problem Set (classical)

      6773. Dinostratus Numbers

      Problem code: DINONUM

      Recents archaeological discoveries of researchers from the University of Alberta in Canada showed that a strange sequence of numbers were found on the walls of the pyramids of Egypt, the ruins of Macchu Picchu and the stones of Stonehenge. Intrigued by the apparent coincidence researchers triggered the Department of Mathematics to decipher what were special about that sequence or numbers.

      The discovery was startling. All numbers were generated by matrices of Dinostratus. Dinostratus was a famous Greek mathematician who lived from 390 to 320 BC and worked in major geometry problems like squaring the circle. Dinostratus studied matrices M of size 3 x 3 formed by nine distinct integers with the property that for every position (i, j), i = 1 ,..., 3, j = 1 ,..., 3 of matrix, the element mi,j is a multiple of its neighbors mi-1,j, mi-1,j-1 and mi,j-1 (if they exist). In his honor, we say that n is a Dinostratus number if exist a matrix M with the property above such that m3,3 = n.

      See an example with n = 36.

      1   2   4
      3 6 12
      9 18 36

      The relationship between the Dinostratus numbers, the pyramids of Egypt, Stonehenge and the stones of the ruins of Machu Picchu still remains a great mystery. But researchers in Alberta are willing to study these magic numbers. Your task is to make a program that receives an integer n and checks whether this is a Dinostratus number.

      Input

      The input consists of several instances. Each instance is given by a line containing an integer n (1 <= n <= 1048576). The input ends with end of file.

      Output

      For each instance, you must print an identifier Instance k, where k is the number of the current instance. On the next line print yes if n is a Dinostratus number otherwise print no.

      Example

      Input:
      36
      37
      38

      Output:
      Instance 1
      yes

      Instance 2
      no

      Instance 3
      no

       


      Added by:Paulo Roberto Santos de Sousa
      Date:2010-06-11
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: ERL JS NODEJS PERL 6 SCALA TCL
      Resource:http://br.spoj.pl/problems/DINOSTRA/









      SPOJ Problem Set (classical)

      6779. Can you answer these queries VII

      Problem code: GSS7

      Given a tree with N ( N<=100000 ) nodes. Each node has a interger value x_i ( |x_i|<=10000 ).

      You have to apply Q ( Q<=100000 ) operations:

      1. 1 a b : answer the maximum contiguous sum (maybe empty,will always larger than or equal to 0 ) from the path a->b ( inclusive ).

      2. 2 a b c : change all value in the path a->b ( inclusive ) to c.

      Input

      first line consists one interger N.

      next line consists N interger x_i.

      next N-1 line , each consists two interger u,v , means that node u and node v are connected

      next line consists 1 interger Q.

      next Q line : 1 a b or 2 a b c .

      Output

      For each query, output one line the maximum contiguous sum.

      Example

      Input:
      5
      -3 -2 1 2 3
      1 2
      2 3
      1 4
      4 5
      3
      1 2 5
      2 3 4 2
      1 2 5
      
      Output:
      5
      
      9

      Added by:刘启鹏
      Date:2010-06-14
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:my own problems









      SPOJ Problem Set (classical)

      6803. Absurd prices

      Problem code: ABSURD

      Surely you know that supermarkets, shopping centres, and indeed all kind of vendors seem to have fallen in love with the digit 9, for that digit occurs most often in the price of a product, preferably at the least significant positions. Your favourite chocolate bar might cost 99 cents, just right to be able to advertise that it costs less than 1 euro. Your new bicycle might cost 499.98 euros, which, of course, is less than 500 euros.

      While such comparisons are mathematically sound, they seem to impose a certain amount of stupidity on the customer. Moreover, who wants to carry home those annoying small coins you get back as change?

      Fortunately, the FIFA has not adopted this weird pricing scheme: a ticket for the final in the first category for example costs 900 dollar, in the second category 600 dollar and in the third category 400 dollar. These prices may only be regarded weird for other reasons.

      We want to distinguish between absurd prices like 99 cents, 499.98 euros, etc. and normal prices. To measure the absurdity of a positive integer, do the following:

      • Eliminate all trailing zeros, i.e., those in the least significant positions, from the number. You now have a positive integer, say x, with a non-zero digit d at its end.
      • Count the number of digits, say a, of the number x.
      • if d=5 the absurdity of the number is 2 * a - 1
      • otherwise, the absurdity of the number is 2 * a

      For example, the absurdity of 350 is 3 and the absurdity of 900900 is 8. Using the measure of absurdity, we can define what we call an absurd price: A price c is absurd if and only if the closed interval [0.95 * c,1.05 * c] contains an integer e such that the absurdity of e is less than the absurdity of c. Given a price in cents, go ahead and tell whether it is absurd!

      Input

      The first line of the input consists of the number t of test cases to follow. Each test case is specified by one line containing an integer c. You may assume that 1 ≤ c ≤ 109.

      Output

      For each test case output if c is absurd or not. Adhere to the format shown in the sample output.

      Example

      Input:
      4
      99
      49998
      90000
      970000000
      
      Output:
      absurd
      absurd
      not absurd
      absurd
      

      Added by:Adrian Kuegel
      Date:2010-06-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Authors: Walter Guttmann/Adrian Kuegel)









      SPOJ Problem Set (classical)

      6804. Cheating or Not

      Problem code: CHEATING

      For the organizers of a soccer world championship the final draw is a very delicate job. It determines the compositions of the groups for the first stage of the tournament and indirectly also the possible matches in the knockout stage. The importance lies in the fact that the success of a team might depend on the opponents it faces - and, maybe, even the winner of the tournament.

      The final draw is often subject to accusations of fraud. Some teams tend to think that their group is stronger than others and therefore complain they were cheated. Your job is to provide some facts that can help convince them of the opposite.

      The draw is somewhat complicated due to a number of fairness considerations. The objective is not to assign too many good teams to the same group. Also teams from the same confederation should be drawn into different groups. This is ensured by the following rules.

      • There are g groups with m members each.
      • The hosting nation will be seeded first in the first group.
      • g-1 selected teams will be seeded first in the remaining groups.
      • The remaining positions are drawn from m-1 pots, one team from each pot per group.
      • You will be told which teams belong to the same confederation and you have to ensure that no two teams of the same confederation are in the same group. For confederations with more than g teams this is impossible, so for these confederations you can ignore this rule.
      • You may assume that for confederations with at most g teams, all teams of the confederation which are not seeded are in the same pot.
      • Note that each team belongs to exactly one confederation and each team is either seeded or contained in exactly one pot.

      We want to compute the average strength of the opponents of a given team. The strengths of the teams will be given in the input. Now you have to compute the average of the sum of the strengths of the other teams in the group of the given team. The average is evaluated over all correct draws which are assumed to have the same likelihood.

      Input

      The input starts with the number of test cases. Each test case is described as follows.

      The first line contains the number of groups g ≤ 8 and the number of teams per group m ≤ 4. A line with g * m integers follows. The i-th integer 0 ≤ si ≤ 10000 denotes the strength of the i-th team.

      The team indices start from 0. By convention, the hosting nation is assigned number 0. The next line lists the g-1 seeded teams by their numbers. Each of the m-1 following lines contains g teams which are allocated to the same pot.

      The next line specifies the number of confederations c. c lines follow which describe one confederation each. Each confederation description starts with the number of teams ni > 0. Then ni numbers with the team indices follow.

      The last line contains the number t of the team, whose average group strength has to be evaluated.

      Output

      Output the average of the sum of strengths of the opponents of team t in the group stage with 3 decimals on a single line.

      Example

      Input:
      2
      2 3
      1 2 3 4 5 6
      1
      2 5
      3 4
      1
      6 0 1 2 3 4 5
      5
      2 3
      1 2 3 4 5 6
      1
      2 5
      3 4
      2
      2 0 5
      4 1 2 3 4
      5
      
      Output:
      6.000
      6.500
      

      Added by:Adrian Kuegel
      Date:2010-06-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Author: Stephan Ritscher)









      SPOJ Problem Set ()

      6805. Counter attack

      Problem code: CATTACK

      At our soccer training camp, we have rehearsed a lot of motion sequences. In case we are defending, all players except the two strikers of our team are in our half. As soon as we are getting the ball, we are starting a counterattack with a long-range pass to one of our strikers. They know each others motion sequences and may pass the ball to the other striker at fixed points.

      There are a lot of decisions: the defender has to select the striker to pass the ball to, and the ball possessing striker has to decide at each of the n fixed points if to pass to the other striker or to run and to dribble. At the last position in the motion sequence of a striker he shoots on the goal. Each of the four actions (long-range pass, dribble, pass, and shoot on the goal) may fail (e.g. because of a defending player of the opposite team) - so our coach has assigned difficulties.

      What is the minimal difficulty of a goal assuming your team plays optimally?

      example image

      In the example depicted in the picture, the defending player (cross in left half) passes the ball to one of the strikers (crosses in right half). The strikers move along fixed paths simultaneously. At each of the fixed positions (circles), the ball possessing striker either dribbles with the ball or passes to the other striker. At the last position, he shoots on the goal.

      Input

      The first line of the input consists of the number of test cases c that follow (1 ≤ c ≤ 100). Each test case consists of five lines. The first line of each test case contains n (2 ≤ n ≤ 100000), the number of fixed points in each strikers motion sequence. It is followed by l0, l1, s0 and s1, the difficulty of a long-range pass to the corresponding striker and the difficulties of the shoots of the strikers. Each striker is described in two lines (first striker 0, then striker 1): The first line contains n-1 difficulties, where the ith number stands for passing from point i to the other player at point i + 1. The second line also contains n-1 difficulties, where the ith number stands for dribbling from point i to point i+1. You may safely assume that each difficulty is a non-negative integer less than 1000.

      Output

      For each test case in the input, print one line containing the minimal difficulty of a move sequence leading to a goal.

      Example

      Input:
      2
      3 3 5 7 999
      9 13
      60 5
      22 6
      5 5
      5 3 5 7 999
      9 13 8 4
      60 5 17 13
      22 6 15 11
      5 5 18 29
      
      Output:
      23
      42
      

      Added by:Adrian Kuegel
      Date:2010-06-18
      Time limit:3s-8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:German Collegiate Programming Contest 2010 (Author: Tobias Werth)









      SPOJ Problem Set (main)

      6818. Capital City

      Problem code: CAPCITY

      There are N cities in Flatland connected with M unidirectional roads. The cities are numbered from 1 to N. The Flat Circle of Flatland (FCF) wants to set up a new capital city for his kingdom. For security reasons, the capital must be reachable from all other cities of Flatland. FCF needs the list of all candidate cities. You are the chief programmer at FACM (Flat Association for Computing Machinery) responsible for providing the list to FCF as soon as possible.

      Input

       

      The first line of the input file contains two integers։ 1N≤100,000 and 1M≤200,000. Each of the following M lines contains two integers 1A, B≤N denoting a road from A to B.


      Output 


      The output file contains an integer denoting the number of candidate cities followed by the list of candidate cities in increasing order.


      Example


      Input:


      4 4

      1 2

      3 2

      4 3

      2 1


      Output:


      2

      1 2


      Added by:Narek Saribekyan
      Date:2010-06-20
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 PAS fpc PAS gpc PYTH 3.2.3
      Resource:Armenian TST 2010, Round 2









      SPOJ Problem Set (classical)

      6819. Yet Another Assignment Problem

      Problem code: ASSIGN5

      New term is coming.  Our monitor Cathy Yin is going to make necessary preparations.  Now she has m jobs to do, and n classmates are going to help her.  Each job requires some classmates working on it for certain time, say the i-th classmate must work on the j-th job for Aij minutes.  As an OIer of great responsibility she wishes to finish all jobs as soon as possible.  But a classmate can do only one job at a time, and two classmates can not do the same job at the same moment.  For example, to decorate the classroom, Alpha must work on it for 3 minutes plus Beta works on it for 4 minutes, then one possible assignment will be ABABBAB, taking 7 minutes in total.

      Now she is going to make a detailed schedule specifying who is doing what at each moment.  Jobs are independent, i.e. they may be done in arbitrary order.  Also for each job anyone can do it for arbitrarily long, but not longer than the required time Aij.  Anyone can be free at any time.  Time for certain classmate doing certain work need not be consecutive.

      As her friend, you are to help her to work out the schedule minimizing the time needed.  (The time of this assignment itself does not count!)

      Input

      First line of the input contains two positive integers m, n (1 <= m, n <= 2000), number of jobs and classmates.

      m lines follow, each descibing a job.  i-th line contains n non-nagative integers (<= 106), where the j-th number is Aij, meaning that the j-th classmate has to work on the i-th job for Aij minutes as descibed above.

      Output

      First line contains single integer T, minimum time needed.  Next line contains n non-negative intergers (<= m), giving one possible schedule for the first minute, where the i-th number specifying the job for the i-th classmate to do, and 0 denotes that the corresponding classmate is free.

      If there are multiple solutions, any one is accepted.

      Example

      Input:
      2 2
      2 5
      5 1

      Output:
      7
      1 0

      Explanation:

      Two jobs are assigned to two classmates, say Lambda and Mu.  To tidy up the classroom Lambda needs to work for 2 minutes and Mu 5 minutes; and to move desks for new comers Lambda needs 5 minutes and Mu 1 minute.

      One optimal schedule is:

      T Lambda Mu
      0 Tidy Free
      1 Move Tidy
      2 T M
      3 M T
      4 M T
      5 M T
      6 M T

      7 minutes in total.  It is obvious that it is impossible to finish it in less than 7 minutes.


      Added by:Tony Beta Lambda
      Date:2010-06-20
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      6823. Seller Bob

      Problem code: CFJUN21

      Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place:

      • A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2xberllars.
      • Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it.

       

      Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. . Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally.

      Input

      The first input line contains number n (1 ≤ n ≤ 5000) — amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0 ≤ x ≤ 2000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0 ≤ x ≤ 2000).

      Output

      Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.

      Example

      Input:
      7
      win 10
      win 5
      win 3
      sell 5
      sell 3
      win 10
      sell 10

      Output: 1056

      Added by:Phan Công Minh
      Date:2010-06-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Codeforces









      SPOJ Problem Set (classical)

      6824. Flag

      Problem code: CTFLAG


      According to a new ISO standard, a flag of every country should have, strangely enough, a chequered field n × m, each square should be wholly painted one of 26 colours. The following restrictions are set:

      • In each row at most two different colours can be used.
      • No two adjacent squares can be painted the same colour.

       

      Pay attention, please, that in one column more than two different colours can be used.

      Berland's government took a decision to introduce changes into their country's flag in accordance with the new standard, at the same time they want these changes to be minimal. By the given description of Berland's flag you should find out the minimum amount of squares that need to be painted different colour to make the flag meet the new ISO standard. You are as well to build one of the possible variants of the new Berland's flag.

      Input

      The first input line contains 2 integers n and m (1 ≤ n, m ≤ 500) — amount of rows and columns in Berland's flag respectively. Then there follows the flag's description: each of the following n lines contains m characters. Each character is a letter from a to z, and it stands for the colour of the corresponding square.

      Output

      Output the minimum amount of squares that need to be repainted to make the flag meet the new ISO standard

      Example

      Input:
      
      3 4
      aaaa
      bbbb
      cccc
      Output: 6

      Added by:Phan Công Minh
      Date:2010-06-21
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Codeforces









      SPOJ Problem Set (classical)

      6825. Field Plan

      Problem code: FPLAN


      World Soccer Championship is coming soon and coach Yogi wants to prepare his team as well as possible. So he made up a strategy field plan for every player of the team. One plan describes a number of possible locations for the player on the field. Moreover, if Yogi wants the player to be able to move from one location A to another location B then the plan specifies the ordered pair (A,B). He is sure that his team will win if the players run over the field from one location to another using only moves of the plan.

      example image

      Yogi tells every player to follow his plan and to start from a location that reaches every other location on the plan (by possibly multiple moves). However, it is quite difficult for some soccer players, simple minded as they are, to find a suitable starting location. Can you help every player to figure out the set of possible start locations?

      Input

      The first line gives the number of field plans. The input contains at most eleven field plans (what else?). Every plan starts with a line of two integers N and M, with 1 ≤ N ≤ 100000 and 1 ≤ M ≤ 100000, giving the number of locations and the number of moves. In the following M lines a plan specifies moves (A,B) by two white space separated integers 0 ≤ A,B < N. The plans are separated by a blank line.

      Output

      For every plan print out all possible starting locations, sorted increasingly and one per line. If there are no possible locations to start, print Confused. Print a blank line after each plan output.

      Example

      Input:
      2
      4 4
      0 1
      1 2
      2 0
      2 3
      
      4 4
      0 3
      1 0
      2 0
      2 3
      
      Output:
      0
      1
      2
      
      Confused
      
      

      Added by:Adrian Kuegel
      Date:2010-06-21
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Author: Christian Hundt)









      SPOJ Problem Set (classical)

      6826. Hacking

      Problem code: HACKING


      A coach of one of the soccer world finals teams (lets call him Hugo Hacker) wants to find out secret information about an opposing team before the game. The coach of the opposing team has a website with public information about his team. Hugo suspects that also secret information is stored on the computer which hosts the website.

      The website contains a form which allows to search for key words and returns a chunk of a text file which contains the key word. Hugo has found out that by entering words which cannot be found in the documents publicly available, he can exploit a bug in the search and get access to other files on the computer. He already knows the publicly available documents. However the search box has a restriction on the maximum length of a word and the characters which can be entered. Can you tell him a word which can be entered in the search box and which does not occur as a substring in the documents?

      Input

      The first line of the input consists of the number of test cases which are to follow. Each test case consists of two lines: in the first line there are three integers n (1 ≤ n ≤ 10000), m (1 ≤ m ≤ 100) and k (1 ≤ k ≤ 26), where n is the length of the publicly available documents, m is the maximum allowed length of words which can be entered in the search box, and k specifies that the search box allows only the first k characters of the alphabet. The second line of each test case describes the publicly available documents and consists of n lower-case letters.

      Output

      For each test case in the input, print one line in the output containing a word which does not occur as a substring in the given text. The word should have at most m lower-case characters from the first k letters in the alphabet. You may assume that for each given test case, there is always at least one such word (you may print any such word).

      Example

      Input:
      2
      9 3 2
      bbbaababb
      9 3 2
      aaabbabaa
      
      Output:
      aaa
      bbb
      

      Added by:Adrian Kuegel
      Date:2010-06-21
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Authors: Simon Gog/Adrian Kuegel)









      SPOJ Problem Set (classical)

      6827. Last Minute Construction

      Problem code: LMCONSTR

      For the upcoming soccer world championship's finals in South Africa the organisation committee has planned a very prestigious project. To take the two teams, which are battling it out for the title, to new heights, the final should take place on a plateau of the "Mafadi", the highest mountain of South Africa. During the preparations, the logistics of such a huge event have been severely underestimated.

      Now, with barely a month to go, the stadium on top of the plateau is finished but the means of transportation to the plateau are next to nonexistent. Until now, there are only small roads connecting many little villages spread all over the mountain. Furthermore, known for their efficiency, ancient South African builders only built a road between two villages, if no other connection existed so far.

      Since the amount of fans would exceed the capacity of the small mountain roads, this leaves the committee with only one choice: improve the possibilities to reach the mountain at one of the sites. But as if this wasn't enough trouble to go through, the mountain folks have announced to sabotage the finals, if the constructions would disturb any village more than once. Since the committee has access to an old tunnel-drill, it has decided to create a number of alternative routes to divert a bit of the traffic.

      The engineers have identified a number of possible sites, all offering a good landing spot to fly in the giant drill to and a takeoff spot to transport the drill back from. But as the drill is really old, it has to follow the natural structures in the rock and can therefore only be used to drill in the given direction. Thus, the engineers seek your help to identify the sites on which a route for the drill (using existing roads and drilling new tunnels) exists from the landing platform to the takeoff spot, visiting each village at most once. Furthermore, a valid route needs to contain all the tunnels identified necessary by the engineers, and it should contain no other tunnels.

      Input

      The input to your program provided by the South African building committee will be structured as follows. Each input file begins with the number of test cases on a single line. On the first line of every test case three numbers N, M, T (1 ≤ N,M ≤ 100000, 0 ≤ T ≤ 100000) will specify the number of villages, as well as connections and tunnels to follow. The second line specifies the location of the landing platform and the takeoff spot respectively (landing platform takeoff spot). After this M lines follow, each giving a pair of villages a b (0 ≤ a,b < N, a ≠ b) to indicate an existing road between a and b which can be used in both directions. Finally T lines follow, each giving a pair of villages a b (0 ≤ a,b < N, a ≠ b) to indicate that a tunnel was deemed necessary for the finals from a to b. The tunnel has to be drilled in the direction from a to b.

      Output

      For each of the presented test cases, print a single line containing either IMPOSSIBLE whenever the construction is not possible, or POSSIBLE whenever the constructions can be carried out under the given restrictions.

      Example

      Input:
      2
      3 2 1
      1 0
      0 1
      0 2
      1 2
      3 2 1
      1 0
      0 1
      0 2
      2 1
      
      Output:
      POSSIBLE
      IMPOSSIBLE
      

      Added by:Adrian Kuegel
      Date:2010-06-21
      Time limit:3s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Authors: Moritz Kobitzsch, Christian Vetter, Ignaz Rutter)









      SPOJ Problem Set (classical)

      6828. Lineup

      Problem code: LINEUP


      On June 13th team Germany has its first match in the FIFA world cup against team Australia. As the coach of team Germany, it is your duty to select the lineup for the game. Given this is your first game in the cup, naturally you want to make a good impression. Therefore you'd like to play with the strongest lineup possible.

      example image

       

      You have already decided on the tactical formation you wish to use, so now you need to select the players who should fill each of the 11 positions in the team. Your assistant has selected the 11 strongest players from your squad, but this still leaves the question where to put which player.

      Most players have a favoured position on the field where they are strongest, but some players are proficient in different positions. Your assistant has rated the playing strength of each of your 11 players in each of the 11 available positions in your formation, where a score of 100 means that this is an ideal position for the player and a score of 0 means that the player is not suitable for that position at all. Find the lineup which maximises the sum of the playing strengths of your players for the positions you assigned them. All positions must be occupied, however, do not put players in positions they are not proficient with (i.e.\ have a score of 0).

      Input

      The input consists of several test cases. The first line of input contains the number C of test cases. For each case you are given 11 lines, one for each player, where the i-th line contains 11 integer numbers sij between 0 and 100. sij describes the i-th player's strength on the j-th position. No player will be proficient in more than five different positions.

      Output

      For each test case output the maximum of the sum of player strengths over all possible lineups. Each test case result should go on a separate line. There will always be at least one valid lineup.

      Example

      Input:
      1
      100 0 0 0 0 0 0 0 0 0 0
      0 80 70 70 60 0 0 0 0 0 0
      0 40 90 90 40 0 0 0 0 0 0
      0 40 85 85 33 0 0 0 0 0 0
      0 70 60 60 85 0 0 0 0 0 0
      0 0 0 0 0 95 70 60 60 0 0
      0 45 0 0 0 80 90 50 70 0 0
      0 0 0 0 0 40 90 90 40 70 0
      0 0 0 0 0 0 50 70 85 50 0
      0 0 0 0 0 0 66 60 0 80 80
      0 0 0 0 0 0 50 50 0 90 88
      
      Output:
      970
      

      Added by:Adrian Kuegel
      Date:2010-06-21
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Author: Holger Frydrych)









      SPOJ Problem Set (classical)

      6829. Polynomial

      Problem code: POLYNOM


      The number of spectators at the FIFA World Cup increases year after year. As you sell the advertisement slots during the games for the coming years, you need to come up with the price a company has to pay in order to get an advertisement slot. For this, you need a good estimate for the number of spectators in the coming games, based on the number of spectators in the past games.

      Your intuition tells you that maybe the number of spectators could be modeled precisely by a polynomial of degree at most 3. The task is to check if this intuition is true.

      Input

      The input starts with a positive integer N, the number of test cases. Each test case consists of one line. The line starts with an integer 1 ≤ n ≤ 500, followed by n integers x1, ..., xn with 0 ≤ xi ≤ 50000000 for all i, the number of spectators in past games.

      Output

      For each test case, print YES if there is a polynomial p (with real coefficients) of degree at most 3 such that p(i) = xi for all i. Otherwise, print NO.

      Example

      Input:
      3
      1 3
      5 0 1 2 3 4
      5 0 1 2 4 5
      
      Output:
      YES
      YES
      NO
      

      Added by:Adrian Kuegel
      Date:2010-06-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Author: Christoph Dittmann)









      SPOJ Problem Set (classical)

      6830. Soccer Bets

      Problem code: SBETS

      The teams have finished the group stage of the FIFA World Cup and the teams that are in the round of the last sixteen are known. My boss has all of the games analyzed and bets on the whole rest of the tournament by writing the outcome of each match on a single sheet of paper. It was my job to bring his bets to the next betting office and set 1000 dollar. Being nervous with so much cash in my pockets I fell over (I am a bit clumsy) and the bets got shuffled. So I don't know if a bet corresponds to the final match or the semi-final or something else.

      I do not want to disappoint my boss, so I decided to place only one bet on the winner of the tournament. Everything I know is that in each round the teams that win (a team wins if it shoots more goals than the opposing team) are in the next round, the other teams are eliminated from the tournament. This is not true for the semi-finals where the losers also play for the third place. So we have in total 16 matches.

      Can you please tell me which team will win the World Cup based on the bets of my boss?

      Input

      The first line of the input is the number of test cases c (1 ≤ c ≤ 100). Each test case consists of 16 lines describing the matches in random order. A match description looks as follows: t1 t2 g1 g2. t1 and t2 are the names of teams (abbreviated as exactly three uppercase letters), g1 and g2 (0 ≤ g1, g2 ≤ 10; g1 ≠ g2) are the goals of the two teams.

      Output

      For each test case, print one line containing the team that will win the FIFA World Cup (based on the analysis of my boss which is always correct!).

      Example

      Input:
      1
      ITA URU 2 0
      ITA IRE 1 0
      ITA ARG 3 4
      YUG ARG 2 3
      GER CZE 1 0
      ENG GER 3 4
      ITA ENG 2 1
      CAM COL 2 1
      ENG CAM 3 2
      ENG BEL 1 0
      GER ARG 1 0
      CZE CRC 4 1
      NET GER 1 2
      BRZ ARG 0 1
      SPA YUG 1 2
      ROM IRE 4 5
      
      Output:
      GER
      

      Added by:Adrian Kuegel
      Date:2010-06-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Author: Tobias Werth)









      SPOJ Problem Set (classical)

      6831. Two Ball Game

      Problem code: TBGAME

      Lizarb's national soccer team undoubtedly belongs to the group of favourites to win the World Cup at the upcoming championship. Their greatest advantages are their excellent dribbling skills and the ball passing precision. Particularly, each player can pass the ball to every other player on the playing field at any distance. The team's captain, Oicul, claims that an exercise which certainly has a substantial effect on the team's soccer skills is the so-called "Two-ball Game".

      In the two-ball game, n > 4 kickers are positioned on the playing field and do not move (i.e.\ change their locations) during the game. Four of the players are distinguished: two of them, denoted as s1 and s2, are called starting players, and two others, denoted as t1 and t2, are called terminal players. At the beginning, player s1 has got a white ball and s2 possesses a black ball. Then each starting player can kick the ball directly to the corresponding terminal player but he can also kick the ball to any other player on the field and this player can pass the ball to the next one, and so on. The aim is that at the end the white ball is in possession of t1 and the black ball in possession of t2. So, it seems the game is quite simple. However, to avoid ball collisions, the constraint of the game is that no ball trajectories cross each other and that no player (including starting and terminal ones) has more than one ball contact. For simplicity, we assume the trajectory of a ball moving from one player to the next one is a line segment.

      Lizarb's national soccer team observed that for some locations of kickers the two-ball game is possible but for some others it is impossible. The figure below shows two example locations: to the left, playing two-ball game is impossible; to the right, playing the game is possible.

      example image

      Your task is to write a program that checks if for given player locations the two-ball game is possible or not.

      Input

      Each input starts with a single integer that gives the number of cases that follow. The firsts line of each case contains the number of players n, with 4 ≤ n ≤ 100000 followed by n lines that describe the coordinates of the players. All coordinates are pairwise different and the points determined by the coordinates are not collinear (recall, three or more points are said to be collinear if they lie on a single straight line). The first coordinate describes the location of s1, the second the location of t1, the third coordinate describes the location of s2, and the fourth the location of t2. The remaining coordinates describe positions of other players of the team.

      Output

      For each case, your algorithm has to output a line containing POSSIBLE if it is possible to play the game and IMPOSSIBLE, otherwise.

      Example

      Input:
      
      2
      5
      2.01 0.02
      1.04 3.02
      0.01 0.99
      4.1  3.2
      2.1  2.01
      5
      2.01 0.02
      1.04 3.02
      0.01 0.99
      2.1  2.01
      4.1  3.2
      
      Output:
      IMPOSSIBLE
      POSSIBLE
      

      Added by:Adrian Kuegel
      Date:2010-06-21
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Author: Maciej Liskiewicz)









      SPOJ Problem Set (classical)

      6832. To Score or not to score

      Problem code: TOSCORE

      Robot soccer matches in the very early days were quite funny, since most of the time there wasn't any action in the game. Robots only moved to catch a ball that a robot from the other team had shot. The reason for this somewhat strange behavior was attributed to the used strategy. The robots made a map of all players from the same team and the opponents. If one player was in possession of the ball before even shooting he tried to check whether it was possible to score from the current situation. In the process he checked if there was a way for the ball to reach the goal via several other players of his team. It was possible to shoot the ball to another player if no opponent was close enough to the shooting line to catch the ball. The opponent always moved perpendicular to the shooting line and only if he was sure that he could intercept the shot. The ball always traveled three times as fast as a robot could move, i.e. the player had to be quite near the shooting line to intercept the shot.

      The other part of the game was fouling another player in order to prevent the other team from reaching the goal. The rules stated that only one player could be fouled at a time, so this only happened if fouling this one player prevented the other team from scoring. Also the initial shooter may not be fouled at any time. Fouling happens almost instantly by knocking the robot out with an electromagnetic pulse, thus the distance between the two opponents does not matter and the fouling robot does not move.

      example image

      Let's have a look at the figure. There are four players in each team, indicated by the black and white circles. Suppose player A has the ball. Then only the shown shots are possible (note the directions). In all other cases a white player is near enough to intercept the shot (e.g. the direct shot from A to the goal). Thus in principle the black team could score. However, if player D is fouled the goal can no longer be scored.

      Your university has decided to program a simulator for these ancient robot football matches and your task is to write the part that checks if the team in possession of the ball is able to score or not, based on the current positions of all robots. As a summary of the description above, a team may score if the ball cannot be intercepted by an opponent player and if more than one player would have to be fouled.

      Input

      The first line contains the number of testcases 1 ≤ k ≤ 10 that follow. The first line of each testcase holds the number n of players per team (1 ≤ n ≤ 20). The next 2n lines contain the coordinates of all players, the first n lines being the first team, the second n lines the second team. A coordinate is given as two non-negative floating point numbers separated by spaces. The first player of the first team is in possession of the ball. The coordinates of the goal follow below the two teams. You may assume that the inputs are chosen in such a way that small floating point errors do not lead to wrong results.

      Output

      Output Goal if the first team is able to score or No goal if the ball can be intercepted or if fouling one player is enough to prevent the team from scoring.

      Example

      Input:
      2
      4
      407.89 297.33
      396.64 80.21
      190.26 96.43
      210.73 290.67
      345.43 315.24
      462.45 218.22
      291.76 60.82
      104.98 113.45
      0 191.18
      4
      407.89 297.33
      396.64 80.21
      190.26 96.43
      210.73 290.67
      521.43 369.86
      565.14 368.22
      563.25 328.18
      521.31 334.00
      0 191.18
      
      Output:
      No goal
      Goal
      

      Added by:Adrian Kuegel
      Date:2010-06-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:German Collegiate Programming Contest 2010 (Author: Thorsten Meinl)









      SPOJ Problem Set (classical)

      6851. Fence

      Problem code: CT10R3B


      We are looking into building a very long fence. We have already found a nice place to build it, and all that remains is to collect the materials.

      From local hardware stores, we can buy unlimited numbers of wooden boards, each of which can come in a variety of different lengths. To avoid waste, we want to make sure that the total length of these boards is exactly equal to the length of the fence we are trying to build.

      Given the length of the fence, and the possible board lengths that we can use, what is the minimum number of boards that we need to purchase in order to get exactly the right length?

      Beware: the fence is going to be very long!

      Input

      The first line of the input file contains the number of cases, T. T test cases follow.

      Each test case consists of two lines. The first line contains space-separated integers L and N. These represent the total length of the fence, and the number of different board lengths that can be purchased. The second line contains N space-separated integers B1, B2, ..., BN, representing all the possible board lengths.

      Output

      For each test case, output one line containing "Case #x: M", where x is the case number (starting from 1) and M is as follows:

      • If it is possible to purchase one or more boards so that their total length is exactly equal to L, then M should be the minimum number of boards required to do this.
      • Otherwise, M should be the string "IMPOSSIBLE".

      Limits

      1 ≤ T ≤ 50.
      1010L ≤ 1018.

      1 ≤ N ≤ 100.

      1 ≤ Bi ≤ 100000.

      All the Bi values in a single test case are distinct.

      Example

      Input:
      2
      10000000001 3
      23 51 100
      10000000001 3
      100 52 22

      Output:
      Case #1: 100000004
      Case #2: IMPOSSIBLE



      Added by:Phan Công Minh
      Date:2010-06-22
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:GCJ 2010









      SPOJ Problem Set (classical)

      6852. Fish

      Problem code: CT16E

      n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.

      Input

      The first line contains integer n (1 ≤ n ≤  18) — the amount of fish in the lake. Then there follow n lines with n real numbers each — matrix a. aij (0 ≤ aij  ≤ 1) — the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij = 1 -  aji. All real numbers are given with not more than 6 characters after the decimal point.

      Output

      Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.

      Example

      Input:
      5
      0 1 1 1 1
      0 0 0.5 0.5 0.5
      0 0.5 0 0.5 0.5
      0 0.5 0.5 0 0.5
      0 0.5 0.5 0.5 0

      Output:
      1.000000 0.000000 0.000000 0.000000 0.000000 

      Added by:Phan Công Minh
      Date:2010-06-22
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Codeforces









      SPOJ Problem Set (classical)

      6860. Asistent

      Problem code: ASISTENT

      You are given a permutation of first N natural numbers on which you are to perform K operations of following type: given integers A and B, your task is to swap elements on positions A and B in permutation and then output permutation rank modulo 1000 000 007.

      Note: Difference from original task is that elements remain swapped after query.

      Input

      On first line of standard input you are given two integers (2 ≤ N ≤ 50 000, 1 ≤ K ≤ 30 000), length of permutation and number of operations.
      On the next line there is permutation of first N natural numbers.
      In next K lines there are two integers A, B ( 1 ≤ A, B ≤ N ).

      Output

      Output permutation rank after applying each of K operations.

      Example

      Input:
      5 3
      1 5 4 2 3
      1 3
      2 3
      2 5

      Output:
      91
      77
      90

      Added by:Ivan Kataniæ
      Date:2010-06-23
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Modified task from Croatian IOI Team Selection Test









      SPOJ Problem Set (classical)

      6885. Wonkas Oompa-Impa Dilemma

      Problem code: WONKA1

           Willy Wonka, the amazing Chocolatier, appears to have a serious predicament at hand. You see, the worker population of his large factory, which consists of 100% Oompa Loompas, is facing a massive decline. This started off because of the fatal accidents in the testing of new Wonka products, but the decline has grown ever since then as old age was slowly factored into the equation. Because Oompa Loompas are as of yet a completely male tribe, they cannot simply reproduce amongst themselves to make up for their dying comrades. 

           So Willy Wonka has travelled out into the uncharted terrain of LoompaLand once more in an attempt to find wives for the Oompa Loompas. This trip is not fruitless, since he soon comes across the Impa Limpas, a tribe of civilized females in search of husbands.

           Problem solved, you say?? Well, not exactly. Since these are civilized women who have embraced the power of logic and wisdom, they will not give consent to marry savages. To test the Oompa Loompas' intellectual capacity, they have set up a task for them. Standing at an angle (possibly perpendicular) to a completely flat field  in the dead center of LoompaLand , the Impa Limpas have set up 2 totem poles facing each other. One belongs to the Impa Limpas while the other belongs to the Oompa Loompas.

           The objective of this task, given the ratio of descent of each totem pole (this ratio is how many degrees the totem pole falls per second), is to determine how many seconds apart the totem poles should be pushed so that they end up with their tops touching and all motion stopped. Willy Wonka knows that the angle at which a totem pole initially stands at in relation to the field will not determine the direction it falls in, only the direction of the push will do this (which should normally be towards the other totem pole). No matter what the situation, you can assume that all motion is stopped once the tops of the poles meet; keep in mind that gravity has nothing to do with this problem.

          The Impa Limpas are gracious with this task and have provided a 2D representation (done with a Cartesian Plane) of their totem poles' set-up to the Oompa Loompas, but they're not THAT gracious... they have rotated the actual diagram in relation to some point by some degrees, so the field may appear to be elevated. Since Oompa Loompas are, in fact, mostly savages, Willy Wonka has no faith in their problem solving capabilities. He attempted to solve this task himself, but seeing as how he dropped out of school early to go into the chocolate making business, his math skills aren't that great. So he has turned to his last hope: you (the boy (or girl...he forgets which) he inspired to become a programmer). Willy Wonka will give you 6 pieces on information: H1 and H2 (the points of the tops of the totem poles), B1 and B2 (the points of the bottom of the totem poles), and A1 and A2 (the ratio of decent of each totem pole). You are to solve this task for your childhood hero at all costs! Don't let Willy down.         

       

      Input

      The first line contains an integer T (with 1<= T <= 10000), specifying the number of test cases that will follow.

      Each of the following T lines contain 4 (x,y) coordinates giving 4 seperate points on the Cartesian Plane: H1, B1, H2, and B2 (-50000<= x, y <= 50000), in that order and 2 real numbers A1 and A2 (0 < A1, A2<= 90), giving each totem pole's degree of descent per second after initial push.

      Output

      Output is a single real number S (rounded off to the nearest 1000th), where S is  the absolute value of the difference in the number of seconds that each totem pole has in the air after it has been pushed before all motion has been stopped by the Oompa Loompas' and the Impa Limpas' totem poles meeting. In the case that this requirement is never met (say, for instance, that the totem poles come crashing down  onto the field without their tops ever meeting) then the program should output "-1".

      Example


      Input:

      3
      0 5 0 0 6 5 6 0 1 1
      -1 6 -4 5 -1 3 -2 1 0.5 0.25
      4 -1 3 -1 4 -5 3 -5 12 10.6
       
       
      Output:

      0.000
      61.087
      -1



      Input Explanation:
      CASE 1:

      H1 Coordinates: (0,5)
      B1 Coordinates: (0,0)
      H2 Coordinates: (6,5)
      B2 Coordinates: (6,0)
      A1 Ratio : 1 degree drop per 1 second (clockwise, in this case)
      A2 Ratio : 1 degree drop per 1 second (counter-clockwise, in this case)

      CASE 2:

      H1 Coordinates: (-1,6)
      B1 Coordinates: (-4,5)
      H2 Coordinates: (-1,3)
      B2 Coordinates: (-2,1)
      A1 Ratio : 0.5 degree drop per 1 second
      A2 Ratio : 0.25 degree drop per 1 second

      CASE 3:


      H1 Coordinates: (4,-1)
      B1 Coordinates: (3,-1)
      H2 Coordinates: (4,-5)
      B2 Coordinates: (3,-5)
      A1 Ratio : 12 degree drop per 1 second
      A2 Ratio : 10.6 degree drop per 1 second



      Output Explanation:

      CASE 1: It takes both totem poles the exact same amount of time to reach the point
      where their tops hit each other. The difference as expressed through S is thus 0.

      CASE 2: For the tops of the totem poles to meet, one totem pole must be pushed
      approximately 61.087 seconds before the other.

      CASE 3: The tops of the totem poles will never meet, so you must print "-1" as shown.



      Hint:


      Pencil and Paper is the way to go!








      Added by:Ammar Qadri
      Date:2010-06-29
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:An Original (By Ammar Qadri)









      SPOJ Problem Set (classical)

      6893. Power Sums

      Problem code: PWSUM

      suma

      Everyone knows that we can express sums of form sigma i = 1 to x ( i^k ) as polynomials
      of degree k+1. Most people find it hard to derive actual formulas for such sums, so
      we'd like to have a program that does that for us! You are given a nonnegative
      integer K, and you're asked to compute the coefficient representation of the polynomial
      which defines the sum shown above. However, we'd like to simplify your computation
      so you only have to output the formula modulo 10007. ( A formula which correctly computes
      the remainder of the sum when divided by 10007, for any natural x ).

      Everyone knows that we can express sums this form as polynomials of degree k+1. Most people find it hard to derive actual formulas for such sums, so we'd like to have a program that does that for us! You are given a nonnegative integer K, and you're asked to compute the coefficient representation of the polynomial which defines the sum shown above. However, we'd like to simplify your computation so you only have to output the formula modulo 10007. ( A formula which correctly computes the remainder of the sum when divided by 10007, for any natural x ).

       

      Input

      The first and only line of input contains a nonnegative integer k ( 0 <= k <= 300 ): the power we use in our sum.

       

      Output

      The first and only line of output should contain the canonic coefficient representation of the formula. To elaborate, this should be the form of your output:

      ak+1xk+1 + akxk + ak-1xk-1 ... a0x0

      ai here represents the coefficient that stands by the i-th power of x. As we only wish to find the formula modulo 10007, all the coefficients should be from interval [0, 10006] of integers. See the sample input and output for further clarification.

       

      Example

      Input:
      1
      
      Output:
      
      5004x^2 + 5004x^1 + 0x^0

      Input:
      3
      Output:
      2502x^4 + 5004x^3 + 2502x^2 + 0x^1 + 0x^0


      Added by:Gustav Matula
      Date:2010-06-30
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      6895. Maximum Edge of Powers of Permutation

      Problem code: MEPPERM

      For a directed graph G where any vertex v has two weights Av and Bv, we call Au+Bv the weight of a edge (u,v). Let MaxEdge(G) be the maximum weight of the edges of G.

      Given a permutation P on 1..n, we can derive a directed graph G=(V,E) where V={1,..,n} and (u,v) in E iff P(u)=v. Your task is to compute MaxEdge(Pk) for every k in 0..q-1.

      Input

      The first line contains a positive integer n.
      The second line contains n integers in {1,..,n}, denoting the permutation P.
      The third and the fourth line both contain n natural numbers, A1,..,An and B1,..,Bn respectively.
      The fifth line contains a positive integer q.

      Output

      The only one line contains q integers MaxEdge(P0),..,MaxEdge(Pq-1), separated by a single space.

      Example

      Input:
      3
      3 2 1
      0 1 2
      2 2 0
      5

      Output:
      3 4 3 4 3

      Constraint

      n <= 66000
      Ai,
      Bi <= 16
      q <= 106

      Notice

      The time limit is somehow strict. Please do not spoil the problem with a cheating solution.

      Description updated on 2010-7-11


      Added by:Lox
      Date:2010-07-01
      Time limit:6s-29s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Own problem









      SPOJ Problem Set (classical)

      6898. Substring Problem

      Problem code: SUB_PROB


      String Matching is an important problem in computer science research and finds applications in Bioinformatics, Data mining,pattern recognition, Internet security and many more areas.

      The problem we consider here is a smaller version of it. You are given a string M and N other strings smaller in length than M. You have to find whether each of these N strings is a substring of M. All strings consist of only alphanumeric characters.

      You are required to write a C/CPP code to solve the problem.

      Input

      Input to the program consists of a series of lines. The first line contains the string M (no more than 100000 characters long). The next line contains an integer N (<1000) the number of query strings. Each of the next N lines contain a string S (each of which is no more than 2000 characters long).

      Output

      Output should consist of N lines each with a character 'Y'/'N' indicating whether the string S is a substring of String M or not.

      Example

      Input:
      abghABCDE
      2
      abAB

      ab


      Output:
       
      N
      Y

      Note: The test data for this problem not only consist of the official test cases from the contest,as well some cases of my own.

      A testcase is added on 25.7.2010, after rejudging 3 users loose accepted.

       


      Added by:.:: Debanjan ::.
      Date:2010-07-02
      Time limit:0.600s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 C99 strict
      Resource:Codefest 2010 CW R#2









      SPOJ Problem Set (main)

      6906. Raining Parabolas

      Problem code: RPAR


       

      It's raining parabolas!
      Nowdays you just can't predict what'll fall on your head tomorrow..
      Because we don't care about the nature, it is now striking back:
         it's raining parabolas!
      The parabolas that are falling are given in form of quadratic
      fuctions: f(x) = ax^2 + bx + c. The ground can be defined as a line
      with N blocks, numbered from 0 to N-1, initially having height 0.
      At some point, a block can have some positive height, but when it exceeds
      10006 ( we don't actually know why, but measurements have shown it is a
      weird regularity.. ) it falls back to 0 . When a parabola falls on the ground, 
      it interacts with its current configuration ( the parabolas that have
      fallen before it ) by summing with them.
      Today you somehow came in possesion of some sort of schedule which defines
      the order in which the parabolas will fall on the ground. Apart from that, 
      you're interested total heights ( sums of heights ) of consecutive blocks
      of ground. 
      You're given two integers: N and M ( 1 <= N, M <= 100000 ). N specifies
      the number of blocks on the floor, and M is the number of queries.
      As we already said, we have two types of queries of form:
         0 x0 x1 a b c ( x0 <= x1, 0 <= a, b, c <= 10006 )
            this type of query just tells you that a parabola has
            fallen into the interval [x0, x1], and it function is f(x) = ax^2 + bx + c
         1 x0 x1
            this is the type of query you have to answer - output the sum of heights
            of all the blocks from interval [x0, x1] modulo 10007
      All numbers in the input are integers.

      Nowdays you just can't predict what'll fall on your head the next day.. Because we don't care about the nature, it is now striking back: it's raining parabolas!

      The parabolas that are falling are given in form of quadratic functions: f(x) = ax2 + bx + c. The ground can be defined as a line with N blocks, numbered from 0 to N-1, initially having height 0. At some point, a block can have some positive height, but when it exceeds 10006 ( we don't actually know why, but measurements have shown it is a weird regularity.. ) it falls back to 0. When a parabola falls on some block, it interacts with its current configuration ( the parabolas that have fallen there before it ) by summing with it. More precisely, if we are given an interval [x0, x1] in which the next parabola will fall, and the function of our parabola is f(x) ( defined above ), some block i ( x0  <= i <= x1 ), with height hi, the new height of that block becomes (hi + f(i)) modulo 10007.

      Today you somehow came in possesion of some sort of schedule which defines the order in which the parabolas will fall on the ground. Apart from that, you're interested total heights ( sums of heights ) of consecutive blocks of ground. When we want to find the total height of some interval [x0, x1], we're looking for the sum of hi for all i ( x0 <= i <= x1 ) modulo 10007.

      Before the first parabola falls, the ground is flat ( all heights are 0 ).

      Input

       

      The first line of input contains two integers: N and M ( 1 <= N, M <= 100000 ). N specifies the number of blocks on the floor, and M is the number of queries. Each of the next M lines contains a query. As we already said, we have two types of queries of form:

         0 x0 x1 a b c (0 <= x0 <= x< N, 0 <= a, b, c <= 10006, all integers )

            this type of query just tells you that a parabola has

            fallen into the interval [x0, x1], and its function is f(x) = ax2 + bx + c


         1 x0 x( 0 <= x0 <= x1 < N, all integers )

            this is the type of query you have to answer - output the sum of heights

            of all the blocks from interval [x0, x1] modulo 10007

       

      Output

      For each query of type 1, output a single line containing the sum of all the heights in the given interval modulo 10007.

      Example

      Input:
      10 2
      0 0 9 1 0 0
      1 0 3
      Output:
      14 

      (the sum of the first 4 squares ( from 0 to 3 ) is 14 )

      Added by:Gustav Matula
      Date:2010-07-05
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      6917. Catch Sheep

      Problem code: XYYHHTT

      XiYangYang is a kind of lovely and rare sheep. They live in a peaceful land which can be describled as a tree with N cities (nodes).

      Now you have K robots. They will start at a same point and travel each edge at least once so that all XiYangYang will be caught. All your robots can stop at any city in the land. Because of expensive oil, you want minimize the total distance that your robots walk.

      Input

      First line : N K ( N<=15000, K<=30 )

      Next N-1 lines: a b c (city a and city b are connected with a road whose length is c (1<=a,b<=N , 0<=c<=100)

      Output

      N lines: The total distance that your robots walk if they all start at city i

      Example

      Input:
      5 3
      1 2 7
      2 3 5
      3 4 14
      3 5 8
      
      Output:
      42
      39
      34
      42
      42
      Hint: my solution can get AC in 0.75~1 second.

      Added by:刘启鹏
      Date:2010-07-07
      Time limit:1s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:LvWeiCong(吕伟聪) at China NOI WinterCamp 2010









      SPOJ Problem Set (classical)

      6926. Tree game

      Problem code: CT23E

      Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree.

      Input

      The first input line contains integer number n (1 ≤ n ≤ 700) — amount of vertices in the tree. The following n - 1 lines contain the description of the edges. Each line contains the pair of vertices' indexes, joined by an edge, ai, bi (1 ≤ ai, bi  ≤ n). It's guaranteed that the graph described in the input is a tree.

      Output

      Output the only number — the maximum product of sizes of the connected components, that Bob can get after deleting some of the tree's edges.

      Example

      Input:
      8
      1 2
      1 3
      2 4
      2 5
      3 6
      3 7
      6 8


      Output:
      18

      Added by:Phan Công Minh
      Date:2010-07-12
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Codeforces









      SPOJ Problem Set (classical)

      6949. PIN

      Problem code: CTOI10D2

      Martin has just been hired as a computer administrator in a big company. The company did not change its authorization system since 1980s. Every person has a four-digit personal identification number (PIN). Nobody uses usernames or passwords, you can login just by typing your PIN. As the company grew, they added the possibility to use letters as well, but the length of the PIN remained the same.

      Martin is not happy with the situation. Suppose there are people whose PINs differ only at a single place, for example 61ab and 62ab. If the first person accidentally presses 2 instead of 1, the system would still let him in. Martin would like to make the statistics about the PINs currently in use, in particular, compute the number of pairs of PINs that differ at 1, 2, 3 or 4 positions. He hopes that these numbers will be alarming enough to convince his boss to invest in a better system.

      Task specification

      Given the list of PINs and an integer D, find the number of pairs of PINs that differ at exactly D positions.

      Input specification

      The first line of the input contains two space-separated positive integers N and D, where N is the number of PINs and D is the chosen number of differences. Each of the following N lines contains a single PIN.

      Constraints

      You may assume that in all test cases 2\leq  N\leq 50\,000 and 1 \le D \le 4.

      Each PIN is of length 4 and each character is either a digit or a lowercase letter between 'a' and 'z', inclusive. You may assume that all PINs in the input are different.

      In test cases worth 15 points, N\leq 2000.

      In test cases worth 60 points, D\leq 2. Out of those, in test cases worth 30 points, D = 1.

      In test cases worth 75 points, every PIN will only consist of digits or lowercase letters between 'a' and 'f', inclusive. Thus it can be viewed as a hexadecimal number.

      Output specification

      Output a single line with a single number: the number of pairs of PINs that differ at exactly D positions.

      Examples

      input:

      4 1
      0000
      a010
      0202
      a0e2

      output:

      0

      For these PINs each pair of PINs differs at more than one position.

      input:

      4 2
      0000
      a010
      0202
      a0e2

      output:

      3

      There are three pairs that differ at exactly 2 positions: (0000,a010), (0000,0202), and (a010,a0e2).


      Added by:Phan Công Minh
      Date:2010-07-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:CEOI 2010









      SPOJ Problem Set (classical)

      6950. A HUGE TOWER

      Problem code: CTOI10D3

      The ancient Babylonians decided to build a huge tower. The tower consists of N cubic building blocks that are stacked one onto another. The Babylonians gathered many building blocks of various sizes from all over the country. From their last unsuccessful attempt they have learned that if they put a large block directly onto a much smaller block, the tower will fall.

      Task specification

      Each two building blocks are different, even if they have the same size. For each building block you are given its side length. You are also given an integer D with the following meaning: you are not allowed to put block A directly onto block B if the side length of A is strictly larger than D plus the side length of B.

      Compute the number of different ways in which it is possible to build the tower using all the building blocks. Since this number can be very large, output the result modulo 109 + 9.

      Input specification

      The first line of the input contains two positive integers N and D: the number of building blocks and the tolerance respectively.

      The second line contains N space-separated integers; each represents the size of one building block.

      Constraints

      All numbers in the input files are positive integers not exceeding 109.

      N is always at least 2.

      In test cases worth 70 points N will be at most 70.

      Out of those, in test cases worth 45 points, N will be at most 20.

      Out of those, in test cases worth 10 points, N will be at most 10.

      For some of the test cases the total number of valid towers will not exceed 1\,000\,000. These test cases are worth 30 points in total.

      For the last six test cases (worth 30 points) the value of N is larger than 70. No upper bound on N is given for these test cases.

      Output specification

      Output a single line containing a single integer: the number of towers that can be built, modulo 1\,000\,000\,009.

      Examples

      input:

      4 1
      1 2 3 100

      output:

      4

      We can arrange the first three blocks in any order, except for 2,1,3 or 1,3,2. The last block has to be at the bottom.

      input:

      6 9
      10 20 20 10 10 20

      output:

      36

      We are not allowed to put a cube of size 20 onto a cube of size 10. There are six ways to order the cubes of size 10, and six ways to order the cubes of size 20.


      Added by:Phan Công Minh
      Date:2010-07-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:CEOI 2010









      SPOJ Problem Set (classical)

      6951. MP3 Player

      Problem code: CTOI10D1

      The MP3 Player

      Georg's new MP3 player has many interesting features, one of them being the key lock. All the keys are locked after more than T seconds of inactivity. After the key lock is engaged, no key performs its original function, but if any key is pressed, the key lock is disengaged.

      For example, assume that T = 5 and the player is currently locked. Georg presses the key A, waits for 3 seconds, presses the key B, waits for 5 seconds, presses C, waits for 6 seconds, and presses D. In this case only the keys B and C perform their regular functions. Note that the keys became locked between C and D was pressed.

      Sound level of the MP3 player is controlled by the + and - keys, increasing and decreasing volume by 1 unit respectively. The sound level is an integer between 0 and Vmax. Pressing the + key at volume Vmax or pressing the - key at volume 0 leaves the volume unchanged.

      Task specification

      Georg does not know the value of T. He wanted to find it by an experiment. Starting with a locked keyboard, he pressed a sequence of N + and - keys. At the end of the experiment Georg read the final volume from the player's display. Unfortunately, he forgot to note the volume before his first keypress. For the purpose of this task, the unknown initial volume will be denoted V1 and the known final volume will be denoted V2.

      You are given the value V2 and a list of keystrokes in the order in which Georg made them. For each key, you are given the type of the key (+ or -) and the number of seconds from the beginning of the experiment to the moment when the key was pressed. The task is to find the largest possible integer value of T which is consistent with the outcome of the experiment.

      Input specification

      The first line of the input contains three space-separated integers N, Vmax and V2 (0 \leq V_2 \leq V_{max}). Each of the next N lines contains a description of one key in the sequence: a character + or -, a space and an integer Ci (0 \leq C_i \leq 2\cdot 10^9), the number of seconds from the beginning of the experiment. You may assume that the keypresses are in sorted order and that all times are distinct (i.e., Ci < Ci + 1 for all 1 \leq i < N).

      Constraints

      You may assume that 2 \leq N \leq 100\,000 and 2 \leq V_{max} \leq 5\,000.

      In test cases worth 40 points N \leq  4\,000.

      In test cases worth 70 points N \cdot  V_{max} \leq 400\,000.

      Output specification

      If T can be arbitrarily large, output a single line containing the word "infinity" (quotes for clarity).

      Otherwise, output a single line containing two integers T and V1 separated by a single space.

      The values must be such that carrying out the experiment with locking time T starting at volume V1 gives the final volume V2. If there are multiple possible answers, output the one with the largest T; if there are still multiple possible answers, output the one with the largest V1.

      (Note that at least one solution always exists: for T = 0 none of the keys performs its action, so it suffices to take V1 = V2.)

      Examples

      input:

      6 4 3
      - 0
      + 8
      + 9
      + 13
      - 19
      - 24

      output:

      5 4

      For T = 5 the keys perform the following actions: unlock, unlock, +, +, unlock, -.

      For any V_1\in\{2,3,4\} we would get V2 = 3. Note that the output contains the largest possible V1.

      For T\geq 6 the last two keystrokes will both be active, hence it will be impossible to have V2 = 3.


      input:

      3 10 10
      + 1
      + 2
      + 47

      output:

      infinity

      If V1 = 10 then for any T we'll have V2 = 10.


      Added by:Phan Công Minh
      Date:2010-07-17
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:CEOI 2010









      SPOJ Problem Set (classical)

      6956. IOI2009 Mecho

      Problem code: CTOI09_1

      Mecho the bear has found a little treasure - the bees' secret honeypot, which is full of honey! He was happily eating his newfound treasure until suddenly one bee saw him and sounded the bee alarm. He knows that at this very moment hordes of bees will emerge from their hives and start spreading around trying to catch him. He knows he has to leave the honeypot and go home quickly, but the honey is so sweet that Mecho doesn't want to leave too soon. Help Mecho determine the latest possible moment when he can leave.

      Mecho's forest is represented by a square grid of by unit cells, whose sides are parallel to the north-south and east-west directions. Each cell is occupied by a tree, by a patch of grass, by a hive or by Mecho's home. Two cells are considered adjacent if one of them is immediately to the north, south, east or west of the other (but not on a diagonal). Mecho is a clumsy bear, so every time he makes a step, it has to be to an adjacent cell. Mecho can only walk on grass and cannot go through trees or hives, and he can make at most steps per minute. At the moment when the bee alarm is sounded, Mecho is in the grassy cell containing the honeypot, and the bees are in every cell containing a hive (there may be more than one hive in the forest). During each minute from this time onwards, the following events happen in the following order:

      • If Mecho is still eating honey, he decides whether to keep eating or to leave. If he continues eating, he does not move for the whole minute. Otherwise, he leaves immediately and takes up to steps through the forest as described above. Mecho cannot take any of the honey with him, so once he has moved he cannot eat honey again.
      • After Mecho is done eating or moving for the whole minute, the bees spread one unit further across the grid, moving only into the grassy cells. Specifically, the swarm of bees spreads into every grassy cell that is adjacent to any cell already containing bees. Furthermore, once a cell contains bees it will always contain bees (that is, the swarm does not move, but it grows).

      In other words, the bees spread as follows: When the bee alarm is sounded, the bees only occupy the cells where the hives are located. At the end of the first minute, they occupy all grassy cells adjacent to hives (and still the hives themselves). At the end of the second minute, they additionally occupy all grassy cells adjacent to grassy cells adjacent to hives, and so on. Given enough time, the bees will end up simultaneously occupying all grassy cells in the forest that are within their reach. Neither Mecho nor the bees can go outside the forest. Also, note that according to the rules above, Mecho will always eat honey for an integer number of minutes. The bees catch Mecho if at any point in time Mecho finds himself in a cell occupied by bees.

      Task

      Write a program that, given a map of the forest, determines the largest number of minutes that Mecho can continue eating honey at his initial location, while still being able to get to his home before any of the bees catch him.

      Constraints

      - the size (side length) of the map
      - the maximum number of steps Mecho can take in each minute

      Input

      The input contains several testcases.

      The fist line contains the number of testcase T.

      Each testcase has the form as following:

      • The first line contains the integers and , separated by a space.
      • The next lines represent the map of the forest. Each of these lines contains characters with each character representing one unit cell of the grid. The possible characters and their associated meanings are as follows:

        T denotes a tree G denotes a grassy cell M denotes the initial location of Mecho and the honeypot, which is also a grassy cell D denotes the location of Mecho's home, which Mecho can enter, but the bees cannot. H denotes the location of a hive

      Note: It is guaranteed that the map will contain exactly one letter M, exactly one letter D and at least one letter H. It is also guaranteed that there is a sequence of adjacent letters G that connects Mecho to his home, as well as a sequence of adjacent letters G that connects at least one hive to the honeypot (i.e., to Mecho's initial location). These sequences might be as short as length zero, in case Mecho's home or a hive is adjacent to Mecho's initial location. Also, note that the bees cannot pass through or fly over Mecho's home. To them, it is just like a tree.

      Output

      For each test , your program must write to standard output a single line containing a single integer: the maximum possible number of minutes that Mecho can continue eating honey at his initial location, while still being able to get home safely. If Mecho cannot possibly reach his home before the bees catch him, the number your program writes to standard output must be instead.

      Grading

      For a number of tests, worth a total of 40 points, will not exceed 60.

      Example

      For the input data:

       1

      7 3
      TTTTTTT
      TGGGGGT
      TGGGGGT
      MGGGGGD
      TGGGGGT
      TGGGGGT
      THHHHHT

      the correct result is:

      1

      Explanation of the example: After eating honey for one minute, Mecho can take the shortest path directly to the right and he will be home in another two minutes, safe from the bees.

      For the input data:

      1

      7 3

      TTTTTTT

      TGGGGGT

      TGGGGGT

      MGGGGGD

      TGGGGGT

      TGGGGGT

      TGHHGGT

      the correct result is:

      2

      Explanation of the example: After eating honey for two minutes, Mecho can take steps during the third minute, then steps during the fourth minute and steps during the fifth minute.


      Added by:Phan Công Minh
      Date:2010-07-19
      Time limit:10s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:IOI 2009









      SPOJ Problem Set (classical)

      6957. Partial Palindrome

      Problem code: PARTPAL

      Fernando is president of country named Palindromia. Every two years there are elections in Palindromia, but not normal elections. Elections in Palindromia are preformed in next steps:

      • Candidate which at the moment isn't president gives to the current president one string O, which consist only of upper-case letters of english alphabet and character '?', string U, which consist only of upper-case letters of english alphabet, and integer K.
      • Current president has one day to compute all longest palindromes in the first string by the folowing rules:
        • Every '?' in O is substituted with one letter from U, i-th '?' in O with i-th letter in U.
        • Every time he search for palindromes, he may substitute some '?' with any letter, at most K-times.
        • If he finds palindrome, he goes to step 1.
      • If he doesn't succeed, the candidate becomes the new president
      • If there are more candidates, go to step one.

      Fernando wants to stay president for at least two more years, so he asks you to write program which solves his problem.


      Input

      First line of input will contain string O ( 1 <= lenght of O <= 5 * 10^5 ), string which Fernando must compute to stay president. O will consist only of upper-case letters of english alphabet and character '?'. You may assume there is at least one '?' in O.

      Second line will contain string U, string with leads for '?'s. i-th letter in U corespond to i-th '?' in O. U will consist only of upper-case letters of english alphabet.

      Third line will contain integer K ( 0 <= K <= 300 ), number of replacements.

      It is guraranteed that there will be not more than 300 '?'s.

      Output

      In first line of output print integer S, lenght of the longest palindrome that Fernando could find.

      In Second and next lines print string Pi and integer Li, longest palindrome and position where it starts. Each Pi must contain only upper-case letters of english alphabet.

       

      Notes:

      • you must print all longest palindromes, in alphabeticaly increasing order
      • if two or more palindromes starts at the same position, print only one of them

      Example

      Input:
      UDOVICAB??IVODUANAVOL?MILOVANA
      CCA
      1

      Output:
      15
      ANAVOLIMILOVANA 16
      UDOVICABACIVODU 1


      Note that both palindromes have 1 letter which Fernando has changed.




      Input:
      ABCDE??ABCDE??
      ABCD
      1

      Output:

      5
      CBABC 6


      Input:
      ABCDE??ABCDEFG
      FG
      0

      Output:
      1
      A 1
      A 8
      B 2
      B 9
      C 10
      C 3
      D 4
      D 11
      E 5
      E 12
      F 13
      F 6
      G 7
      G 14


      Added by:Zvonimir Medic
      Date:2010-07-20
      Time limit:2s-2.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6









      SPOJ Problem Set (classical)

      6977. Odd Independent Sets

      Problem code: INDEPCNT

      Given integer N ( 1 <= N <= 60), output the number of Rooted Unlabeled Trees which have an odd number of independent sets.

      Rooted Unlabeled Tree: An Unlabeled Tree with a specified vertex as root and order amongst children does not matter. That is, two trees are considered equal if they are the same after some re-ordering of their non-root vertices. A rigorous definition is "two Rooted Unlabeled Trees T1 and T2 are equal if and only if there is a bijection f between T1 and T2 such that if root1 and root2 are the roots of T1 and T2 respectively, f(root1)=root2 and edge (u,v) is in T1 if and only if edge (f(u),f(v)) exists in T2"

      Independent Set: A set of vertices (possibly empty) is called an Independent Set if no two vertices of the set have an edge between them.

      Input

      First line contains T, the number of test cases.
      Next T lines contain one number each, N. 

      Output

      Output T lines, one per test case. Each line should contain the number of rooted unlabeled trees which have an odd number of independent sets. Output the answer modulo 1000000007. That is, if the actual answer is A, output A%1000000007. (This is just to keep computations within 64 bit integers.)

      Example

      Input:
      6
      1
      2
      3
      4
      5
      40
      Output:
      0
      1
      2
      2
      5
      632355321

      Added by:Subrahmanyam Velaga
      Date:2010-07-23
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6









      SPOJ Problem Set (classical)

      6978. Check 1324

      Problem code: PERMPATT

      Given a permutation P[1...n] of {1,2,...n}, you should output if the permutation contains a pattern of the form 1324. That is, do there exist indices  1 <= i1 < i2 < i3 < i4 <= n such that  P[i1] < P[i3] < P[i2] < P[i4]. For example, P = 6 8 5 4 9 3 7 2 1 10 contains one: the indices 1, 2, 7, 10 correspond to the sequence  6 8 7 10 which is a 1324 pattern.

      Input

      First line contains T, the number of test cases

      Each of the next T lines contains n (1 <= n <= 100000), followed by n integers, representing a permutation of [1,2,..,n].

      SUM( n * log2(n)) over all test cases <= 108. Do not assume anything else about the number of test cases or their distribution.

      Output

      Output T lines, one per test case: "yes"(without quotes) if the permutation contains a 1324 pattern or "no" (without quotes) otherwise.

      Warning: Huge I/O

      Example

      Input:
      2
      10 6 8 5 4 9 3 7 2 1 10
      10 5 3 4 7 9 10 8 6 2 1
      Output:
      yes
      no

      Added by:Subrahmanyam Velaga
      Date:2010-07-23
      Time limit:5s-50s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6









      SPOJ Problem Set (classical)

      6981. The Least Number

      Problem code: RNDORDER

      You are given n symbols a1, a2,..., an. You are told that there is a total ordering of the symbols. That is, there is a permutation [P1, P2,..., Pn] of [1,2,...,n] such that aP1< aP2 <...< aPn. You are trying to figure out the order by doing comparisons. The process you follow for determining the order is as follows:

      • Compare [a1, a2]
      • Compare [a2, a3], [a1, a3
      • Compare [a3, a4], [a2, a4], [a1, a4]
      • ....
      • ....
      • Compare [an-1,an], [an-2,an],..., [a1, an]

      Note that you compare in the order specified. That is you compare [a2, a3], then and only then do you compare [a1, a3].

      Definition of Compare[ai, aj] (i < j)

      • If Compare [ai, aj] = 1, it means ai > aj. If Compare[ai, aj] = -1, it means ai < aj
      • Compare is consistent. Suppose, that you queried [a2, a6] and it was already established [a2 < a6] (because for example a2 < a5 and a5 < a6 - since both of these comparisons happen earlier), then [a2, a6] returns -1.
      • If no relationship is known between ai and aj, Compare[ai, aj] = 1 with probablity 1/2 and -1 with probability 1/2

      Your task is to output the probability that a1 is the smallest element of the final ordering so obtained.

      Input

      First line contains T, the number of test cases

      Each of the next T lines contains one number each, n(1 <= n <= 1000). 

      Output

      Output T lines in total, one per test case: Probability that a1 is indeed the smallest element at the end of the comparisons. Your output will be judged correct if it differs by no more than 10-9 to the reference answer.

      Example

      Input:
      3
      1
      2
      3
      
      Output:
      
      1
      0.500
      0.3750000
      Explanation:
      n = 1 is trivial
      For n = 2, only comparison is [a1, a2]. a1 is lower with probability 1/2.
      For n = 3, a1 is not the least element if either (a1 > a2) or (a1 < a2 and a3 < a2 and a3 < a1). 
      So, probability that a1 is not the least element = 1/2 + 1/8 = 5/8. Probability that a1 is the least = 3/8 = 0.375.

      Added by:Subrahmanyam Velaga
      Date:2010-07-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6









      SPOJ Problem Set (classical)

      6985. Rearranging Digits

      Problem code: ARRANGE2

      Given A and B, how many numbers between A and B (with no leading 0's) rearrange their digits when multiplied by 2 ?

      Input :
      The first line contains the number of test cases T. T lines follow, containing two integers A and B.

      Output :
      Output T lines, one for each test case containing the desired answer for the corresponding test case.

      Sample Input :
      2
      1 100
      499875921 499875921

      Sample Output :
      0
      1

      Constraints :
      1 <= T <= 10000
      1 <= A <= B <= 10000000000 (10^10)


      Added by:Varun Jalan
      Date:2010-07-26
      Time limit:2s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem









      SPOJ Problem Set ()

      6986. Summing Slopes

      Problem code: SUMSLOPE

      A digit in a number N is a minima if it is lesser than both the digits adjacent to it. Similarly, a digit is a maxima if it is greater than both the digits adjacent to it. The slope of N is the number of digits in N (leaving out the first and the last digit) which are either a minima or a maxima. Given A and B, count the sum of the slopes of all numbers between A and B.

      Input :
      The first line contains the number of test cases T. Each of the next T lines contains two integers A and B.

      Output :
      Output T lines one for each test case, containing the required sum for the corresponding test case.

      Sample Input :
      3
      101 101
      1 100
      100 150

      Sample Output :
      1
      0
      19

      Constraints :
      1 <= T <= 50000
      1 <= A <= B <= 1000000000000000 (10^15)


      Added by:Varun Jalan
      Date:2010-07-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:own problem









      SPOJ Problem Set (classical)

      6988. Beer Machines

      Problem code: STJEPAN


       

      Little Stjepan lives in a village which can be represented as X-axis. In village there are N beer machines, machine i has x coordinate Pi and needs Ti seconds to produce 1 liter of beer.

      This year M tourists (one by one because there is only one guide, Stjepan) will visit his village, tourist i will arrive at point Ai, want to drink Li liters of beer but will have energy to walk at most Di seconds (that is Di units of length), he will walk to beer machine Stjepan suggests him and as soon as machine produces Li liters of beer tourist will be able to enjoy it.

      As Stjepan wants all tourists to come next year too he will choose machine for each tourist so that tourist can get a beer as soon as possible. Help Stjepan to do that and write program which will output minimal sum of passed times from arrival of tourist to getting a beer. If a tourist can't get a beer then his time is 0.

      Note that tourists are independent and machines can be used multiple times.

      Input

      On first line of standard input you are given two integers (2 ≤ N ≤ 250 000, 1 ≤ M ≤ 500 000), number of beer machines and number of tourists.

      Next 5 lines contain 4 integers (X0, A, B, C) each and they describe arrays P, T, A, L and D, respectively.
      With these four numbers i-th element of array is defined as Xi = 1 + ((Xi-1*A + B) mod C), where indices are 1-based and X0 is given in input.

      1 ≤ X0, A, B, C ≤ 109.

      Note: Author's solution doesn't depend on properties of pseudo-random generator.

      Output

      Output total time from task statement. Answer will fit in 64-bit signed integer.

      Example

      Input:
      
      3 4
      3 4 1 4 3 6 2 4 4 10 3 8 1 10 3 1 8 7 1 3 2 6
      1 3 2
      Output: 53
      Explanation: 
      Machines (P, T) : (2, 3), (6, 7), (4, 3)
      Tourists (A, L, D) : (6, 5, 6), (10, 7, 3), (2, 2, 6), (8, 4, 3)
      Tourist #1 -> Machine #3 -> 17 time units
      Tourist #2 -> No beer :( -> 0 time units
      Tourist #3 -> Machine #1 -> 6 time units
      Tourist #4 -> Machine #2 -> 30 time units

      Added by:Ivan Kataniæ
      Date:2010-07-27
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      6999. Avoiding SOS Grids

      Problem code: AVOIDSOS

      You are given a grid having N rows and M columns. Some squares are contain letters 'S' or 'O', whereas the other squares are unfilled. A filled grid is called "Avoiding SOS" if there is no occurance of the string "SOS" in the grid either vertically or horizontally. In how many ways can the grid be completed by filling the unfilled squares with either 'S' or 'O' such that the resultant grid is "Avoiding SOS" ?


      Input :
      The first line contains T the number of test cases. T test cases follow. The first line for the test case contains N and M, the number of rows and columns in the grid respectively. N lines follow, each containing M characters. The jth character in the ith line is a '.' if the corresponding square in the grid is unfilled, otherwise it contains either the letter 'S' or the letter 'O'. A blank line seperates two test cases.

      Output :
      Output T lines, one for each test case, containing the desired answer for the corresponding test case. Output each result modulo 1000000007.

      Sample Input :
      5
      2 3
      ...
      ...

      1 4
      ....

      3 3
      .O.
      S.S
      .O.

      1 3
      SOS

      1 3
      SOO

      Sample Output :
      49
      12
      9
      0
      1

      Constraints :
      1 <= T <= 100
      1 <= N,M <= 8


      Added by:Varun Jalan
      Date:2010-07-29
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem used for Indian ICPC training camp









      SPOJ Problem Set (classical)

      7001. Visible Lattice Points

      Problem code: VLATTICE

      Consider a N*N*N lattice. One corner is at (0,0,0) and the opposite one is at (N,N,N). How many lattice points are visible from corner at (0,0,0) ? A point X is visible from point Y iff no other lattice point lies on the segment joining X and Y.
       
      Input :
      The first line contains the number of test cases T. The next T lines contain an interger N
       
      Output :
      Output T lines, one corresponding to each test case.
       
      Sample Input :
      3
      1
      2
      5
       
      Sample Output :
      7
      19
      175
       
      Constraints :
      T <= 50
      1 <= N <= 1000000


      Added by:Varun Jalan
      Date:2010-07-29
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:own problem used for Indian ICPC training camp









      SPOJ Problem Set (main)

      7002. Buildings

      Problem code: BUILDING

      A certain city has M buildings, all having a width of 1. The ith building has height h_i units. The outline of the city can be seen by everyone passing along, and you wish to place an advertisement in front. You want the advertisement to be totally contained within the boundary defined by the outline of the city. The advertisement should be rectangular in shape, and its base should be at ground level. Also, it should have an integral height and its vertical edges should coincide with the vertical edges of the buildings. Now you wonder, for each building x, how many ways are there to place an advertisement such that it hides (fully or partially) building x ?

      Input :
      The first line contains an integer M, the number of buildings. The second line contains M space seperated integers, the heights of the buildings.

      Output :
      Output M integers. The ith integer is the number of possible advertisements which cover the ith building partially or fully.

      Sample Input :
      4
      2 1 4 4

      Sample Outout :
      5 6 12 10

      Constraints :
      1 <= M <= 100000
      1 <= h_i <= 10000


      Added by:Varun Jalan
      Date:2010-07-29
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK NODEJS PERL 6 PYTH 3.2.3 n SED
      Resource:own problem used for Indian ICPC training camp









      SPOJ Problem Set (classical)

      7010. Police Business

      Problem code: ACAB

      Cops are one of the most fascinating types of people. In the movies they are usually shown as fat and lazy, but they are so much more! Our today's specimen, officer Acab is, for example, very much into philosophy. All the criminals are afraid of Acab so when he appears in a city no criminals can come there. He's often engaged in car chases, so he usually asks himself the following questions: If I know a criminal has to travel from city a to city b, how many cities are there (other than a and b) such that there are no other cops there, and if I come to that city the criminal won't be able to accomplish his trip? If I sort those cities by distance from a, which one will be the k-th in the sorted list? How many roads are there such that there are no other cops on them, and if I'm present on that road the criminal won't be able to travel from a to b? Which is the k-th such road if I sort the available roads by their distance from a?


      Given a list of bidirectional roads that connect the cities write a program that will answer Acab's questions. In the beginning we know that there are no other cops in any of the cities. There will be one or more paths between each pair of cities.

      Sometimes Acab's cop-friends contact him to tell him they have entered a city or road. There is never more than one cop present in a city or on a road. Thus, when a road or city is reported for the second time, we assume the cop has left there. This only means that after each even report of the same city or a road there are no cops there, and for odd reports there is a cop there.


      Note: we define the distance of a road from a city as the minimum of the distances of its endpoints from that city. Even though Acab is a good cop, he doesn't have any special powers such as multilocation, so he can only be present in one city at a time. If you, for some reason, find two cities or roads equidistant from the city a, output the one with the smaller index. Also, the other cops aren't as good as Acab, so they only block Acab from visiting a city, and not the criminals.

      Input

      The first line of input contains two integers N and M (1 <= N <= M <= 100000).
      The next M lines contain a pair of integers a and b (1 <= a, b <= N).
      All the cities are numbered from 1 to N.
      The next line contains a single integer Q (1 <= Q <= 200000).
      The next Q lines contain queries. There are six possible types of queries:
          1 n   -  a cop has contacted Acab to let him know he's in city n
          2 e   -  a cop has contacted Acab to let him know he's on the road e
          3 a b  -  tell Acab how many cities he can block the criminal with
          4 a b  -  tell Acab how many roads he can block the criminal with
          5 a b k  -  tell Acab which is the k-th city he can block the criminal with
          6 a b k  -  tell Acab which is the k-th road he can block the criminal with

      Output

      For each query of type 3, 4, 5 or 6 output a single line containing the answer. If for a query of type 5 or 6 k is greater than the actual number of possible cities, output -1. Also, in queries 2 and 6 the number of the road is assumed to be its index from the input.

      Example

      Input:
      9 10
      1 2
      1 3
      2 4
      2 5
      4 5
      4 6
      3 7
      3 8
      7 8
      8 9
      10
      3 6 9
      4 6 9
      5 6 9 2
      6 6 9 2
      1 2
      5 6 9 2
      2 1
      6 6 9 2
      1 2
      5 6 9 2

      Output:
      5
      4
      2
      1
      1
      2
      2

      Explanation:
      In the first query, there are 5 blockable cities: 4, 2, 1, 3, 8.
      In the second query there are 4 blockable roads: 6, 1, 2, 10.
      In the third query the second city is 2 (4, 2, 1, 3, 8).
      In the fourth query the second road is 1 (6, 1, 2, 10).
      In the fifth query we've been reported there's a cop in city 2.
      In the sixth query the second blockable city is 1 (city 2 already contains a cop).
      In the seventh query we've been reported there's a cop on road 1.
      In the eighth query the second blockable road is 2 (road 1 already contains a cop).
      In the ninth query we've been reported the cop from city 2 has left.
      In the tenth query the second city is 2 again.


      Added by:Gustav Matula
      Date:2010-07-30
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:own problem









      SPOJ Problem Set (classical)

      7015. Party

      Problem code: CFPARTY

      n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.

      What is the maximum amount of people that could stay at the party in the end?

      Input

      The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).

      Output

      For each test output in a separate line one number — the maximum amount of people that could stay in the end.

      Example

      Input:
      1
      3
      
      Output:
      1
      

      Added by:Ефиме
      Date:2010-08-02
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Codeforces









      SPOJ Problem Set (classical)

      7019. Zig-Zag rabbit

      Problem code: ZIGZAG

      A N×N matrix is filled with numbers 1 to N2, diagonally in a zig-zag fashion.

      The table below shows numbers in the matrix for N = 6.

      1

      2

      6

      7

      15

      16

      3

      5

      8

      14

      17

      26

      4

      9

      13

      18

      25

      27

      10

      12

      19

      24

      28

      33

      11

      20

      23

      29

      32

      34

      21

      22

      30

      31

      35

      36

      There is a rabbit in the cell containing number 1. A rabbit can jump to a neighboring cell (up, down, left or right) if that cell exists.

      Given K valid rabbit jumps, write a program that will calculate the sum of numbers of all cells that rabbit visited (add the number to the sum each time rabbit visits the same cell). 

      Input

      The first line contains two integers N and K (1 ≤ N ≤ 100 000, 1 ≤ K ≤ 300 000), the size of the matrix and the number of rabbit jumps.

      The second line contains a sequence of K characters 'U', 'D', 'L' and 'R', describing the direction of each jump. The sequence of jumps will not leave the matrix at any moment.

      Output

      Output one integer, the sum of numbers on visited cells.

      Note: This number doesn't always fit in 32-bit integer type.

      Example

      Input:
      6 8
      DDRRUULL
      
      Output:
      47
      Input:
      3 8
      DDRRUULL
      
      Output:
      41
      Input:
      6 10
      RRRRRDDDDD
      
      Output:
      203

      Clarification for the first sample: The rabbit visits cells 1, 3, 4, 9, 13, 8, 6, 2 and 1. Clarification for the second sample: The rabbit visits cells 1, 3, 4, 8, 9, 7, 6, 2 and 1. Clarification for the third sample: The rabbit visits cells 1, 2, 6, 7, 15, 16, 26, 27, 33, 34 and 36.


      Added by:Luka Kalinovcic
      Date:2010-08-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6









      SPOJ Problem Set (classical)

      7022. Cow Patterns

      Problem code: CPATTERN

      A particular subgroup of K (1 <= K <= 25,000) of Farmer John's cows likes to make trouble. When placed in a line, these troublemakers stand together in a particular order. In order to locate these troublemakers, FJ has lined up his N (1 <= N <= 100,000) cows. The cows will file past FJ into the barn, staying in order. FJ needs your help to locate suspicious blocks of K cows within this line that might potentially be the troublemaking cows. 

      FJ distinguishes his cows by the number of spots 1..S on each cow's coat (1 <= S <= 25). While not a perfect method, it serves his purposes. FJ does not remember the exact number of spots on each cow in the subgroup of troublemakers. He can, however, remember which cows in the group have the same number of spots, and which of any pair of cows has more spots (if the spot counts differ). He describes such a pattern with a sequence of K ranks in the range 1..S. For example, consider this sequence: 

         1 4 4 3 2 1

      In this example, FJ is seeking a consecutive sequence of 6 cows from among his N cows in a line. Cows #1 and #6 in this sequence have the same number of spots (although this number is not necessarily 1) and they have the smallest number of spots of cows #1..#6 (since they are labeled as '1'). Cow #5 has the second-smallest number of spots, different from all the other cows #1..#6. Cows #2 and #3 have the same number of spots, and this number is the largest of all cows #1..#6. 

      If the true count of spots for some sequence of cows is: 

         5 6 2 10 10 7 3 2 9

      then only the subsequence 2 10 10 7 3 2 matches FJ's pattern above. 

      Please help FJ locate all the length-K subsequences in his line of cows that match his specified pattern.

      Input

      Line 1: Three space-separated integers: N, K, and S 

      Lines 2..N+1: Line i+1 describes the number of spots on cow i. 

      Lines N+2..N+K+1: Line i+N+1 describes pattern-rank slot i.

      Output

      Line 1: The number of indices, B, at which the pattern matches 

      Lines 2..B+1: An index (in the range 1..N) of the starting location where the pattern matches.

      Example

      Input:
      9 6 10
      5
      6
      2
      10
      10
      7
      3
      2
      9
      1
      4
      4
      3
      2
      1
      
      Output:
      1
      3
      

      Added by:Luka Kalinovcic
      Date:2010-08-06
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:USACO 2005 December Gold









      SPOJ Problem Set (classical)

      7023. Cookies

      Problem code: KOLACI

      Darko and Marko are twins and they love to eat cookies. Their grandma Mara loves to bake cookies, but she doesn't like the fact that Darko and Marko eat them too fast.

      To teach her grandsons to eat slower, Mara turned it into a game. Mara will bake N cookies and assign them with integers 1 to N. Then she will arrange them in a circle such that each cookie i is between to cookie i−1 and i+1 except for cookies 1 and N that are neighbors.

      Mara knows a recipe for 26 different types of cookies. We will denote a cookie type with lower case english letters 'a' to 'z'.

      Darko and Marko will each get one cookie every 5 minutes. Mara will say one integer out loud. Darko and Marko will search for a cookie with this number, but will eat two neighboring cookies. This procedure is repeated until one or two cookies are left on the table. Then the game ends and Mara eats the remaining cookies.

      The game can be represented with a sequence of (N−1) div 2 integers that Mara said out loud. For example, the illustrations above can be represented with a sequence (4, 8, 6). Two games are considered different if their respective sequences are different.

      After a few games Mara noticed that Marko and Darko often fight during the game. In fact, they fight every time when the two neighboring cookies are of different types because they can't decide which one will get which cookie.

      Mara decided to count the number of ways to play a game in a way to avoid such situations.

      Given a cookie type for each of N cookies, write a program that will calculate the number of ways to play a game such that Darko and Marko will not fight. This number can get very large, so output the remainder of division by 10007 instead.

      Input

      The first line contains one integer N (3 ≤ N ≤ 75), the number of cookies.

      The second line contains a sequence of N lower case english letters, types of cookies in order they are arranged in a circle.

      Output

      Output a single integer, the total number of ways to play a game that will prevent Darko and Marko from fighting modulo 10007.

      Example

      Input:
      8
      cibaboca
      
      Output:
      4
      Input:
      5
      aabab
      
      Output:
      5
      Input:
      11
      fffffffffff
      
      Output:
      388

      Clarification for the first example: This sample corresponds to illustration above. Four valid sequences are (4, 8, 2), (4, 8, 6), (8, 4, 2) i (8, 4, 6).

      Clarification for the second example: Five valid sequences are (3, 1), (5, 2), (4, 4), (4, 1) i (4, 2).

      Clarification for the third example: All cookies share the same type, so Darko and Marko can't get into fight no matter what. In each step Mara can say any integer remaining on the table, so the total number of games is equal to 11⋅9⋅7⋅5⋅3 = 10395. 388 is the remainder of division by 10007.


      Added by:Luka Kalinovcic
      Date:2010-08-06
      Time limit:12s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Croatian IOI team trials 2010









      SPOJ Problem Set (classical)

      7025. Roads in Berland

      Problem code: CT25C

      There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.

      Input

      The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of distances. j-th integer in the i-th row — di, j, the distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads.

      Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.

      Output

      Output k lines, each line contains one integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.

      Example

      Input:
      3
      0 4 5
      4 0 9
      5 9 0
      2
      2 3 8
      1 2 1




      Output:
      17
      12

      Added by:Phan Công Minh
      Date:2010-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Based on codeforces









      SPOJ Problem Set ()

      7034. Crashing Robots

      Problem code: CROBOTS

       

      In a modernized warehouse, robots are used to fetch the goods. Careful
      planning is needed to ensure that the robots reach their destinations with-
      out crashing into each other. Of course, all warehouses are rectangular,
      and all robots occupy a circular floor space with a diameter of 1 meter.
      Assume there are N robots, numbered from 1 through N. You will get to
      know the position and orientation of each robot, and all the instructions,
      which are carefully (and mindlessly) followed by the robots. Instructions
      are processed in the order they come. No two robots move simultane-
      ously; a robot always completes its move before the next one starts mov-
      ing.

       

      In a modernized warehouse, robots are used to fetch the goods. Careful planning is needed to ensure that the robots reach their destinations without crashing into each other. Of course, all warehouses are rectangular, and all robots occupy a circular floor space with a diameter of 1 meter. Assume there are N robots, numbered from 1 through N. You will get to know the position and orientation of each robot, and all the instructions, which are carefully (and mindlessly) followed by the robots. Instructions are processed in the order they come. No two robots move simultaneously; a robot always completes its move before the next one starts moving.

      A robot crashes with a wall if it attempts to move outside the area of the warehouse, and two robots crash with each other if they ever try to occupy the same spot.

       

      Input

       

      The first line of input is K, the number of test cases. Each test case starts with one line consisting of two integers, 1 ≤ A, B ≤ 100, giving the size of the warehouse in meters. A is the length in the EW-direction, and B in the NS-direction.

      The second line contains two integers, 1 ≤ N, M ≤ 100, denoting the numbers of robots and instructions respectively.
      Then follow N lines with two integers, 1 ≤ Xi ≤ A, 1 ≤ Yi ≤ B and one letter (N, S, E or W), giving the starting position and direction of each robot, in order from 1 through N. No two robots start at the same position.
      Finally there are M lines, giving the instructions in sequential order. An instruction has the following format:
      <robot #> <action> <repeat>
      Where <action> is one of:
      • L: turn left 90 degrees,
      • R: turn right 90 degrees, or
      • F: move forward one meter,

       

      and 1 ≤ <repeat> ≤ 100 is the number of times the robot should perform this single move.

       

       

      Output

      Output one line for each test case:

      • Robot i crashes into the wall, if robot i crashes into a wall. (A robot crashes into a wall if Xi = 0, Xi = A + 1, Yi = 0 or Yi = B + 1.)
      • Robot i crashes into robot j, if robots i and j crash, and i is the moving robot.
      • OK, if no crashing occurs.

       

      Only the first crash is to be reported.

       

      Example

      Input:
      4
      5 4
      2 2
      1 1 E
      5 4 W
      1 F 7
      2 F 7
      5 4
      2 4
      1 1 E
      5 4 W
      1 F 3
      2 F 1
      1 L 1
      1 F 3
      5 4
      2 2
      1 1 E
      5 4 W
      1 L 96
      1 F 2
      5 4
      2 3
      1 1 E
      5 4 W
      1 F 4
      1 L 1
      1 F 20
      
      
      Output:
      Robot 1 crashes into the wall
      Robot 1 crashes into robot 2
      OK
      Robot 1 crashes into robot 2
      

      Added by:Mohammad Kotb
      Date:2010-08-08
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:NCPC 2005









      SPOJ Problem Set (classical)

      7035. The Embarrassed Cryptographer

      Problem code: CRYPTON

       

      The young and very promising cryptogra-
      pher Odd Even has implemented the security
      module of a large system with thousands of
      users, which is now in use in his company.
      The cryptographic keys are created from the
      product of two primes, and are believed to be
      secure because there is no known method for
      factoring such a product effectively.

       

      The young and very promising cryptographer Odd Even has implemented the security module of a large system with thousands of users, which is now in use in his company. The cryptographic keys are created from the product of two primes, and are believed to be secure because there is no known method for factoring such a product effectively.

      What Odd Even did not think of, was that both factors in a key should be large, not just their product. It is now possible that some of the users of the system have weak keys. In a desperate attempt not to be fired, Odd Even secretly goes through all the users keys, to check if they are strong enough. He uses his very poweful Atari, and is especially careful when checking his boss’ key.

       

       

      Input

       

      The input consists of no more than 20 test cases. Each test case is a line with the integers 4 ≤ K ≤ 10^100 and 2 ≤ L ≤ 10^6 . K is the key itself, a product of two primes. L is the wanted minimum size of the factors in the key. The input set is terminated by a case where K = 0 and L = 0.

       

      Output

       

      For each number K, if one of its factors are strictly less than the required L, your program should output “BAD p”, where p is the smallest factor in K. Otherwise, it should output “GOOD”. Cases should be separated by a line-break.

       

      Example

      Input:
      143 10
      143 20
      667 20
      667 30
      2573 30
      2573 40
      0 0
      
      Output:
      GOOD
      BAD 11
      GOOD
      BAD 23
      GOOD
      BAD 31
      

      Added by:Mohammad Kotb
      Date:2010-08-08
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NCPC 2005









      SPOJ Problem Set (classical)

      7050. Necklace Decomposition

      Problem code: NECKDEC

       

      string clockwise on a ring, with the first
      character following on the last, starting at
      any character position and moving clock-
      wise on the ring until the character pre-
      ceeding the starting character is reached.
      A string is a necklace if it is the lexico-
      graphically smallest among all its cyclic
      rotations. For instance, for the string 01011 the cyclic rotations are
      (10110,01101,11010,10101,01011), and furthermore 01011 is the smallest
      string and hence, a necklace.

      The set of cyclic rotations of a string are the strings obtained by embedding the string clockwise on a ring, with the first character following on the last, starting at any character position and moving clockwise on the ring until the character preceeding the starting character is reached. A string is a necklace if it is the lexicographically smallest among all its cyclic rotations. For instance, for the string 01011 the cyclic rotations are (10110,01101,11010,10101,01011), and furthermore 01011 is the smallest string and hence, a necklace.

      Any string S can be written in a unique way as a concatenation S = T1 T2 . . . Tk of necklaces Ti such that Ti+1 < Ti for all i = 1, . . . , k − 1, and Ti Ti+1 is not a necklace for any i = 1, . . . , k − 1. This representation is called the necklace decomposition of the string S, and your task is to find it.
      The relation < on two strings is the lexicographical order and has the usual interpretation: A < B if A is a proper prefix of B or if A is equal to B in the first j − 1 positions but smaller in the jth position for some j. For instance, 001 < 0010 and 1101011 < 1101100.

      Input

      On the first line of the input is a single positive integer n, telling the number of test scenarios to follow. Each scenario consists of one line containing a non-empty string of zeros and ones of length at most 100.

      Output

      For each scenario, output one line containing the necklace decomposition of the string. The necklaces should be written as ’(’ necklace ’)’.

      Example

      Input:
      5
      0
      0101
      0001
      0010
      11101111011
      
      Output:
      (0)
      (0101)
      (0001)
      (001)(0)
      (111)(01111)(011)

      Added by:Mohammad Kotb
      Date:2010-08-08
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NCPC 2005









      SPOJ Problem Set (classical)

      7099. Advanced Edit Distance

      Problem code: ADVEDIST


      The edit distance of two strings S and T is the minimum number of edit operations that need to be done to transform S into T . The valid edit operations are:
      • Insert a single character at any position.
      • Modify an existing character.
      • Remove an existing character.
      For example, the edit distance of “pantera” and “aorta” is 5, because the following chain of
      edits is valid (and there is no shorter chain):
      “pantera” >>> “antera” >>> “aotera” >>> “aoera” >>> “aora” >>> “aorta”.

      We define the advanced edit distance in a similar way, but adding the swap of two adjacent characters as an extra valid operation. With this setting, the advanced edit distance of “pantera” and “aorta” is 4:
      “pantera” >>> “antera” >>> “antra” >>> “aotra” >>> “aorta”.


      You need to write a program that calculates the advanced edit distance of two given words.

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      two non-empty words, each of them of at most 1000 lowercase letters, separated by a single
      space. The last line of the input contains two asterisks separated by a single space and should
      not be processed as a test case.

      Output

      For each test case output a single line with an integer representing the advanced edit distance
      of the two input words.

      Example

      Input:

      pantera aorta
      zero zero
      * *

      Output:

      4
      0

      Added by:Pablo Ariel Heiber
      Date:2010-08-13
      Time limit:180s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2007









      SPOJ Problem Set (classical)

      7100. Back To The Polygon

      Problem code: BACKTPOL

      A simple polygon is a polygon that does not overlap with itself. A diagonal of a simple polygon
      is a segment within the polygon that connects two non-consecutive vertices. A triangulation
      of a simple polygon of N edges is the drawing of exactly N − 3 diagonals that do not touch
      each other anywhere, with the possible exception of their endpoints. A triangulation divides
      the polygon in exactly N − 2 triangles that do not overlap and only touch each other along
      their edges.

      In this problem, you are given the triangulation of a simple polygon, which means, the set of
      triangles in which a polygon was divided. From them, you need to reconstruct the original
      polygon.

      Input

      The input contains several test cases, each one described in several lines. The first line of each
      test case contains an integer N (3 ≤ N ≤ 500), the number of edges of the original polygon.
      Each of the next N − 2 lines describes one triangle in the triangulation of the polygon. Each
      triangle is given by six integers X1 , Y1 , X2 , Y2 , X3 and Y3 separated by single spaces, where Xi
      and Yi are the coordinates in the XY plane of the i-th vertex of the triangle (−1000 ≤ Xi , Yi ≤
      1000). The triangles and their vertices are not given in any specific order. The last line of the
      input contains a single −1 and should not be processed as a test case.

      Output

      For each test case output a single line with 2N integers separated by single spaces. These
      integers must represent the coordinates in the XY plane of the vertices of the original polygon,
      in clockwise order. To make the output unique, the first vertex to be listed is the one with the
      smallest X coordinate, and if there are many of those, the one with the smallest Y coordinate
      among them.

      Example

      Input:
      5
      0 0 10 9 10 0
      10 9 0 9 0 0
      10 9 0 9 5 13
      3
      0 1 1 1 1 0
      10
      -1 -2 2 -2 2 -1
      -1 -2 0 -1 -2 3
      -2 3 2 3 1 2
      0 -1 2 1 1 2
      -1 -2 2 -1 0 -1
      2 1 0 -1 2 0
      2 3 2 2 1 2
      0 -1 -2 3 1 2
      -1
      Output:
      0 0 0 9 5 13 10 9 10 0
      0 1 1 1 1 0
      -2 3 2 3 2 2 1 2 2 1 2 0 0 -1 2 -1 2 -2 -1 -2

      Added by:Pablo Ariel Heiber
      Date:2010-08-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2007









      SPOJ Problem Set (classical)

      7101. Charly And Nito

      Problem code: CANDN

      Charly and Nito are friends and they like to be together at a nice bar in Palermo Hollywood.
      About at 3 a.m. they start to feel sleepy and want to go home. They want to get home quickly
      so each of them uses a path that minimizes the distance to his home. However, Charly and
      Nito also like to walk together while they talk about the “good old times”, so they want to
      walk together as much as possible.
      Charly and Nito live in a city that can be modeled as a set of streets and junctions. Each
      street connects a pair of distinct junctions and can be walked in both directions. No two streets
      connect the same pair of junctions. Charly and Nito do not live together, and they do not live
      at the bar. There is at least one path from the bar to Charly’s home; the same occurs with
      Nito’s home.
      Given information about the streets and junctions in the city, the locations of the bar, Charly’s
      home and Nito’s home, you must tell Charly and Nito the maximum distance that they can
      walk together without forcing them to walk more than the minimum distance from the bar to
      their respective homes. Charly and Nito also want to know how much each of them will walk
      alone.

      Input

      The input contains several test cases, each one described in several lines. The first line of
      each test case contains five integers J, B, C, N and S separated by single spaces. The value
      J is the number of junctions in the city (3 ≤ J ≤ 5000); each junction is identified by an
      integer number between 1 and J. The values B, C and N are the identifiers of the junctions
      where the bar, Charly’s home and Nito’s home are located, respectively (1 ≤ B, C, N ≤ J);
      these three junction identifiers are different. The value S is the number of streets in the city
      (2 ≤ S ≤ 150000). Each of the next S lines contains the description of a street. Each street
      is described using three integers E1 , E2 and L separated by single spaces, where E1 and E2
      identify two distinct junctions that are endpoints of the street (1 ≤ E1 , E2 ≤ J), and L is the
      length of the street (1 ≤ L ≤ 104 ). You may assume that each street has a different pair of
      endpoints, and that there exist paths from junction B to junctions C and N . The last line
      of the input contains the number −1 five times separated by single spaces and should not be
      processed as a test case.

      Output

      For each test case output a single line with three integers T , C and N separated by single
      spaces, where T is the maximum distance that Charly and Nito can walk together, C is the
      distance that Charly walks alone, and N is the distance that Nito walks alone.

      Example

      Input:
      5 3 2 1 6
      3 4 10
      4 5 10
      5 1 3
      5 2 4
      1 3 23
      2 3 24
      8 1 7 8 8
      1 2 1
      2 4 1
      2 3 1
      4 5 1
      3 5 1
      5 6 1
      6 8 1
      6 7 1
      -1 -1 -1 -1 -1

      Output:

      20 4 3
      4 1 1

      Added by:Pablo Ariel Heiber
      Date:2010-08-13
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2007









      SPOJ Problem Set (classical)

      7102. Doing The Word Wrap

      Problem code: DTWW

      You are developing a visual component for a web browser. The component is known as textarea,
      and its main functionality is to show a given text using one or more lines. Every textarea has
      a linewidth W , which is the number of characters that can fit in a single line.
      The text that needs to be shown is a sequence of words. The textarea must display the text
      using lines of W characters, without breaking any word, and placing a single space between
      each pair of consecutive words that are in the same line. Any number of trailing spaces may
      be left at the end of each line. So the behavior of the textarea is quite simple: it keeps adding
      words to a line until the next word does not fit; each time this occurs, a new line is started.
      With the permanent growing in the amount of information that web pages must show, you
      have to make a smart textarea that uses as little space as possible, even when dealing with very
      long texts. Given a text to show and a number of lines L, you must set the linewidth W to the
      minimum possible value such that the text is shown using at most L lines.

      Input

      The input contains several test cases, each one described in exactly two lines. The first line
      of each test case contains two integers L and N separated by a single space, where L is the
      maximum number of lines the textarea can have (1 ≤ L ≤ 108 ), and N is the number of words
      the text to show is made of (1 ≤ N ≤ 105 ). The second line contains the text to show, formed
      by N non-empty words of at most 25 lowercase letters each, separated by an arbitrary number
      of spaces. The last line of the input contains the number −1 twice separated by a single space
      and should not be processed as a test case.

      Output

      For each test case output a single line with an integer W representing the minimum linewidth
      such that the textarea has at most L lines.

      Example

      Input:
      1 2
      hello word
      2 2
      racing club
      -1 -1
      Output: 10
      6

      Added by:Pablo Ariel Heiber
      Date:2010-08-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2007









      SPOJ Problem Set (classical)

      7103. Edit Distance

      Problem code: EDDIST

      The edit distance of two strings S and T is the minimum number of edit operations that need to be done to transform S into T . The valid edit operations are:
      • Insert a single character at any position.
      • Modify an existing character.
      • Remove an existing character.
      For example, the edit distance of “pantera” and “aorta” is 5, because the following chain of
      edits is valid (and there is no shorter chain):
      “pantera” >>> “antera” >>> “aotera” >>> “aoera” >>> “aora” >>> “aorta”.

      In this problem, given a value K and a word S, we need to construct a word T such that the edit distance of S and T is at most K. There are of course several possibilities for that, so we will ask that you choose the word T that comes first alphabetically. A word always comes alphabetically after any proper prefix. Among two words that are not prefixes of each other, the one that comes first alphabetically is the one that has, in the first position at wich they differ from left to right, a letter closest to the beginning of the alphabet. Notice that the empty word (that has zero characters) is a valid word and is alphabetically before any other word.

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      an integer K (0 ≤ K ≤ 1000) and a non-empty word S of at most 1200 lowercase letters,
      separated by a single space. The last line of the input contains the number −1 and an asterisk
      separated by a single space and should not be processed as a test case.

      Output

      For each test case output a single line with a word T of lowercase letters such that the edit
      distance of S and T is at most K. If there are several words in that situation, output the one
      that comes first alphabetically.

      Example

      Input:
      4 abcadef
      1000 zero
      0 zero
      -1 *
      Output: aaaaaadef

      zero

      Added by:Pablo Ariel Heiber
      Date:2010-08-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2007









      SPOJ Problem Set (classical)

      7104. Feanor The Elf

      Problem code: FTHEELF

      Feanor is an elf, and of course, he really likes arrows and bows. Surprisingly enough, Feanor
      has a laptop, but he knows nothing about programming, so he requires your help.
      Feanor lives in a tower of height H, and he loves throwing arrows from the top of it. He had a
      good amount of intesive training and he knows that he always throws his arrows with the same
      initial speed V . He wants you to make a program that given H and V returns the maximum
      distance that a Feanor’s arrow can reach when it hits the ground, measured from the base
      of the tower. With this information, he will be able to place a nice circular fence to prevent
      deoriented little elves from being killed.
      Newtonian laws apply in Feanor’s world and the gravity has the same strength as in ours. These
      laws can be summarized as follows:
      • The position of Feanor is assumed to be a point. The same occurs with the position of
      his arrow at each moment in time.
      • The initial speed V of the arrow can be expressed as Vx2 + Vy2 = V2 , where Vx and Vy
      are the horizontal and vertical components of V , respectively. Speed Vx is always non-
      negative, while speed Vy is positive if the arrow is thrown up, and negative if the arrow
      is thrown down.
      • The initial position of the arrow is the position of Feanor.
      • The horizontal position of the arrow (relative to Feanor’s position) at time t is x(t) = Vx * t.
      • The vertical position of the arrow (relative to Feanor’s position) at time t is y(t) = Vy * t − gt2 / 2, where g = 9.8 m/s2 .

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      two integers V and H separated by a single space. The value V is the initial speed of Feanor’s
      arrow measured in m/s (0 ≤ V ≤ 1000), while the value H is the tower’s height in meters
      (0 ≤ H ≤ 1000). The last line of the input contains the number −1 twice separated by a single
      space and should not be processed as a test case.

      Output

      For each test case output a single line with the radius of Feanor’s fence in meters, rounded up
      to 6 decimal digits (he wants to be sure that he doesn’t kill those cute little elves).

      Example

      Input:
      1 0
      10 0
      100 0
      1000 0
      -1 -1

      Output:

      0.102041
      10.204082
      1020.408163
      102040.816327

      Added by:Pablo Ariel Heiber
      Date:2010-08-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2007









      SPOJ Problem Set (classical)

      7107. G Key

      Problem code: GK


      Leandro and Fede are traveling by train and to spend some time they decided to start playing
      the guitar. They want to play together some songs, but Fede’s memory is not working well
      because he caught a little cold. To work it out, Leandro wants to show to Fede some music
      scores of several punk rock songs. A punk rock song is a sequence of notes, and there are twelve
      possible notes, divided in two groups. The first group has seven natural notes called A, B, C,
      D, E, F and G, while the second group has five alterations called A#, C#, D#, F# and G#.
      The way to draw a music score is as follows: you start with an empty one, and then you draw
      note by note from left to right in the same order they appear in the song. In the following
      picture you can see an empty music score with two lines. The symbol at the beginning of each
      line is called G key. Each line is divided in four groups, each group having room for four notes.

      In this figure, the song “E, F, F#, G, G#, A, A#, B, C, C#, D, D#” is depicted.

      Can you help Leandro writing a program for drawing punk rock songs given the sequence of
      notes?

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      the number of notes N (1 ≤ N ≤ 100), followed by the sequence of N notes. Each note is one
      of A, A#, B, C, C#, D, D#, E, F, F#, G and G#. Values in each line are separated by single
      spaces. The last line of the input contains a single −1 and should not be processed as a test
      case.

      Output

      For each test case output the music score of the input song and print a blank line after each test
      case (even after the last one). You have to follow the sample input and output for drawing the
      music scores. Every score line has the same background formed by the characters “|” (pipe)
      and “-” (hyphen). They differ in the borders (first and last borders are doubled), and of course
      in the notes they have inside. Each eighth note is drawn consecutively as in the sample, and
      the different heights are those shown. Alterations are preceded by a character “#” (sharp sign).
      There must be no trailing spaces at the end of printed lines, neither empty score lines (without
      notes inside).

      Example

      Input:

      36 E F F# G G# A A# B C C# D D# E F F# G G# A A# B C C# D D# E F F# G G# A A# B C C# D D#
      -1

      Output:
      ||                        |                        |                        |                        |
      ||------------------------|------------------------|--------------|\----|\--|------------------------|
      ||                        |                        |  |\    |\    |     |   |                        |
      ||------------------------|--------------------|\--|--|-----|----x|---#x|---|------------------------|
      ||                        |        |\    |\    |   | x|   #x|               |                        |
      ||--------------------|\--|--|\----|-----|----x|---|------------------------|--------------------|\--|
      ||        |\    |\    |   |  |    x|   #x|         |                        |        |\    |\    |   |
      ||--|\----|-----|----x|---|#x|---------------------|------------------------|--|\----|-----|----x|---|
      ||  |    x|   #x|         |                        |                        |  |    x|   #x|         |
      ||-x|---------------------|------------------------|------------------------|-x|---------------------|
      ||                        |                        |                        |                        |
       |                        |                        |                        |                        |
       |------------------------|--------------|\----|\--|------------------------|------------------------|
       |                        |  |\    |\    |     |   |                        |                        |
       |--------------------|\--|--|-----|----x|---#x|---|------------------------|--------------------|\--|
       |        |\    |\    |   | x|   #x|               |                        |        |\    |\    |   |
       |--|\----|-----|----x|---|------------------------|--------------------|\--|--|\----|-----|----x|---|
       |  |    x|   #x|         |                        |        |\    |\    |   |  |    x|   #x|         |
       |#x|---------------------|------------------------|--|\----|-----|----x|---|#x|---------------------|
       |                        |                        |  |    x|   #x|         |                        |
       |------------------------|------------------------|-x|---------------------|------------------------|
       |                        |                        |                        |                        |
       |                        |                        |                        |                        ||
       |--------------|\----|\--|------------------------|------------------------|------------------------||
       |  |\    |\    |     |   |                        |                        |                        ||
       |--|-----|----x|---#x|---|------------------------|------------------------|------------------------||
       | x|   #x|               |                        |                        |                        ||
       |------------------------|------------------------|------------------------|------------------------||
       |                        |                        |                        |                        ||
       |------------------------|------------------------|------------------------|------------------------||
       |                        |                        |                        |                        ||
       |------------------------|------------------------|------------------------|------------------------||
       |                        |                        |                        |                        ||

      Added by:Pablo Ariel Heiber
      Date:2010-08-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:FCEyN UBA ICPC Selection 2007









      SPOJ Problem Set (classical)

      7108. Heptadecimal Numbers

      Problem code: HEPNUM


      The Factory of Computer Enhaced Numbers (FCEN) has asked its Development Comitee (DC)
      to come up with a way to handle numbers written in base 17.
      As everybody knows, base 17 is very important for many scientific applications, as well as for
      engineering and other practical uses. Numbers in base 17 can be tough, but are kind and soft
      if treated appropiately.
      Numbers in base 17 are written by using a set of 17 characters: digits 0 to 9 with their usual
      values, and uppercase letters A to G that have values from 10 to 16, respectively.
      Base 17, probably because its basement on a prime number, does not require numbers to start
      with a non-zero digit, so each number has many representations. For instance, the decimal
      number 117 can be written as 6F , but also as 06F or even 00000006F .
      Because of this leading-zeroes thing, heptadecimal numbers are hard to compare. As a member
      of the FCEN-DC, you were asked to write a program that helps in this difficult and challenging
      task.

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      two non-empty strings of at most 105 heptadecimal digits, separated by a single space. The last
      line of the input contains two asterisks separated by a single space and should not be processed
      as a test case.

      Output

      For each test case output a single line with the sign “<” if the first heptadecimal number is
      smaller than the second one, the sign “>” if the first heptadecimal number is greater than the
      second one, or the sign “=” if both heptadecimal numbers are equal.

      Example

      Input:

      006F B3B
      0000 0
      * *

      Output:
      <
      =

      Added by:Pablo Ariel Heiber
      Date:2010-08-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2007









      SPOJ Problem Set (classical)

      7109. Indicator of progression

      Problem code: INDIPROG

      When dealing with a long task, computers often provide a progress indicator to help users
      estimate how much longer they will have to wait. This is especially useful when copying a large
      number of data files from one drive to another.
      In the Institute of Computer Power Control (ICPC) are very concerned about their brand new
      file copier, which they think will change forever the way people copy files. While this is a great
      accomplishment for the engineers in ICPC, the lack of a progress indicator is threatening the
      future of the project and the well being of most computer users around the world!
      The Supremum Principal Director Manager of ICPC has called you personally to ensure you
      are up for the task. The interface provided by the developing team of the file copier only gives
      two integers M and N . M is the number of files that have already been copied, and N is
      the total number of files to be copied. Using this information, you must write a module that
      displays the progress indicator.
      The indicator must be drawn as a string of exactly 20 characters. The first K of them must
      be asterisks (“*”) and the rest must be hyphens (“-”). The number K must be chosen in such
      a way that K/20 correctly approximates M/N ; this means that the distance between the two
      mentioned fractions is minimum. If there is more than one possible value for K, the greatest
      one must be chosen.
      Also, for more precision, a number P without leading zeroes and followed by a percentage
      sign (“%”) must be written on top of the described indicator. Since the goal is to represent
      the finished percentage, the number P must be such that P/100 correctly approximates M/N ,
      with the same policy as before. The finished percentage must be centered on top of the display.
      This means that if possible, the same number of display characters (“*” or “-”) must be seen
      to the left and to the right of the percentage; if this is not possible, exactly one extra character
      must be seen to the left.

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      two integers M and N as explained above (0 ≤ M ≤ N ≤ 109 and N ≠ 0). These values are
      separated by a single space. The last line of the input contains the number −1 twice separated
      by a single space and should not be processed as a test case.

      Output

      For each test case output a single line with exactly 20 characters representing the mentioned
      display.

      Example

      Input:

      2 5
      2 6
      0 10
      -1 -1

      Output:


      ********-40%--------
      *******--33%--------
      ---------0%---------




      Added by:Pablo Ariel Heiber
      Date:2010-08-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2007









      SPOJ Problem Set (classical)

      7132. Headshot

      Problem code: HEADSHOT

      You have a revolver gun with a cylinder that has n chambers. Chambers are located in a circle on a cylinder. Each chamber can be empty or can contain a round. One chamber is aligned with the gun's barrel. When trigger of the gun is pulled, the gun's cylinder rotates, aligning the next chamber with the barrel, hammer strikes the round, making a shot by firing a bullet through the barrel. If the chamber is empty when the hammer strikes it, then there is no shot but just a "click".

       

      You have found a use for this gun. You are playing Russian Roulette with your friend. Your friend loads rounds into some chambers, randomly rotates the cylinder, aligning a random chamber with a gun's barrel, puts the gun to his head and pulls the trigger. You hear "click" and nothing else - the chamber was empty and the gun did not shoot.

      Now it is your turn to put the gun to your head and pull the trigger. You have a choice. You can either pull the trigger right away or you can randomly rotate the gun's cylinder and then pull the trigger. What should you choose to maximize the chances of your survival?

       


      International Cyber Police Corporation (ICPC) had built a new mega-tall business center to host its
      headquarters and to lease some space for extra pro¯t. It has so many °oors, that it is impractical to have
      a separate button in each of its m elevator cars for each individual °oor. Instead, each elevator car has
      just two buttons. One button in i-th elevator car makes it move up ui °oors, the other makes it move
      down di °oors. The business center is so high, that we can ignore its height for this problem (you will
      never reach the top °oor), but you cannot go below the ground °oor. All °oors are numbered by integer
      numbers starting from zero, zero being the ground °oor.
      You start on the ground °oor of the business center. You have to choose one elevator car out of m to
      ride on. You cannot switch elevators cars after that. What is the lowest °oor above the ground °oor you
      can get to after you press elevator car buttons exactly n times

      Input

      The input first line contains a single line with a string of n digits "0" and "1" (2<=n<=100). This line of digits represents the pattern of rounds that were loaded into the gun's chambers. "0" represent an empty chamber, "1" represent a loaded one. In this representation, when cylinder rotates before a shot, the next chamber to the right gets aligned with the barrel for a shot. Since the chambers are actually located on a circle, the first chamber in this string follows the last one. There is at least one "0" in this string.

       Output

       

      Write to the output single one of the following words (without quotes):

      "SHOOT" - if pulling the trigger right away makes you less likely to be actually shot in the head with the bullet (more likely that the chamber will be empty).

      "ROTATE" - if randomly rotating the cylinder before pulling the trigger makes you less likely to be actually shot in the head with the bullet (more likely that the chamber will be empty).

      "EQUAL" - if both of the above choices are equal in terms of probability of being shot.

       

      Example

      Input:
       0011
      Output:
       EQUAL

      Input:
       0111
      
      Output:
       ROTATE

      Input:
       000111
      Output:
       SHOOT

      Added by:Gareev
      Date:2010-08-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:NEERC 2009









      SPOJ Problem Set (classical)

      7133. Garden 2005

      Problem code: IOIGARD

       

      Byteman owns the most beautiful garden in Bytetown. He planted n roses in his garden. Summer has come
      and the flowers have grown big and beautiful. Byteman has realized that he is not able to take care of all the
      roses on his own. He has decided to employ two gardeners to help him. He wants to select two rectangular
      areas, so that each of the gardeners will take care of the roses inside one area. The areas should be disjoint
      and each should contain exactly k roses.
      Byteman wants to make a fence surrounding the rectangular areas, but he is short of money, so he wants
      to use as little fence as possible. Your task is to help Byteman select the two rectangular areas.
      The garden forms a rectangle l meters long and w meters wide. It is divided into l · w squares of size
      1 meter × 1 meter each. We fix a coordinate system with axes parallel to the sides of the garden. All squares
      have integer coordinates (x,y) satisfying 1  x  l, 1  y w. Each square may contain any number of roses.
      The rectangular areas, which must be selected, should have their sides parallel to the sides of the garden
      and the squares in their corners should have integer coordinates. For 1  l1  l2  l and 1  w1  w2  w, a
      rectangular area with corners (l1,w1), (l1,w2), (l2,w1) and (l2,w2):
      • contains all the squares with coordinates (x,y) satisfying l1  x  l2 and w1  y  w2, and
      • has perimeter 2 · (l2−l1+1)+2 · (w2−w1+1).
      The two rectangular areas must be disjoint, that is they cannot contain a common square. Even if they have a
      common side, or part of it, they must be surrounded by separate fences.

       

      Byteman owns the most beautiful garden in Bytetown. He planted n roses in his garden. Summer has come and the flowers have grown big and beautiful. Byteman has realized that he is not able to take care of all the roses on his own. He has decided to employ two gardeners to help him. He wants to select two rectangular areas, so that each of the gardeners will take care of the roses inside one area. The areas should be disjoint and each should contain exactly k roses. Byteman wants to make a fence surrounding the rectangular areas, but he is short of money, so he wants to use as little fence as possible. Your task is to help Byteman select the two rectangular areas.

      The garden forms a rectangle l meters long and w meters wide. It is divided into l · w squares of size 1 meter × 1 meter each. We fix a coordinate system with axes parallel to the sides of the garden. All squares have integer coordinates (x,y) satisfying 1<=x<=l, 1<=y<=w. Each square may contain any number of roses. The rectangular areas, which must be selected, should have their sides parallel to the sides of the garden and the squares in their corners should have integer coordinates. For 1<=l1<=l2<=l and 1<=w1<=w2<=w, a rectangular area with corners (l1,w1), (l1,w2), (l2,w1) and (l2,w2):

      • contains all the squares with coordinates (x,y) satisfying l1<=x<=l2 and w1<=y<=w2, and

      • has perimeter 2 · (l2−l1+1)+2 · (w2−w1+1).

      The two rectangular areas must be disjoint, that is they cannot contain a common square. Even if they have a common side, or part of it, they must be surrounded by separate fences.

      Task

       

       

      Write a program, that:

      • reads from the standard input the dimensions of the garden, the number of roses in the garden, the number of roses that should be in each of the rectangular areas, and the positions of the roses.

      • finds the corners of two such rectangular areas with minimum sum of perimeters that satisfy the given conditions.

      • writes to the standard output the minimumsum of perimeters of two non-overlapping rectangular areas, each containing exactly the given number of roses (or a single word NO, if no such pair of areas exists).

       

      Input

       

      The first line of standard input contains two integers: l and w (1<=l,w<=250) separated by a single space — the length and the width of the garden. The second line contains two integers: n and k (2<=n<=5000, 1<=k<=n/2) separated by a single space — the number of roses in the garden and the number of roses that should be in each of the rectangular areas. The following n lines contain the coordinates of the roses, one rose per line. The (i+2)-nd line contains two integers li, wi (1<=li<=l, 1<=wi<=w) separated by a single space — the coordinates of the square containing the i-th rose. Two or more roses can occur in the same square.

       

      Output

       

      The standard output should contain only one line with exactly one integer—the minimum sum of perimeters of two non-overlapping rectangular areas, each containing exactly k roses, or a single word NO, if no such pair of areas exists.

       

      Example

      Input:
      6 5
      7 3
      3 4
      3 3
      6 1
      1 1
      5 5
      5 5
      3 1
      
      Output:
      22

      Added by:Gareev
      Date:2010-08-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:IOI 2005, Day 1









      SPOJ Problem Set (classical)

      7150. Palindrome 2000

      Problem code: IOIPALIN

      A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome. As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.

      Input

      The first line contains one integer: the length of the input string N, 3≤N≤5000. The second line contains one string with length N. The string is formed from uppercase letters from ‘A’ to ‘Z’, lowercase letters from ‘a’ to ‘z’ and digits from ‘0’ to ‘9’. Uppercase and lowercase letters are to be considered distinct.

      Output

      The first line contains one integer, which is the desired minimal number.

      Example

      Input:
      5
      Ab3bd
      
      Output:
      2

      Added by:Gareev
      Date:2010-08-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:IOI 2000, Day 1









      SPOJ Problem Set (classical)

      7152. Boundary 2003

      Problem code: IOIBOUND

      Farmer Don watches the fence that surrounds his N meter by N meter square, flat field (2<=N<=500,000). One fence corner is at the origin (0, 0) and the opposite corner is at (N,N); the sides of Farmer Don's fence are parallel to the X and Y axes.Fence posts appear at all four corners and also at every meter along each side of the fence, for a total of 4×N fence posts. The fence posts are vertical and are considered to have no radius. Farmer Don wants to determine how many of his fence posts he can watch when he stands at a given location within his fence. Farmer Don’s field contains R (1<=R<=30,000) huge rocks that obscure his view of some fence posts, as he is not tall enough to look over any of these rocks. The base of each rock is a convex polygon with nonzero area whose vertices are at integer coordinates. The rocks stand completely vertical. Rocks do not overlap, do not touch other rocks, and do not touch Farmer Don or the fence. Farmer Don does not touch the fence, does not stand within a rock, and does not stand on a rock. Given the size of Farmer Don's fence, the locations and shapes of the rocks within it, and the location where Farmer Don stands, compute the number of fence posts that Farmer Don can see. If a vertex of a rock lines up perfectly with a fence post from Farmer Don's location, he is not able to see that fence post.

      Input

      The first line of input contains two space-separated integers: N and R.
      · The next line of input contains two space-separated integers that specify the X
      and Y coordinates of Farmer Don's location inside the fence.
      · The rest of the input file describes the R rocks:
      o Rock i’s description starts with a line containing a single integer pi (3 £ pi
      £ 20), the number of vertices in the rock's base.
      o Each of the next pi lines contains a space-separated pair of integers that are
      the X and Y coordinates of a vertex. The vertices of a rock’s base are
      distinct and given in counterclockwise order.

      The first line of input contains two space-separated integers: N and R. The next line of input contains two space-separated integers that specify the X and Y coordinates of Farmer Don's location inside the fence. The rest of the input file describes the R rocks: Rock i’s description starts with a line containing a single integer pi (3<=pi<=20), the number of vertices in the rock's base. Each of the next pi lines contains a space-separated pair of integers that are the X and Y coordinates of a vertex. The vertices of a rock’s base are distinct and given in counterclockwise order.

      Output

      The output file should contain a single line with a single integer, the number of fence posts visible to Farmer Don.

      Example

      Input:
      100 1
      60 50
      5
      70 40
      75 40
      80 40
      80 50
      70 60
      
      Output:
      319

      Added by:Gareev
      Date:2010-08-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:IOI 2003, Day 2









      SPOJ Problem Set (classical)

      7155. Test

      Problem code: CF25E

      Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s1, the second enters an infinite loop if the input data contains the substring s2, and the third requires too much memory if the input data contains the substring s3. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions?

      Input

      There are several test cases. For each test case there are exactly 3 lines. The i-th line contains string si. All the strings are non-empty, consists of lowercase Latin letters, the length of each string doesn't exceed 105.

      Output

      For each test case output one number — what is minimal length of the string, containing s1, s2 and s3 as substrings.

      Example

      Input:
      ab
      bc
      cd
      abacaba
      abaaba
      x

      Output:
      4
      11

      Added by:David Gómez
      Date:2010-08-17
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:Codeforces - Unofficial Test Cases









      SPOJ Problem Set (classical)

      7169. Pizza

      Problem code: EGYPIZZA


      Abotrika is having a party because his team won the african cup so he is inviting his friends to eat some pizza.

      Unfortunately,Abotrika's friends can't eat an entire pizza but all of them know exactly how much pizza 

      they can eat and insist on getting the exact amount of pizza but Abotrika eats one complete pizza and all of them wants his amount of pizza in one slice.

      Their requests break down to three different pizza slices-either one quarter or a half or three quarters of pizza.

      write a program that will help Abotrika to find out what is the minimal number of pizzas he has to order so that 

      everyone gets exact amount of pizza they want.

      Input

      First line contains an integer N, 0<=N<=10,000 , number of friends.

      In each of next N lines there is amount of pizza that each of Abotrika's friends wants to eat,that 

      is the fraction 1/4 , 1/2 or 3/4.

      Output

      In the first and only line you should write the minimal number of pizzas Abotrika has order don't forget to order 

      one complete pizza for Abotrika

      Example

      Input:
      3
      1/2
      3/4
      3/4
      Output:
      4
      Input:
      5
      1/2
      3/4
      1/2
      1/4
      1/4
      Output:
      4
      Note : the problem rejudged

      Added by:Kawmia Institutes
      Date:2010-08-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: BF LISP sbcl LISP clisp JS LUA PHP
      Resource:Croatian Highschool Competitions in Informatics 2004









      SPOJ Problem Set (classical)

      7184. Axis of Symmetry

      Problem code: AXIS

      Given a point p and a line L on the plane, the reflection of p against L is a point q such that
      the segment pq is perpendicular to L and its middle point is on L. If p is on L, then p = q.

      Given a set of points on the plane, an axis of symmetry is a line on the plane such that the
      reflection of any point of the set against that line gives a point of the set.
      In this problem you are given a set of points on the plane, and you must decide whether there
      exists at least one axis of symmetry or not.

      Input

      The input contains several test cases, each one described in several lines. The first line of each
      test case contains an integer N indicating the number of points in the set (3 ≤ N ≤ 1000).
      Each of the next N lines describes a different point of the set using two integers X and Y
      separated by a single space (−2000 ≤ X, Y ≤ 2000); these numbers represent the coordinates
      of the point in the XY plane. You may assume that no two points of each test case have the
      same location. The last line of the input contains a single −1 and should not be processed as
      a test case.

      Output

      For each test case output a single line with an uppercase “Y” if there exists at least one axis of
      symmetry for the provided set of points, or an uppercase “N” otherwise.

      Example

      Input:
      4
      -10 0
      10 0
      10 10
      10 -10
      4
      -10 0
      10 1
      10 10
      10 -10
      6
      -1000 30
      -100 20
      -10 10
      1000 30
      100 20
      10 10
      -1

      Output:
      Y
      N
      Y

      Added by:Pablo Ariel Heiber
      Date:2010-08-19
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2008









      SPOJ Problem Set (classical)

      7185. Bye Bye Cakes

      Problem code: BYECAKES

      John is moving to a different city and he wants to use all his perishable food before doing it,
      to avoid wasting. Luckily all he has now is eggs, flour, sugar and milk, so he is going to make
      his famous cakes and give them to his friends as a goodbye gift.
      John only knows how to make an entire cake and not half a cake, a third of a cake, or any
      other portion. So, he will buy whatever is needed of each ingredient so that he can make an
      integer number of cakes and have nothing left. Of course, he wants to spend as little money as
      possible. You must help John to decide how much he should buy of each ingredient.

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      eight integers E, F , S, M , E' , F' , S' and M' separated by single spaces. Values E and E' are
      numbers of eggs, F and F' are grams of flour, S and S' are grams of sugar, and M and M' are
      centiliters of milk. For each ingredient, X is the amount John has (0 ≤ X ≤ 1000), while X' is
      the amount needed to make a single cake (1 ≤ X ≤ 1000). The last line of the input contains
      the number −1 eight times separated by single spaces and should not be processed as a test
      case.

      Output

      For each test case output a single line with four non-negative integers separated by single spaces,
      representing the amount of each ingredient John needs to buy, in the same order and units as
      the input.

      Example

      Input:
      2 3 4 5 1 1 1 1
      3 6 9 0 1 2 3 4
      -1 -1 -1 -1 -1 -1 -1 -1
      Output: 3 2 1 0
      0 0 0 12

      Added by:Pablo Ariel Heiber
      Date:2010-08-19
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2008









      SPOJ Problem Set (classical)

      7186. Counting Pascal

      Problem code: COUNTPAS

      Pascal’s triangle is a common figure in combinatorics. It is a triangle formed by rows of integers.
      The top row contains a single 1. Each new row has one element more than the previous one
      and is formed as follows: the leftmost and rightmost values are 1, while each of the other values
      is the sum of the two values above it. Here we depict the first 7 rows of the triangle.

                  1            
                1   1          
              1   2   1        
            1   3   3   1      
          1   4   6   4   1    
        1   5   10   10   5   1  
      1   6   15   20   15   6   1

      Pascal’s triangle is infinite, of course, and contains the value 1 an unbounded number of times.
      However, any other value appears a finite number of times in the triangle. In this problem you
      are given an integer K ≥ 2. Your task is to calculate the number of values in the triangle that
      are different from 1 and less than or equal to K.

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      an integer K (2 ≤ K ≤ 109 ). The last line of the input contains a single −1 and should not be
      processed as a test case.

      Output

      For each test case output a single line with an integer indicating the number of values in Pascal’s
      triangle that are different from 1 and less than or equal to K.

      Example

      Input:
      2
      6
      -1

      Output:
      1
      10

      Added by:Pablo Ariel Heiber
      Date:2010-08-19
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2008









      SPOJ Problem Set (classical)

      7187. Dinosaur Menace

      Problem code: DINOSM

      After a failed but interesting DNA project, a lot of dinosaurs spread over the lab devouring
      most of the staff. Jeff, a scientist that worked in the project, managed to survive by hiding in
      the southwest corner of the lab. Now that all dinosaurs are asleep, he is going to try to leave.
      The exit of the lab is located at the northeast corner.
      Jeff knows that if any of the dinosaurs wakes up, he does not stand a chance, so he needs to
      minimize the likelihood of that happening. For that, he wants to follow a path that maximizes
      the minimum distance from him to a dinosaur along the path. The length of the path is of no
      interest to Jeff.
      For this problem we consider that Jeff and the dinosaurs are points on the plane, and that Jeff’s
      path is a continuous curve conecting the southwest and northeast corners of the lab. As we
      mentioned, Jeff wants to maximize the minimum distance between this curve and the position
      of any dinosaur.

      Input

      The input contains several test cases, each one described in several lines. The first line of each
      test case contains three integers N , W , and H separated by single spaces. The value N is the
      number of dinosaurs in the lab (1 ≤ N ≤ 300). The values W (width) and H (height) are the
      size of the lab on the x and y coordinates, respectively (2 ≤ W, H ≤ 106 ). This means that
      the starting position of Jeff is at (0, 0), while the exit of the lab is located at (W, H). Each
      of the next N lines contains two integers X and Y separated by a single space, representing
      the coordinates of a different dinosaur (1 ≤ X ≤ W − 1 and 1 ≤ Y ≤ H − 1). Note that no
      dinosaur is located on the border of the lab. You may assume that no two dinosaurs have the
      same location. The last line of the input contains the number −1 three times separated by
      single spaces and should not be processed as a test case.

      Output

      For each test case output a single line with the maximum possible distance to the closest
      dinosaur. Write the result rounded to the closest number with exactly three decimal places,
      using the highest in case of ties, as usual.

      Example

      Input:
      1 2 2
      1 1
      3 5 4
      1 3
      4 1
      1 2
      2 5 4
      1 3
      4 1
      -1 -1 -1

      Output: 1.000
      1.581
      1.803

      Added by:Pablo Ariel Heiber
      Date:2010-08-19
      Time limit:9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2008









      SPOJ Problem Set (classical)

      7188. Escape from Jail

      Problem code: ESJAIL


      Harry is currently a prisoner of the International Common Prison for Criminals (ICPC), the
      most secure prison in the world. It was designed by and old gamer and as such, the prison is
      not necesarilly closed, but only an incredibly logical and fast mind can get out.
      The prison is made of N chambers connected by M corridors. Each corridor connects exactly
      two chambers and can be traversed in any direction. Each chamber is either empty, contains
      a single unbreakable door, or contains a single key. No chamber contains both a door and a
      key. There are K doors and K keys in the whole prison. Each key opens a different door, and
      each door is opened by a different key. If a chamber contains a door, the corresponding key is
      needed to enter the chamber, regardless of which corridor was used to reach it.
      Harry found the complete map of the prison, including the location of each door and each key,
      and wants to know how to get out that hell hole. According to the map, Harry is now in
      chamber number 1, and the exit is in chamber N . Given the information on the map, let Harry
      know if it is possible to escape or if he is doomed forever.

      Input

      The input contains several test cases, each one described in several lines. The first line of each
      test case contains three integers N , K, and M separated by single spaces. The value N is the
      number of chambers in the prison (4 ≤ N ≤ 105 ); each chamber is identified by an integer
      number between 1 and N . The value K is the number of doors and keys (1 ≤ K ≤ N/2), while
      M is the number of corridors (1 ≤ M ≤ 105 ). Each of the next K lines describes a door and its
      corresponding key using two integers A and B separated by a single space, with the following
      meaning: chamber A cointains the key that opens the door in chamber B (2 ≤ A, B ≤ N − 1).
      The last M lines of the test case describe the corridors. Each of these lines cointains two integers
      C and D separated by a single space, indicating that there is a corridor connecting chambers
      C and D (1 ≤ C < D ≤ N ). You may assume that no two corridors connect the same pair of
      chambers. The last line of the input contains the number −1 three times separated by single
      spaces and should not be processed as a test case.

      Output

      For each test case output a single line with an uppercase “Y” if it is possible for Harry to escape
      from the prison, or an uppercase “N” otherwise.

      Example

      Input:
      4 1 4
      2 3
      3 4
      2 3
      1 3
      2 4
      6 2 5
      5 4
      3 2
      2 6
      2 5
      1 4
      1 5
      3 4
      4 1 1
      3 2
      2 3
      -1 -1 -1

      Output: N
      Y
      N

      Added by:Pablo Ariel Heiber
      Date:2010-08-19
      Time limit:9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2008









      SPOJ Problem Set (classical)

      7189. Falta Envido

      Problem code: FALTAENV

      Envido is an important part of the typical argentinian game Truco. It is even more important
      when Falta Envido is called, because in this case the winner of the Envido wins the entire game.
      In this problem you are asked to calculate the envido advantage of a cheater.
      Truco is played with a limited deck of spanish cards. This deck contains four suits: espada,
      basto, copa and oro. There are 10 cards of each suit: 1, 2, 3, 4, 5, 6, 7, 10, 11 and 12. Cards
      10, 11 and 12 have an envido value of 0, while the envido value for any of the other cards is
      simply its number. Each player holds three cards. The winner of an Envido is the player with
      the higher envido score. When calculating his envido score each player can either:
      1. select a single card and have as envido score the envido value of the card; or
      2. select two cards of the same suit and have as envido score 20 plus the sum of the envido
      value of each selected card.
      Players always select the card or cards that yield the highest envido score. For instance, a
      player having a 10 and a 2 of the same suit, together with a 5 of a different suit, would inform
      an envido score of 22 because 20 + 0 + 2 = 22.
      A cheater playing Truco thinks that he can change one of his three cards without anybody else
      in the table noticing. If he changes more than one card, he surely will be discovered, so he does
      not do that. Since even changing one card is risky, he only does it when the envido score of the
      resulting hand is much higher than the one of his original hand.
      Given the cards the cheater has in hand, you must calculate the maximum increase he can get
      in the envido score by exchanging one of his cards with a card from the deck. Notice that the
      resulting hand must be formed by two of his original cards and one new card selected from the
      deck, and that he cannot have two equal cards (same number and suit).

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      six values N1 , S1 , N2 , S2 , N3 , and S3 separated by single spaces. Each pair (Ni , Si ) describes
      a card in the hand of the cheater (1 ≤ i ≤ 3), where Ni is the number of the card (1, 2, 3, 4,
      5, 6, 7, 10, 11 or 12), and Si is its suit (espada, basto, copa or oro). You may assume that the
      three cards are different. The last line of the input contains three times the number −1 and an
      asterisk, with the six values separated by single spaces, and should not be processed as a test
      case.

      Output

      For each test case output a single line with an integer representing the maximum increase in
      the envido score that can be obtained by replacing exactly one card of the input hand.

      Example

      Input:
      12 espada 10 basto 11 basto
      7 espada 1 oro 2 oro
      7 espada 1 oro 6 espada
      -1 * -1 * -1 *

      Output: 7
      10
      0

      Added by:Pablo Ariel Heiber
      Date:2010-08-19
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2008









      SPOJ Problem Set (classical)

      7190. Guess the Number

      Problem code: GUESSTHE

      You are playing the funny game “Guess the number” with a friend. In this game, one of the
      players choose a positive integer and the other has to guess it by using the clues that are
      revealed. The i-th clue is either “Y” or “N” indicating whether the hidden number is a multiple
      of i or not, respectively. For instance, if the clues so far are “YYNYY” it means that the number
      is a multiple of 1, 2, 4 and 5, but it is not a multiple of 3. Given the clues of the game so
      far, you have to guess the minimum possible number according to them, or call your friend a
      cheater if there is no number such that the clues were correctly given.

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      a non-empty string of at most 20 characters. The string is formed entirely of uppercase letters
      “Y” and “N”, and represents the clues given so far, in order from left to right. The last line of
      the input contains a single asterisk and should not be processed as a test case.

      Output

      For each test case output a single line with the minimum positive integer that satisfies all the
      clues, or −1 if there is no such a number.

      Example

      Input:
      YYNYY
      YYYNNN
      *

      Output: 20
      -1

      Added by:Pablo Ariel Heiber
      Date:2010-08-19
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2008









      SPOJ Problem Set (classical)

      7191. Hexagonal Board

      Problem code: HEXBOARD

      Square boards (as the chessboard) are really common among games and luckily, they are easy
      to draw with the help of a ruler. However, there exist other games that requiere hexagonal
      boards, that are much harder to draw by hand.
      The Institute for Client Permanent Comfort (ICPC) of a famous board game factory has decided
      to provide their customers with an automated program to build hexagonal boards for several
      games. The size of an hexagonal board is determined by a single integer N that indicates how
      many cells there are in each of the 6 sides of the board. For example, a board of size N = 2
      should look as follows when drawn by the program.
            _
       _/ \_
      / \_/ \
      \_/ \_/
      / \_/ \
      \_/ \_/
        \_/

      Your task is to help ICPC in making the program.

      Input

      The input contains several test cases. Each test case is described in a single line that contains
      an integer N representing the size of the board (1 ≤ N ≤ 20). The last line of the input
      contains a single −1 and should not be processed as a test case.

      Output

      For each test case output the hexagonal board of the required size, and a line with exactly
      three asterisks. You have to follow the sample input and output, as well as the example given
      above. Use only regular spaces, underscores (“ ”), slashes (“/”) and backslashes (“\”). There
      must be no trailing spaces at the end of printed lines, neither empty lines.

      Example

      Input:
      1
      3
      -1

      Output: _
      / \
      \_/
      ***
      _
      _/ \_
      _/ \_/ \_
      / \_/ \_/ \
      \_/ \_/ \_/
      / \_/ \_/ \
      \_/ \_/ \_/
      / \_/ \_/ \
      \_/ \_/ \_/
      \_/ \_/
      \_/
      ***

      Added by:Pablo Ariel Heiber
      Date:2010-08-19
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2008









      SPOJ Problem Set (classical)

      7192. Integral Maximization

      Problem code: INTEGMAX

      A set of points on the XY plane, all of them with different x coordinate, defines a polygonal
      line in the following way: sort the points in increasing order of their x coordinates, and connect
      each point with its neighbors. The integral of such polygonal line is the area contained below
      the line and above the x axis, between the first and last values of x. For instance, the set of
      points {(5, 1), (3, 2), (6, 2), (2, 1)} defines the polygonal line shown in the figure; the integral of
      the polygonal line is the shaded area, with a value of 6.

      Given a set of N different values for x, and a set of N values for y, we want to pair them to
      form N points on the plane such that the integral of the polygonal line defined by the points is
      as large as possible.

      Input

      The input contains several test cases, each one described in exactly three lines. The first line of
      each test case contains an integer N indicating the number of points in the set (2 ≤ N ≤ 104 ).
      The second line contains N different integers Xi separated by single spaces (1 ≤ Xi ≤ 104
      for 1 ≤ i ≤ N ); these integers represent the values of x and are given in increasing order
      (Xi < Xi+1 for 1 ≤ i ≤ N − 1). The third line contains N integers Yi separated by single spaces
      (1 ≤ Yi ≤ 104 for 1 ≤ i ≤ N ); these integers represent the values of y and are not given in any
      particular order. The last line of the input contains a single −1 and should not be processed
      as a test case.

      Output

      For each test case output a single line with the maximum integral of a polygonal line formed
      by pairing the input values, using exactly one decimal digit. Notice that one decimal digit is
      always enough to represent the exact value of the integral of a polygonal line defined by points
      with integer coordinates.

      Example

      Input:
      2
      1 2
      1 2
      4
      2 3 5 6
      1 2 1 2
      -1

      Output: 1.5
      7.0

      Added by:Pablo Ariel Heiber
      Date:2010-08-19
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2008









      SPOJ Problem Set (classical)

      7193. The Pharaoh Curse

      Problem code: CURSE

      Most of the contestants managed to arrive at the Benelux Algorithm Programming Contest on time. All except those unfortunate souls who chose to use a cheap car navigation system. A couple of wrong turns led them completely of course, and now they have ended up all over the world. Consider the case of contestant J.-P. B. (who has asked to remain anonymous). After driving for countless hours he found himself beneath three miles of water in the middle of the Atlantic Ocean. He was so focused on his navigation system that he failed to look outside until he noticed that the air was getting very moist. Fortunately for this contestant there was a spare submarine under his seat, which allowed him to escape this perilous situation. Tragic as this story seems, it is not even the worst. Another contestant, whom we will simply call S, wisely decided to travel by train. Sadly, she still listened to the advice of her evil car navigation system, and this morning she took a southbound train instead of heading north. After some more bad directions she found herself locked inside a labyrinth, in the pyramid of the Egyptian pharaoh Sok-O-Ban. As any experienced adventurer knows, these ancient tombs are often riddled with traps and other mechanisms. Sok-O-Ban's nal resting place was no exception. During his lifetime this pharaoh was known for his sadistic behavior, and he liked to give impossible challenges to random strangers. It is therefore no coincidence that the cavern where contestant S ended up was completely closed o , surrounded by solid rock on every side. After looking around, our protagonist S managed to draw a map of the tomb. Fortunately she found no skeletons, mummies or spiked death traps. She did discover some buttons embedded in the oor tiles. If she could press them all at the same time, then the hidden exit would open. But as soon as she would release one of the buttons, the door would close again. Besides the buttons, the walls and a few dusty oor tiles, there were also two sarcophagi lled with rocks. To accommodate the small stature of the ancient Egyptians, the sarcophagi were cubes with sides measuring 1 meter, the same size as the  oor tiles. It seemed that these sarcophagi were the key to escaping: by pushing them onto the buttons the exit could be kept open. Only one small problem remained: the sarcophagi were far too heavy to move by hand and too large to climb over. Fortunately for S, the pharaoh did not anticipate the portable sarcophagus transporter she had conveniently stashed in her backpack. Attaching this reusable system to her arms allowed her to e ortlessly push a sarcophagus exactly one meter straight ahead. This corresponds nicely to the 1 meter steps S used when marking out the grid in her map.

      Input

      On the first line of the input is a positive integer, the number of test cases. Then for each test case: A line containing two positive integers h;w  50, the height and width of the maze. h lines of w characters each, the map of the cavern our protagonist made, in which: '#' is a wall or otherwise impassible space. '.' is an empty space, of which there are at most 100. 'S' is our protagonist. 'X' is one of the heavy sarcophagi. There are at most two of these.'B' is a button. 'E' is the exit. There is exactly one exit, on the edge of the map. The edge of the map contains only walls and the exit.

      Output

      For each test case: One line containing the minimum number of steps2 it will take S to escape the tomb, or the text "impossible" if she cannot escape.

      Example

      Input:
      3
      7 8
      ########
      #..S...#
      #.####.#
      #.#.XB.#
      #.####.#
      #......E
      ########
      7 8
      ########
      #..S...#
      #.####.#
      #.#.BX.#
      #.####.#
      #......E
      ########
      4 8
      ##E#####
      #...####
      #SX.XBB#
      ########
      
      Output:
      impossible
      10
      19

      Added by:Gareev
      Date:2010-08-20
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6









      SPOJ Problem Set (classical)

      7200. Strange Calendar

      Problem code: CAL

      In a galaxy, far far away, there was a planet, Gringo quite similar to our own. Maybe it is because the planet has a similar "Sun" and "Moon". In Gringo, people use a calendar which is identical to ours. It is said this calendar was made by one of many kings in Gringo's history thousands of years ago. In the legend, it says the king liked programming very much, and at one night he solved a very difficult problem. He was so happy that he wanted to make a new calendar to congratulate. Hence in his calendar, this very midnight with full moon is first second.

       

      In this calendar, names of periods of time are same to ours, like days, months, years, minutes and seconds. In Gringo planet, the planet will reach same position on its revolution around the "Sun" every T1 seconds, the time between two neighbor full moons is T2 seconds and the time between two neighbor midnights is T3 seconds. It's very clear that a year is T1 seconds and a day is T3 seconds. And luckily, T1 is divisible by T3. So a leap year is unnecessary.

       

      But T2 may be not divisible by T3, which is very troublesome. But our king was very clever, he made following rules.

       

      1. A new day comes when a midnight come.

      2. A new year comes when the planet reaches the same position with the "first midnight" on its revolution around the "Sun". Of course it will be a midnight and a new day will come, too.

      3. When a new day comes, if the "Moon" will be full in this day, a new month will come, too.

      4. When a new year comes, a new month will come, too. The "Moon" may not be full. So the month was called "0th month" of a year, until a new full moon come.

      5. Due to these complex rules, it is very difficult to calculate how many days in a month. Now many people in Gringo are turning to you for help.

       

      Input

       

      There are multiple test cases. The first line of input contains an integer T (T<= 20), indicating the number of test cases. Then T test cases follow. There is a blank line between different test cases. The first line of each test case contains 3 integers T1, T2 and T3 (1<=T3<=10000, 5<=T1/T3<=1000, T1 is divisible by T3, T3<T2<T1). The next line contains an integer Q (1<=Q<=100). Then Q lines follow, each line contains two integer Yi and Mi, means the Mith month in Yith year, (1 <= Yi <=5000, 0<= Mi <= 5000).

       

      Output

       

      For each month, output how many days in that months. If there is no such month, output 0.

       

      Sample Input

      1

      3650 295 10

      4

      1 1

      1 2

      2 0

      2 13

       

      Sample Output

      29

      30

      18

      0


      Added by:paradigm2k10
      Date:2010-08-20
      Time limit:1s-11s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Fictious









      SPOJ Problem Set (classical)

      7208. Black or White

      Problem code: BORW

      It’s Black, It’s White, It’s Tough For You To Get By
      Michael Jackson (1958-2009)


      You have a sequence of integers. You can paint each of the integers black or white, or leave
      it unpainted. The black integers must appear in ascending order and the white integers
      must appear in descending order. The ascending/descending order must be strict, that
      is, two integers painted with the same color cannot be equal. Paint the sequence so as to
      minimize the number of unpainted integers.

      Input

      The input contains several test cases, each one described in exactly two lines. The first line
      contains an integer N indicating the number of elements in the sequence (1 ≤ N ≤ 200).
      The second line contains N integers Xi separated by single spaces, representing the
      sequence to paint (1 ≤ Xi ≤ 106 for 1 ≤ i ≤ N ). The last line of the input contains a
      single −1 and should not be processed as a test case.

      Output

      For each test case output a single line with an integer representing the minimum number
      of unpainted elements of the sequence, when the sequence is painted optimally following
      the rules described above.

      Example

      Input:
      8
      1 4 2 3 3 2 4 1
      12
      7 8 1 2 4 6 3 5 2 1 8 7
      -1

      Output: 0
      2

      Added by:Pablo Ariel Heiber
      Date:2010-08-22
      Time limit:120s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2009









      SPOJ Problem Set (classical)

      7209. Closest Triplet

      Problem code: CLOSEST

      Closest pair is an old problem that asks to find, given a set of N points in the plane,
      the pair that minimizes the distance between them. This problem can easily be solved
      using roughly N 2 operations by testing all possible pairs of points and keeping at each
      step the optimal pair. With a more clever approach, the problem has been solved using
      ∼ N log N operations.
      Closest triplet is an analogous problem which also takes a set of N points as input, and
      asks for the triplet (group of three points) that minimizes the sum of the three distances
      between each pair of them. In this case there is also a trivial solution that tests all possible
      triplets using roughly N3 operations. However, since you are a clever programmer, we
      are confident that you are able to find a better algorithm.

      Input

      The input contains several test cases, each one described in several lines. The first line
      contains an integer N indicating the number of points in the set (3 ≤ N ≤ 3000). Each
      of the next N lines describes a different point of the set using two integers X and Y
      separated by a single space (1 ≤ X, Y ≤ 106 ); these values represent the coordinates of
      the point in the XY plane. You may assume that within each test case no two points
      have the same location. The last line of the input contains a single −1 and should not
      be processed as a test case.

      Output

      For each test case output a single line with a real number representing the sum of the
      distances between each pair of points of any closest triplet of the set of points. Round
      the result to the closest rational number with three decimal places. In case of ties, round
      up. Always use exactly three digits after the decimal point, even if it means finishing
      with a zero.

      Example

      Input:
      4
      1 1
      4 1
      1 5
      1000 1000
      9
      100000 200000
      200000 200000
      150000 286603
      60000 140000
      240000 140000
      150000 340000
      1 340000
      300000 340000
      150000 87087
      -1

      Output: 12.000
      300000.796

      Added by:Pablo Ariel Heiber
      Date:2010-08-22
      Time limit:150s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2009









      SPOJ Problem Set ()

      7210. Draw Mountains

      Problem code: DRAWM

      You are a member of a team that is working in a new wonderful graphics program.
      Your task is to write a module for drawing skylines of mountains. However, for now the
      program is in beta version, so each skyline is discretized. This means that your module
      receives as input a sequence of integers representing heights. Each pair of consecutive
      heights in the sequence may differ by at most 1 and produces a column of output, each
      column containing a single character. The particular character to write and its position
      in the column depend on the pair of heights. When both heights are equal an underscore
      (“ ”) must be printed. If the heigths within the pair increase or decrease, you must write
      a slash (“/”) or a backslash (“\”), respectively. The position of the character in the
      column is such that the skyline visually respect the given heights.
      For instance, the sequence of heights (1, 2, 3, 2, 3, 3, 2, 1, 0) must produce the skyline shown
      in the following figure.

          _
       /\/ \
      /     \
             \

      Notice that when the sequence of heights has C + 1 elements, the corresponding skyline
      has only C columns. Given a sequence of heights, you must draw the skyline according
      to the rules given above. See the examples for further clarification.

      Input

      The input contains several test cases, each one described in exactly two lines. The first
      line contains an integer C indicating the number of columns of the skyline (1 ≤ C ≤ 70).
      The second line contains C + 1 integers Hi separated by single spaces representing the
      sequence of heights (0 ≤ Hi ≤ 30 for 1 ≤ i ≤ C + 1). You may assume that there exist
      an height Hi = 0, and that the difference between succesive heights is at most 1 (i.e.
      |Hi − Hi+1 | ≤ 1 for 1 ≤ i ≤ C). The last line of the input contains a single −1 and should
      not be processed as a test case.

      Output

      For each test case output the correponding skyline, followed by a line with exactly three
      asterisks (“***”). While writting the skyline, use only regular spaces, newlines, and the
      three characters mentioned in the statement. Ths skyline must be left aligned and it
      must contain exactly C columns. There must be no trailing spaces at the end of printed
      lines, neither empty lines.

      Example

      Input:
      8
      1 2 3 2 3 3 2 1 0
      3
      1 0 0 1
      -1

      Output:
        _
       /\/ \
      /     \
             \
      ***
      \_/
      ***

      Added by:Pablo Ariel Heiber
      Date:2010-08-22
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2009









      SPOJ Problem Set (classical)

      7211. Elastic Bands

      Problem code: ELASTIC

      The Institute of Circles with Perimetral Connections (ICPC) has recently discovered that
      several machines that were working in their diverse productive areas were totally obsolete.
      Of course, all machines in the Institute contain several circles.
      The Supreme Chief Director Manager President of the ICPC asked their Computer Aided
      Problem Solving department to help in overcoming this situation. They have signaled
      you as the maximum responsible, so you better get to work.
      Many machines in the Institute have mechanical parts in the shape of a circle that need
      to be rotated clockwise in order for the machine to work. Currently, each circular part
      is connected to a different electrical engine that does the job. You noted, however, that
      when many circles are coplanar, you can connect them with elastic bands and they will
      rotate all together with the energy of one engine.
      This marvelous idea lead you to a new problem. What’s the optimal way to connect
      all the circles? In general, there are many ways to place elastic bands and make all the
      circles be connected. Since some of the rotating power of the system is lost in the tension
      of the elastic bands, you want to minimize the total length of elastic bands used.
      Formally, the length of the elastic band that connects two cricles is the perimeter of the
      smallest convex area that contains both circles. The total length is the sum of the lengths
      of all used elastic bands. Two circles can be connected with an elastic band even if the
      band touches or goes through any number of other circles or elastic bands.

      Input

      The input contains several test cases, each one described in several lines. The first line
      contains an integer N indicating the number of circles to connect (2 ≤ N ≤ 3000). Each
      of the next N lines describes a different circle using three integers X, Y and R separated
      by single spaces (1 ≤ X, Y, R ≤ 106 ). The values X and Y represent the coordinates of
      the center of the circle in the XY plane, while the value R indicates its radius. You may
      assume that within each test case no two circles overlap or touch each other. The last
      line of the input contains a single −1 and should not be processed as a test case.

      Output

      For each test case output a single line containing a real number representing the minimum
      total length of elastic band needed to connect all the circles. Round the result to the
      closest rational number with three decimal places. In case of ties, round up. Always use
      exactly three digits after the decimal point, even if it means finishing with a zero.

      Example

      Input:
      3
      2 2 2
      1 6 1
      6 1 1
      2
      1 1 1
      1 4 1
      -1

      Output: 35.829
      12.283

      Added by:Pablo Ariel Heiber
      Date:2010-08-22
      Time limit:240s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2009









      SPOJ Problem Set (classical)

      7212. Find String Roots

      Problem code: FINDSR


      In mathematics, the N-th root of a number M, is a number K such that KN = M , i.e. KKK . . . K = M where K is multiplied N times.
      We can translate this into strings. In string notation, the yuxtaposition is concatenation instead of multiplication. So, the N-th root of a string S is another string T such that TN = S, where T N = T T T . . . T is the string T concatenated N times. For instance, if S = “abcabcabcabc”, for N = 2 the string T = “abcabc” is the N-th root of S, while for N = 4 its N-th root is T = “abc”. Note that for N = 1 any string S is the N-th root
      of S itself.
      Given a string S you have to find the maximum N such that the N-th root of S exists. In the above example the answer would be 4, because there is no N-th root of S = “abcabcabcabc” for N > 4.

      Input

      The input contains several test cases, each one described in a single line. The line contains
      a non-empty string S of at most 105 characters, entirely formed of digits and lowercase
      letters. The last line of the input contains a single asterisk (“*”) and should not be
      processed as a test case.

      Output

      For each test case output a single line with the greatest integer N such that there exists
      a string T that concatenated N times is equal to S.

      Example

      Input:
      abcabcabcabc
      abcdefgh012
      aaaaaaaaaa
      *

      Output: 4
      1
      10

      Added by:Pablo Ariel Heiber
      Date:2010-08-22
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2009









      SPOJ Problem Set (classical)

      7216. The Clocks

      Problem code: CLOCKS

       

      |-------|    |-------|    |-------|    
      | | | | | | |
      |---O | |---O | | O |
      | | | | | |
      |-------| |-------| |-------|
      A B C

      |-------| |-------| |-------|
      | | | | | |
      | O | | O | | O |
      | | | | | | | | |
      |-------| |-------| |-------|
      D E F

      |-------| |-------| |-------|
      | | | | | |
      | O | | O---| | O |
      | | | | | | | |
      |-------| |-------| |-------| (Figure 1)
      G H I

      There are nine clocks in a 3*3 array (figure 1). The goal is to return all the dials to 12 o'clock with as few moves as possible. There are nine different allowed ways to turn the dials on the clocks. Each such way is called a move. Select for each move a number 1 to 9. That number will turn the dials 90' (degrees) clockwise on those clocks which are affected according to figure 2 below.

      Move   Affected clocks

      1 ABDE
      2 ABC
      3 BCEF
      4 ADG
      5 BDEFH
      6 CFI
      7 DEGH
      8 GHI
      9 EFHI (Figure 2)

      Input

       

      Read nine numbers from standard input. These numbers give the start positions of the dials. 0=12 o'clock, 1=3 o'clock, 2=6 o'clock, 3=9 o'clock. The example in figure 1 gives the following input data file:

      3 3 0
      2 2 2
      2 1 2

      Output

       

      Write to the standard output the shortest sequence of moves (numbers), which returns all the dials to 12 o'clock. In case there are many solutions, write the solution which is the least in lexicographic order. In our example the output is as follows:

      4 5 8 9

      Example

      Each number represents a time accoring to following table:
      0 = 12 o'clock
      1 = 3 o'clock
      2 = 6 o'clock
      3 = 9 o'clock

      3 3 0         3 0 0         3 0 0          0 0 0         0 0 0 
      2 2 2 5-> 3 3 3 8-> 3 3 3 4 -> 0 3 3 9-> 0 0 0
      2 1 2 2 2 2 3 3 3 0 3 3 0 0 0

      Note: This just represents a valid sequence of moves, and not the solution


      Added by:BSRK Aditya
      Date:2010-08-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:IOI 94 - Day 2









      SPOJ Problem Set (classical)

      7217. Training for final

      Problem code: TRIKA


      Abotrika is a famous player who plays in a good team , his team is going to play the final match next week and he have to train hard because all his fans are expecting that Abotrika will score more than one goal , so his team-mates suggested helping him in training given that Abotrika will play alone against all his friends in the training.

      Input

      Given two integers N,M (length and width of the training court) ,  2<=N,M<=20 and X,Y the starting point of Abotrika on the court where X is number of row and Y is number of column 1<=X,Y<=N,M then P[i][j],where P is the power of each of his friends 0< P[i][j]<100 , and P[X][Y] is the power of Abotrika.

      Output

      The output must be one line either "N" or "Y  then the maximum power "Abotrika can get when he pass from his friends to reach the (the goal who is at the cell P[N][M] in the court ). NOTE :  Abotrika's power decreases by the power of his team-mate whom Aboutrika succeeded to get through on his way to score a goal. "Y" means that he had scored a goal with power at least 0  and "N" if he couldn't reach the goal with zero power at least … don't forget that Abotrika can move through two directions either right or downwards to reach the goal. 

      Example

      Input:
      

      4 4

      1 1

      100 55 10 2

      20   10 90 1

      60   20 22 4

      1     30 70 5

      Output:

      Y 23

       

      Explaination :

      The maximum power Abotrika can get after reaching goal : 100- (55+10+2+1+4+5)=23 

       

      Input:
      

      2 2

      1 1

      1 55

      20 10

      Output:

      N

      Explaination :

      The maximum power Abotrika can get after reaching goal : 1 - (20+10)=-29 so it will be N 


      Added by:Kawmia Institutes
      Date:2010-08-22
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: BF
      Resource:Own problem









      SPOJ Problem Set (classical)

      7230. Garbage Collection

      Problem code: GARBAGE

      A big office uses a cleaning robot to empty the trash can in every cubicle. The surface of
      each cubicle is a square and the office floor plan is organized as a rectangular matrix of R
      rows of C cubicles each. The cleaning process begins by the robot entering the floor by a
      door that accesses the topmost leftmost cubicle, and finishes with the robot exiting using
      the same door. Both entering and leaving take 26 seconds each. When the cleaning robot
      is in a cubicle it can emtpy the trash can using 13 seconds. The robot can also move to
      a cubicle that shares a side with its current location, using 38 seconds. The robot needs
      to enter in each cubicle at least once to empty its trash can.

      The total time the robot takes for the entire process depends on the actual tour through
      the different cubicles. Among all possible tours, we are interested in those of minimum
      time.

      Given the description of the office, you must indicate the minimum time required for
      the entire cleaning process (including entering, leaving, emptying the trash can in every
      cubicle, and moving around). Notice that it is possible that an optimal tour passes
      through a cubicle several times, but the robot has to take the time to empty the trash
      can only once.

      Input

      The input contains several test cases, each one described in a single line. The line contains
      two integers R and C separated by a single space, representing the number of rows and
      cubicles per row, respectively (1 ≤ R, C ≤ 100). The last line of the input contains the
      number −1 twice separated by a single space and should not be processed as a test case.

      Output

      For each test case output a single line with an integer representing the minimum number
      of seconds that the robot needs to complete the cleaning process.

      Example

      Input:
      4 2
      3 3
      -1 -1

      Output: 460
      549

      Added by:Pablo Ariel Heiber
      Date:2010-08-24
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2009









      SPOJ Problem Set (classical)

      7231. Homework

      Problem code: HOMEW

      When trying to clean your old room, you find out your old notes from high school.
      Reading the homeworks you were given then, you start thinking how much easier they
      would have been today. However, there is a particular one that still seems to maintain
      its difficulty.

      When the solution to a problem involved solving the square root of an integer, to keep
      a fancy and clean expression, you were asked to express it as the integer part and the
      root part. This means that if you had as solution N you were asked to express it
      as √N = A √B with the part A being as high as possible. For instance, 180 can be
      expressed as 1 √180, 2 √45, 3 √20 or 6 √5. Of course, the last expression is the correct
      one.

      Now that you are grown up, you decide to write a program to perform this task for you.

      Input

      The input contains several test cases, each one described in a single line. The line contains
      an integer N (1 ≤ N ≤ 1018 ). The last line of the input contains a single −1 and should
      not be processed as a test case.

      Output

      For each test case output a single line with two integers A and B separated by a single
      space such that √N = A √B and A is maximum.

      Example

      Input:
      180
      17
      1000000000000000000
      -1

      Output: 6 5
      1 17
      1000000000 1

      Added by:Pablo Ariel Heiber
      Date:2010-08-24
      Time limit:400s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2009









      SPOJ Problem Set (classical)

      7232. Inversion Sort

      Problem code: INVESORT

      You have just bought an old fashioned jukebox that can hold 10 music albums. Albums
      are mantained as a sequence, each album represented by a unique lowercase letter between
      “a” and “j”, inclusive. The jukebox allows you to select a subsequence of contiguous
      albums and a mechanical arm inverts that part of the sequence. For instance, if the
      current sequence is “abcdefghij” and you select the subsequence “bcd”, the result of
      the inversion would be “adcbefghij”. Soon you notice that it is possible to get the
      albums into any desired order using simply inversions. However, you are interested in
      doing so with the minimum number of operations.
      Given the current order and a desired order of the 10 music albums, find the minimum
      number of inversion operations needed to obtain the desired order.

      Input

      The input contains several test cases, each one described in a single line. The line contains
      two strings C and D separated by a single space, representing the current and desired
      orders of the music albums, respectively. Each of the strings has exactly 10 characters
      and contains the characters of “abcdefghij” in some order. The last line of the input
      contains two asterisks (“*”) separated by a single space and should not be processed as
      a test case.

      Output

      For each test case output a single line with an integer representing the minimum number
      of inversions needed to transform the current order given by C, into the desired order
      given by D.

      Example

      Input:
      abcdefghij adcbefghij
      abcdefghij abcdefghij
      bcdaefghji beagfcdhji
      * *

      Output: 1
      0
      2

      Added by:Pablo Ariel Heiber
      Date:2010-08-24
      Time limit:240s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6
      Resource:FCEyN UBA ICPC Selection 2009









      SPOJ Problem Set (classical)

      7239. Cells

      Problem code: IPCELLS


      Tim loves spreadsheets. Everything he does on a computer, he does in a spreadsheet. Track his expenses? Create a spreadsheet! Decide which car to buy? Create a spreadsheet to compare them! Make an inventory of his games? Create a spreadsheet! Decide which girl he loves most? …

      Unfortunately his spreadsheet software just crashed and he needs some of the data right now and does not have the time to install a competing office suit.

      Given the formulas used in the cells of a spreadsheet, calculate the values of all the cells.

      Input

      The first line of the input file contains an integer specifying the number of test cases. Each test case is preceded by a blank line.

      Each test case starts a single number giving the number of expression. Each of the following lines contains a single cell formula of the form “CELL = EXPRESSION”, where CELL is the name of the cell and EXPRESSION is a mathematical expression consisting of cell names and the operators +-* and /. A cell name is a non-empty sequence of letters followed by a positive integer.

      Each test case is correct: there are no cycles, and all cells referenced in expressions have definitions.

      Evaluating expressions

      When evaluating an expression, usual priorities apply: first we evaluate all * and / (left to right), and only then all + and - (again, left to right).

      You may assume that the expressions are such that when evaluating the expression in correct order, the result and also all intermediate values will fit into 32-bit signed integer variables.

      The operator / represents integer division which is always rounded down. The dividend will always be non-negative and the divisor will always be positive.

      Output

      For each test case output the calculated values of cells, one per line, in the form “CELL = VALUE”. The rows in the output should be ordered alphabetically. (To compare two rows, take a look at the first character where they differ. The one with a smaller ASCII value goes first.)

      Optionally, output a blank line between test cases.

      Example

      Input:
      2

      3
      A47 = 5 + ZZ22
      ZZ22 = 3
      A9 = 13 + A47 * ZZ22

      2
      A1 = 4 / 7 + 4 / 7
      B2 = 3 * 3 / 7 Output: A47 = 8
      A9 = 37
      ZZ22 = 3

      A1 = 0
      B2 = 1

      Added by:Mohammad Kotb
      Date:2010-08-27
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IPSC









      SPOJ Problem Set (classical)

      7240. Playground

      Problem code: PLYGRND


       

      George has K ≤ 20 steel wires
      shaped in the form of half-circles,
      with radii a1 , a2 , . . . , aK .
      They
      can be soldered (connected) at the
      ends, in any angle. Is it possible
      for George to make a closed shape
      out of these wires? He does not
      have to use all the wires.
      The wires can be combined at
      any angle, but may not intersect.
      Beware of floating point errors.

       

      George has K ≤ 20 steel wires shaped in the form of half-circles, with radii a1 , a2 , . . . , aK . They can be soldered (connected) at the ends, in any angle. Is it possible for George to make a closed shape out of these wires? He does not have to use all the wires. The wires can be combined at any angle, but may not intersect. Beware of floating point errors.

       

       

      Input

       

      Each data set consists of a number 0 < K ≤ 20 on a line by itself, followed by a line of K space-separated numbers ai . Each number is in the range 0 < ai < 10^7 , and has at most 3 digits after the decimal point. 

      The input will be terminated by a zero on a line by itself.

       

      Output

       

      For each test case, there should be one word on a line by itself; “YES” if it is possible to make a simple connected figure out of the given arcs, and “NO” if it isn’t.

       

      Example

      Input:
      1
      4.000
      2
      1.000 1.000
      3
      1.455 2.958 4.424
      7
      1.230 2.577 3.411 2.968 5.301 4.398 6.777
      0
      
      
      Output:
      NO
      YES
      NO
      YES
      

      Added by:Mohammad Kotb
      Date:2010-08-27
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NCPC 2005









      SPOJ Problem Set (classical)

      7248. Chess part1

      Problem code: ROOKS

      Two rooks are to be placed on a chess like N*N game board . each square contains a single non negative integer . the rooks must be placed on different squares.

      We say that some squares on the board are attacked if that square in the same row or same column with the rook but squares containing rooks are not attacked.

      We want to place our rooks so that the total sum of the numbers of all attacked squares is as large as possible . write a program that will find this maximum sum.

       

      Input

      The first line on input will contain N , 2<=N<=300

      Each of the following N lines N integers . each number will be greater than or equal zero and less that 1000 these are numbers on board

       

      Output

      the only line should contain single integer – the maximum sum from the task description

       

      Example

      Input:
      3
      0 1 4
      3 0 2
      1 4 1
      
      Output:
      15
      

      Added by:Kawmia Institutes
      Date:2010-08-30
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Croatian Highschool Competitions in Informatics 2006









      SPOJ Problem Set (classical)

      7249. Perfume

      Problem code: PERFUME


       

      One of the largest perfume shops is making perfumes by mixing fragrant
      essential oils with other compounds. The shop representative told you that what
      really matters in the mixture is the percentages of two main components (call
      them A and B), all other stuff is complementary. For example their first sold
      perfume had 10% of component A and 35% of component B, while the most
      successful one had 16% of A and 20% of B. Sometimes the store needs to
      create a new mixture with specific percentages of A and B and they wonder if
      this can be achieved by mixing some of the mixtures they already have and this
      is where they need your help. For example a new mixture which has 12% of A
      and 30% of B can be created by mixing the two mixtures above in the ratio 2:1,
      while it is impossible to create a mixture which has 13% of A and 22% of B
      using the same two mixtures.

       

      One of the largest perfume shops is making perfumes by mixing fragrant essential oils with other compounds. The shop representative told you that what really matters in the mixture is the percentages of two main components (call them A and B), all other stuff is complementary. For example their first sold perfume had 10% of component A and 35% of component B, while the most successful one had 16% of A and 20% of B. Sometimes the store needs to create a new mixture with specific percentages of A and B and they wonder if this can be achieved by mixing some of the mixtures they already have and this is where they need your help. For example a new mixture which has 12% of A and 30% of B can be created by mixing the two mixtures above in the ratio 2:1, while it is impossible to create a mixture which has 13% of A and 22% of B using the same two mixtures.

       

       

      Input

       

      The first line contains T <= 100, the number of test cases. The first line of each test case contains an integer (1 <= N <= 200), the number of mixtures the shop already has. The next N lines each contain two floating point numbers (0 <= A, B <= 100, A+B <= 100) representing the percentages of components A and B in each mixture. The next line contains an integer (1 <= Q <= 5151) the number of mixtures to verify. The next Q lines each contain two floating point numbers (0 <= A, B <= 100, A+B <= 100) representing the percentages of components A and B in each new mixture. Test cases are separated by one or more empty lines.

       

      Output

       

      For each mixture query print "Yes" if the new mixture can be created from the already existent ones or "No" otherwise. Print a blank line between test cases.

       

      Example

      Input:
      2
      2
      10.0000 35.0000
      16.0000 20.0000
      2
      12.0000 30.0000
      13.0000 22.0000
      3 10 35 16 20 7 15 1 13 22 Output: Yes No

      Yes

      Added by:Mohammad Kotb
      Date:2010-08-31
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ENC09









      SPOJ Problem Set (classical)

      7250. Blocks for kids

      Problem code: PBOARD

      Wango is a brilliant maths teacher. He has two sons Kango and Dango. They are born two years apart on the
      same day! Kango is 9 and Dango is 7. Their birthdays are approaching again. Wango has to buy them a gift
      each. After long thought, this time Wango wanted to give each of his sons a piece of the Pango board and thus
      introduce them to higher mathematics.
      A size n (n >= 0) Pango board is a 2 by n rectangle of unit squares. A pango board has to be tiled with Pango
      pieces. Any tiling with the Pango pieces is acceptable. A size 0 Pango board exists and is unique and serves as
      an example of the empty set.


      Four types of Pango pieces are available.
      1      2     3      4
      ==    ==   ==    ==
      XX    X    X      X
      XX    XX  X


      Picture of the four kinds of pieces

      4 types of blocks


      When Wango presents a board to Kango or Dango, he has to tile the board completely with these pieces
      (unlimited number of pieces of each type are available) and then give them out. Note that pieces cannot be
      rotated for tiling. To cut costs (recession mind you), Wango decides to buy a single board of size N, then
      choose a k (0 <= k <= N), and give a size k board to Kango and a size (N-k) board to Dango, (tiled of course).
      Help him find the number of ways he can give the presents. Two ways are distinct if and only if either Dango
      gets a different board or Kango gets a different board. Two Pango boards are considered the same if and only
      if they have the same tiling (same set of tiles at the same places) from left to right (rotation of board is not
      allowed in comparing).

      Input

      The input consists of a sequence of cases, one per line.
      Each case consists of one integer N (0 <= N <= 1000,000,000) representing the size of the board which
      Wango is going to buy.
      The input will end with a line containing -1. This case should not be processed.
      There will be a maximum of 10000 test cases.

      Output

      One line per case, outputting the number of ways Wango can distribute the presents to his sons modulo
      10,007.

      Example

      Input:
      0
      1
      2
      -1

      Output:
      1
      4
      16

      Explanation:
      Number of different 0-sized Pango boards = 1
      Number of different 1-sized Pango boards = 2
      Number of different 2-sized Pango boards = 6
      For N = 0, he has to give 0-sized boards to both his sons. He can do this in 1*1 = 1 way
      For N = 1, he has to give 0-sized board to one of his sons, and 1-sized board to the other, for a total of 2*1 +
      1*2 = 4 ways
      For N = 2, he can give the presents in 6*1 + 2*2 + 1*6 = 16 ways

      Added by:Manukranth
      Date:2010-09-01
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC Amritapuri (India) Regionals 2008/2009









      SPOJ Problem Set (classical)

      7258. Lexicographical Substring Search

      Problem code: SUBLEX

      Little Daniel loves to play with strings! He always finds different ways to have fun with strings! Knowing that, his friend Kinan decided to test his skills so he gave him a string S and asked him Q questions of the form:


      If all distinct substrings of string S were sorted lexicographically, which one will be the K-th smallest?


      After knowing the huge number of questions Kinan will ask, Daniel figured out that he can't do this alone. Daniel, of course, knows your exceptional programming skills, so he asked you to write him a program which given S will answer Kinan's questions.

      Example:


      S = "aaa" (without quotes)
      substrings of S are "a" , "a" , "a" , "aa" , "aa" , "aaa". The sorted list of substrings will be:
      "a", "aa", "aaa".

       

      Input

      In the first line there is Kinan's string S (with length no more than 90000 characters). It contains only small letters of English alphabet. The second line contains a single integer Q (Q <= 500) , the number of questions Daniel will be asked. In the next Q lines a single integer K is given (0 < K < 2^31).

      Output

      Output consists of Q lines, the i-th contains a string which is the answer to the i-th asked question.

      Example

      Input:
      aaa
      2
      2
      3

      Output: aa
      aaa

      Added by:Damir Ferizovic
      Date:2010-09-02
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Own Problem









      SPOJ Problem Set (classical)

      7259. Light Switching

      Problem code: LITE


      Farmer John tries to keep the cows sharp by letting them play with intellectual toys. One of the larger toys is the lights in the barn.  Each of the N (2 <= N <= 100,000) cow stalls conveniently numbered 1..N has a colorful light above it.

      At the beginning of the evening, all the lights are off. The cows control the lights with a set of N pushbutton switches that toggle the lights; pushing switch i changes the state of light i from off to on or from on to off.

      The cows read and execute a list of M (1 <= M <= 100,000) operations expressed as one of two integers (0 <= operation <= 1).

      The first kind of operation (denoted by a 0 command) includes two subsequent integers S_i and E_i (1 <= S_i <= E_i <= N) that indicate a starting switch and ending switch. They execute the operation by pushing each pushbutton from S_i through E_i inclusive exactly once.

      The second kind of operation (denoted by a 1 command) asks the cows to count how many lights are on in the range given by two integers S_i and E_i (1 <= S_i <= E_i <= N) which specify the inclusive range in which the cows should count the number of lights that are on.

      Help FJ ensure the cows are getting the correct answer by processing the list and producing the proper counts.

      Input


      Line 1: Two space-separated integers: N and M
      Lines 2..M+1: Each line represents an operation with three space-separated integers: operation, S_i, and E_i

      Output

      Lines 1..number of queries: For each output query, print the count as an integer by itself on a single line.

      Example

      Input:
      4 5
      0 1 2
      0 2 4
      1 2 3
      0 2 4
      1 1 4

      Output:
      1
      2

      Added by:Iqram Mahmud
      Date:2010-09-03
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:USACO November 08









      SPOJ Problem Set (classical)

      7260. Number Game

      Problem code: NUMGAME


      Arya and Bran are playing a game. Initially, two positive integers A and B are written on a blackboard. The players take turns, starting with Arya. On his or her turn, a player can replace A with A - k*B for any positive integer k, or replace B with B - k*A for any positive integer k. The first person to make one of the numbers drop to zero or below loses.

      For example, if the numbers are initially (12, 51), the game might progress as follows:

      • Arya replaces 51 with 51 - 3*12 = 15, leaving (12, 15) on the blackboard.
      • Bran replaces 15 with 15 - 1*12 = 3, leaving (12, 3) on the blackboard.
      • Arya replaces 12 with 12 - 3*3 = 3, leaving (3, 3) on the blackboard.
      • Bran replaces one 3 with 3 - 1*3 = 0, and loses.

      We will say (AB) is a winning position if Arya can always win a game that starts with (A,B) on the blackboard, no matter what Bran does.

       

      Given four integers A1A2B1B2, count how many winning positions (AB) there are with A1 ≤ A ≤ A2 and B1 ≤ B ≤ B2.

      Input

      The first line of the input gives the number of test cases, TT test cases follow, one per line. Each line contains the four integers A1A2B1B2, separated by spaces.

      1 ≤ T ≤ 250. 
      1 ≤ A1 ≤ A2 ≤ 1,000,000.
      1 ≤ B1 ≤ B2 ≤ 1,000,000.
      A2 - A1 ≤ 999,999.
      B2 - B1 ≤ 999,999.

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is the number of winning positions (AB) with A1 ≤ A ≤ A2 and B1≤ B ≤ B2.

      Example

      Input:
      3
      5 5 8 8
      11 11 2 2
      1 6 1 6 Output: Case #1: 0
      Case #2: 1
      Case #3: 20


      Added by:Mohammad Kotb
      Date:2010-09-03
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Code Jam 2010









      SPOJ Problem Set (classical)

      7264. Digital LED Number

      Problem code: DIGNUM

      Given a digital LED pattern of a number. You have to find the number and print it. All inputs will be valid as shown.

      Input

      Input consists of LED patterns. Each pattern is given in set of fixed number of lines. You have to read input till EOF.

      Output

      Print the number corresponding to each pattern.

      Example

      Input:
      _ _  _  _  _ _
       _| _| _|| ||_||_
      |_  _||_ |_|  | _|
      _     _    _
        ||_ |_||_  || |
        ||_|  ||_| ||_|
      _  _  _  _    _
        ||_||_||_  ||_|
        |  | | _| ||_|


      Output:


      232095
      164610
      799518

      Added by:XeRoN!X
      Date:2010-09-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7296. Trees Again

      Problem code: CNTTREE

      Given a tree, you need to count how many subtrees with diameter <= K exist.
       
      Input :
      The first line contains the number of test cases T.
      T test cases follow. For each test case, the first line contains N and K. The following N - 1 lines contain two integers ai and bi, indicating an edge between nodes ai and bi in the tree. There is a blank line after each test case.
       
      Output :
      Output T lines, one corresponding to each test case, containing the required answer.
       
      Sample Input :
      2
      3 1
      0 1
      1 2
       
      6 3
      0 1
      1 2
      2 3
      2 4
      3 5
       
       
      Sample Output :
      5
      23
       
       
      Constraints :
      1 <= T <= 100
      2 <= N <= 60
      0 <= ai,bi < N
      1 <= K <= N - 1


      Added by:Varun Jalan
      Date:2010-09-12
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:own problem









      SPOJ Problem Set (classical)

      7297. Placing Coins on a Grid

      Problem code: GRIDCOIN

      In how many ways can R coins be placed on an N * M grid such that each row and each column have atleast 1 coin ?

      Input :
      The first line contains the number of test cases T. T lines follow containing 3 integers: N,M and R. (1 <= T <= 100. 1 <= N,M <= 200. 1 <= R <= N * M)

      Output :
      Output T lines, one for each test case, containing the output for the corresponding test case. Output all values modulo 1000000007

      Sample Input :
      3
      1 1 1
      2 1 1
      2 3 3

      Sample Output :
      1
      0
      6


      Added by:Varun Jalan
      Date:2010-09-12
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:own problem









      SPOJ Problem Set (classical)

      7299. Multiples of 3

      Problem code: MULTQ3

      There are N numbers a[0],a[1]..a[N - 1]. Initally all are 0. You have to perform two types of operations :

      1) Increase the numbers between indices A and B (inclusive) by 1. This is represented by the command "0 A B"
      2) Answer how many numbers between indices A and B (inclusive) are divisible by 3. This is represented by the command "1 A B".

      Input :
      The first line contains two integers, N and Q. Each of the next Q lines are either of the form "0 A B" or "1 A B" as mentioned above.

      Output :
      Output 1 line for each of the queries of the form "1 A B" containing the required answer for the corresponding query.

      Sample Input :
      4 7
      1 0 3
      0 1 2
      0 1 3
      1 0 0
      0 0 3
      1 3 3
      1 0 3

      Sample Output :
      4
      1
      0
      2

      Constraints :
      1 <= N <= 100000
      1 <= Q <= 100000
      0 <= A <= B <= N - 1


      Added by:Varun Jalan
      Date:2010-09-12
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:own problem









      SPOJ Problem Set (classical)

      7301. Lucky Controller

      Problem code: LCKYCONT

      Egor works as a controller in the bus. Each day he is given a pack of tickets which he then sells. Recently he has become interested about how many tickets in the pack are lucky. He thinks that the more tickets are lucky the luckier day he will have. No he wants to find out how lucky for him will the next day be. The numbers of all tickets consist of n digits. The ticket is considered to be lucky if the sum of the first n/2 digits equals to the sum of the last n/2 digits. Egor knows that the numbers in the pack that he will be given can start with equal probability from any number in the interval from a to b inclusive. The pack holds k tickets. The numbers in the tickets are consecutive. Help Egor find out the expected amount of lucky tickets in the pack.

      Input

      The first line of the input file contain number n - the amount of tests. The next n lines consist of three integers a, b и k (0 <= a <= b < 10^12, 1 <= k <= 100000). Integers a, b and b+k consist of the same amount of digits which is equal to the amount of digits in the number of each ticket. They may start with zeroes. The amount of digits in a and b is always even.

      Output

      Output the expected quantity of lucky tickets in the pack in the form of irreducible fraction. In case the result is an integer, no slash should appear in the output.

      Example

      Input:
      3
      0123 4567 150
      10 10 20
      4000 4999 11
      
      Output:
      6519/635
      2
      103/125
      
      

      Added by:Spooky
      Date:2010-09-12
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Open All-Ukrainian Collegiate Contest Final, 2010









      SPOJ Problem Set (classical)

      7322. Prime Pattern

      Problem code: CHEFJUN

      There is a very large field, colored white and divided into squares. There is a coordinate system attached to the field: y-axis goes from south to north and x-axis goes from west to east. Sides of the squares are parallel to the axes. There is a robot in the (0, 0) square. Robot starts to move in spiral as depicted. First it moves one step east and one step north. Then two steps west and two steps south. Then three steps east and three steps north, four steps west and four steps south and so on. It moves to a new square with each step. As it moves it counts squares it passes and, if the number of the square is the prime number, then the robot fills this square with black color. The (0, 0) square has the number 0. Given the coordinates of a square you are to calculate the distance from this square to the nearest to it black square. For two squares with coordinates (x1, y1) and (x2, y2) the distance between those squares is |x1-x2|+|y1-y2|.

       

      Input

      Input file consists of a set of tests. The first line of the file is number T – the number of tests (T <= 500). Following T lines contains two integers each separated with a space: x and y – the coordinates of the square (-2000001 < x < 2000001, -2000001 < y < 2000001).

      Output

      For each coordinate pair in the input file you are to output the distance between this square and the nearest to it black square.

      Example

      Input:
      8
      0 0
      1 0
      1 1
      0 1
      3 3
      -3 -3
      -1 2
      0 -3
      
      Output:
      1
      1
      0
      0
      1
      1
      2
      2
      
      

      Added by:Spooky
      Date:2010-09-14
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:CodeChef June Challenge









      SPOJ Problem Set (classical)

      7323. Happy Days

      Problem code: CHEFJUL

      Johnny has a pool in his garden. There are several islands in the pool. Some islands are connected by bridges. Any bridge can be removed. Every day Johnny removes some bridges so that there is only one way from any island to any other. In the evening he returns removed bridges to their places. Also he has some favorite bridges which he never removes. Johnny will be happy if he is able to make a configuration of bridges on the given day which he has never made before. You have to count the amount of days he will be happy. Of course, if the favorite bridges themselves don't satisfy the happiness condition Johnny will not be happy for even single day.

      Input

      The first line of input file contains number t the number of test cases. Then the description of each test case follows. The first line of each test case contains number n the number of islands. Islands are numbered with integers from 1 to n. Then n lines follow each containing n characters defining the connectivity matrix of those islands. Character in column x of line y will be 1 if the islands with numbers x and y are connected and 0 otherwise. The next line is number p the number of favorite bridges. The next p lines contain the pairs of islands that are conected by favorite bridges.

      Constraints

      1 <= t <= 5
      2 <= n <= 30
      1 <= p <= min(6, n-1)

      Output

      For each test case print the number of days Johnny will be happy in this situation.

      Example

      Input:
      1
      4
      0111
      1011
      1101
      1110
      2
      1 2
      3 4
      
      Output:
      4
      
      

      Added by:Spooky
      Date:2010-09-14
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:CodeChef July Challenge









      SPOJ Problem Set ()

      7333. Shuffle Music

      Problem code: SHUFFLEN

      My office is quite far from my home. Every day, I go there by bus. That takes a lot of time. More over, due to traffic jams, the time to reach my office is not fixed. To make the best use of this time, I carry my music player all the time. My music player has a ‘shuffle’ mode. In that mode, the music player selects a track randomly that has not been played in that session (before the next Shuffle), and starts playing. It will continue doing so, until, I have stopped playing, or it has played all tracks in that session.

      For the purpose of this problem, you can assume that all tracks are of equal duration. To select randomly, the player keeps list of the tracks already played. That is, if I listen to one track now, from next shuffle session, that track will be marked as played.

      In addition, after stopping play, when it shuffles once more, to select a random track, the player always use such strategy that, selecting an old track (Already listened in previous shuffle session) is twice more probable than a new track (Not listened in previous shuffle session). I go to my office in the morning and return home at night.  Performing 2 shuffles a day, one in the morning, one at night.

      It takes at least p minutes and at most q minutes to reach my office. The time required will always be an integer. You can assume that all travel times are equiprobable (that is, if p = 2 and q = 4, and if P(t) is the probability to reach office in t minutes, then P(2) = P(3) = P(4)). If all tracks are of 1 minute, how many days on average are required to listen to all the songs?

      Input

      First line of input contains an integer T(≤10053), the number of test cases. Each test case contains 5 integers, N (1≤N≤75), p1, q1, p2, q2 (0 ≤ p1, q1, p2, q2 ≤ 30, p1 ≤ q1, p2 ≤ q2), where N is the number of songs, p1,q1 are the minimum and maximum number of songs listened during day, and p2,q2 are the minimum and maximum number of songs during night.

      Output

      For each test case, output the test case, followed by the expected number of days required to listen all songs. If it’s not possible to listen to all songs, output “IMPOSSIBLE”.

      The Judge used is "Ignore FP rounding up to 10^-6".

      Example

      Input:

      11
      1 0 1 0 1
      20 0 26 1 3 10 11 21 0 0 64 0 0 1 23 48 0 0 0 0 42 18 29 6 13 29 19 25 0 0 32 0 0 8 27 75 0 1 0 1 75 0 1 0 0 75 0 0 0 1 Output:
      Case 1: 1.3333333
      Case 2: 3.1143655 Case 3: 1.0000000 Case 4: 39.6303478 Case 5: IMPOSSIBLE Case 6: 7.1950023 Case 7: 4.7682679 Case 8: 8.1514607 Case 9: 660.4533446 Case 10: 1320.4066892 Case 11: 1320.4066892

      Hint

      Calculate P [n] [ rest ] [q] [next]. It is in this session, we have not heard the song in each n songs played,
      with "rest" number of songs never heard, with q minutes played so far,
      the probability of "next" song been played for the first time. Dp by this O (N ^ 2q ^ 2).
      Sum over [0, q] to get P [n] [rest] [qsum] [next], so we can use subtraction to get interval sums.

      Now let 0 be day, 1 by night, then we compute dp[0][rest], dp[1] [rest], the expected number of days it takes to
      finish all the songs if only considering day or night. dp [0] [rest] is [0, rest) of dp [1] [rest] and P [n] [rest] [qsum] [next].
      Using O ( rest ) can be calculated as as X = dp[0][rest], Y = dp[1] [rest], then {X = a Y + c, Y = b X + d}.
      Solving this, and done.
      In the base case with rest=1, use infinite geometric series to compute overall O (TN ^ 2 + N ^ 2q ^ 2).


      Added by:Chen Xiaohong
      Date:2010-09-17
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Thailand National 2010, Statement Clarified and Enhanced to remove ambiguity.









      SPOJ Problem Set (classical)

      7337. Shuffling

      Problem code: SHUFFLE1

      A casino owns an expensive card shuffling machine which may shuffle up to 520 cards at a
      time (there are 52 cards in each deck). For convenience, we will simply label the cards 1, 2,
      3, ..., N where N is the total number of cards, and copies of the same card (e.g. Ace of
      Spades) from different decks are considered different. Unfortunately, the card shuffling
      machine is defective, and it always shuffles the cards the same way. The company that
      produces these machines is out of business because of the economic downturn. There is no
      one who can fix the machine, and a new machine is too expensive.


      Being a brilliant employee of the casino, you realized that all is not lost. You can shuffle the
      cards differently simply by using the machine zero or more times. For example, suppose
      that the machine shuffles the cards 1, 2, 3, 4 into the order 2, 3, 4, 1. If you put the cards into
      the machine, take the shuffled cards out and insert them into the machine again (without
      changing the order), you will get the order 3, 4, 1, 2. That way, it is possible to shuffle the
      cards in many different ways even though it may take longer. But this is not a significant
      issue since decks do not have to be reshuffled often, and used decks can be shuffled while
      other decks are being used to avoid any waiting time.


      Unfortunately, not all shufflings can be produced in this way in general, and you wish to
      know if this procedure "stack the decks" in a favorable way for the casino or the player. As
      a first step, you wish to know which shufflings are possible to produce, and how many times
      you need to use the machine on the deck in order to produce the shuffling.

      Input

      The input for each case consists of three lines. The first line consists of a single integer N
      indicating the number of cards to shuffle. The number of cards is a positive integer up to
      520. The second line consists of the integers 1, 2, ..., N listed in some order and separated by
      a space. The list gives the order of the shuffling performed by the machine when the input
      cards are ordered 1, 2, ..., N. The third line is in the same format as the second line, and
      gives the shuffling we wish to obtain. The end of input is indicated by a line in which N = 0.

      Output

      For each case, print the smallest number of times (zero or more) you need to pass the deck
      through the machine to produce the desired shuffling. If it is not possible, print -1. The
      output for each case should be in a single line. You may assume that the answer will always
      fit in a 32-bit signed integer.

      Example

      Input:
      4
      2 3 4 1
      3 4 1 2
      4
      2 3 4 1
      1 3 2 4
      10
      2 1 3 5 6 7 8 9 10 4
      1 2 3 9 10 4 5 6 7 8
      0
      Output: 2
      -1
      12

      Added by:Varun Jalan
      Date:2010-09-19
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Rocky Mountain Regionals 2009/10









      SPOJ Problem Set (classical)

      7356. Iterated Bitcount Function

      Problem code: ITERBIT

      Let f(x) be the number of 1's in the binary representation of x.

      We can define f^k(x) as f(x) for k = 1, and f^(k-1)(f(x)) for k > 1.

      Let f^*(x) be the smallest k >= 1 such that f^k(x) = 1.

      Given N and K, how many numbers x between 1 and N inclusive have f^*(x) = K ?

      Input :
      The first line contains the number of test cases T. Each of the next T lines contains two space seperated numbers N and K.

      Output :
      Output one line corresponding to each test case, containing the answer for the corresponding test case. Output all answers modulo 1000000007.

      Sample Input :
      6
      1 1
      2 1
      3 1
      3 2
      13 3
      20 2

      Sample Output :
      1
      2
      2
      1
      3
      10

      Constraints :
      1 <= T <= 1000
      1 <= N <= 10^500
      1 <= K <= 10


      Added by:Varun Jalan
      Date:2010-09-20
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:own problem, used for Al Khwarizm '10









      SPOJ Problem Set (classical)

      7363. Tree Sum

      Problem code: TREESUM

      Let Lx denote the level of a node x in a rooted tree. Lx is 1 if x is the root, otherwise Lx = 1 + Ly, where y is the parent of x in the rooted tree.

      You need to calculate the sum Lx ^ K for all nodes x in the tree.

      Input :
      The first line contains the number of test cases T. T test cases follow. The first line of each test case contains N and K, where N is the number of nodes in the tree. The following N - 1 lines contain two integers ai and bi, indicating an edge between nodes ai and bi in the tree. There is a blank line after each test case.

      Output :
      Output N lines for each test case. The ith line should contain the required sum if the tree is rooted at node i. Output all values modulo 1000000007. Output a blank line after each test case.

      Sample Input :
      2
      3 2
      0 1
      1 2

      3 3
      0 1
      0 2

      Sample Output :
      14
      9
      14

      17
      36
      36

      Constraints :
      1 <= T <= 10
      1 <= N <= 20000
      1 <= K <= 20
      0 <= ai,bi < N


      Added by:Varun Jalan
      Date:2010-09-20
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem, used for Al Khwarizm '10









      SPOJ Problem Set (classical)

      7378. Manhattan Companies

      Problem code: MCOMP

      Everyone knows what Manhattan streets look like. For simplicity, we'll say there are two types of streets: horizontal and vertical (when seen on a map). For two junctions A and B, with coordinates (ax, ay), (bx, by) respectively, we define distance( A, B ) = |ax-bx| + |ay-by|.

      A company in Manhattan has the following problem: we have to link N junctions by couriers in such a way that each pair of  junctions can communicate through the couriers. We must use the minimal possible number of couriers to do so. Also, of all the possible solutions with the minimal number of couriers, we'll take the one that minimizes the maximum distance of assigned junction pairs over all the couriers.

      Input

      The first line of input contains a single integer: N (2 <= N <= 105).
      The next N lines each contains two integers: xi and yi (0 <= xi, yi <= 105).

      Output

      The first and only line of output should contain the minimal maximum distance over all the couriers defined above.

      Example

      Input:
      3
      0 0
      0 2
      2 0
      Output: 2
      Explanation: couriers go between junction pairs ( 1, 2 ) and ( 1, 3 ). 
      Maximum distance is 2.

      Added by:Gustav Matula
      Date:2010-09-23
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set ()

      7380. Factorial challenge

      Problem code: FUNFACT

      Ling: Stir, let's go out and play our favorite game.

      Stir: I am already having fun with my first factorial program.

      Ling: Than I will give you a challenge on factorials. If you fail in it, you will have to come.

      Stir: ok..

      Ling gives Stir a number x and the challenge is to find the largest value of n such that n! is not greater than the largest value that can be formed by x digits. Stir is stuck with the problem and needs your help. Now, it's your turn to make sure that Stir can continue having fun with factorials.

      Input

      The first line of the input contains a number t (about 10^5), the number of the test cases. The next t lines contain a number x (1 <= x <= 10^9).

      Output

      Output a total of t lines with each line containing the value n corresponding to the input case.

      Example

      Input: 
      2
      1
      7

      Output:
      3
      10

      Added by:Siddharth Kothari
      Date:2010-09-23
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Own problem









      SPOJ Problem Set (classical)

      7386. Activities

      Problem code: ACTIV

      Ana likes many activities. She likes acrobatics, alchemy, archery, art, Arabic dances, and
      many more. She joined a club that offers several classes. Each class has a time interval
      in every week. Ana wants to sign up for many classes, but since they overlap in time, she
      looks for a subset of non-overlapping classes to attend. A subset is non-overlapping if it
      does not contain two classes that overlap in time. If a class starts at the time another
      class ends, this is not considered overlapping.
      Ana decided to list all the non-overlapping non-empty subsets of classes. Then she will
      choose the subset she likes best. In order to predict the amount of paper needed to write
      the list, she wants you to calculate how many of these subsets there are.

      Input

      Each test case is described using several lines. The first line contains an integer N
      indicating the number of classes the club offers (1 ≤ N ≤ 105 ). Each of the next N lines
      describes a class using two integers S and E that represent the starting and ending times
      of the class, respectively (1 ≤ S < E ≤ 109 ). The end of input is indicated with a line
      containing a single −1.

      Output

      For each test case, output a single line with a single integer representing the number of
      non-overlapping non-empty subsets of classes. To make your life easier, output only the
      last 8 digits of the result. If the result has less than 8 digits, write it with leading zeros
      to complete 8 digits.

      Example

      Input: 
      5
      1 3
      3 5
      5 7
      2 4
      4 6
      3
      500000000 1000000000
      1 500000000
      1 500000000
      1
      999999999 1000000000
      -1 Output:
      00000012
      00000005
      00000001

      Added by:Pablo Ariel Heiber
      Date:2010-09-24
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set (classical)

      7387. Airplane Parking

      Problem code: PKA

      During this economic crisis time, Jack has started an incredible new business related to air travel, a parking-lot for airplane. He bought a very large land to park airplanes. However the land is very narrow, so that the only way airplanes can go in or go out of the parking lot must be in the Last-In First-Out fashion (see picture below). He only has spaces in the parking lot so he cannot take some airplane at the end out so that other airplanes can move. Because of the limitation of the parking lot, it is not possible to accommodate all requests for parking. Each request consists of the planned arrival time and planned departure time, which are the times the airplane arrives at the parking lot.

      An example below shows a request table for 4 planes.
      Airplane Arrival Departure
      1 1 10
      2 2 5
      3 3 7
      4 6 9
      In this case, it is possible to accommodate airplane 1, 2, and 4. But it is not possible to accommodate both airplanes 2 and 3. It is possible that different planes plan to arrive or depart the parking lot at the same time. Jack has the best crews working with him, so that they will manage to arrange the plane to the parking lot in the best way that if it is possible to park and take out the planes they will be able to do it.

      Consider another example.
      Airplane Arrival Departure
      5 10 12
      6 10 15
      7 13 17

      Although airplane 5 and 6 arrive at the same time, Jack's crews know that airplane 5 will have to be out before airplane 6, so when both airplanes arrive they put airplane 6 in first, following by airplane 5.


      Given a list of parking requests, you want to find the maximum number of airplanes that can be parked in this parking lot, provided that they can only depart in the Last-In First-Out fashion.

      Input

      The first line contains an integer T, the number of test cases (1 < T < 5). Each test case is in the following format. The first line starts with an integer N (1 < N < 300) denoting the number of airplanes. The next
      N lines describe the request table. Each line 1 + i, for 1 < i < N, contains two integer Si and Ti, (0 < Si < Ti < 1,000,000,000) which are the planned arrival time and planned departing time for airplane i.

      Output

      For each test case, you program must output a single line consisting of one integer, the maximum number of airplanes that can be parked in Jack's parking lot.

      Example

      Input: 
      2
      4
      1 10
      2 5
      3 7
      6 9
      3
      10 12
      10 15
      13 17
      Output:
      3
      2

      Added by:Race with time
      Date:2010-09-25
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:ACM ICPC Phuket 2009 - 2010









      SPOJ Problem Set (classical)

      7389. Rating Hazard

      Problem code: PKD


      A very important aspect of web portals is customer reviews. The customers can rate any product in the web portal. Generally, a customer can rate a product from one star to five star. Based on the rating of all the customers the average customer rating for a product is shown. Look at the figure on the left to get a clear idea. For example if three customers rate a product as 3 star, 4 star and 4 star respectively then the average rating will be (3+4+4)/3 = 3.67 (Rounded to two digits after the decimal point). In the figure on the left 847 customers have rated a product and 597, 189, 26, 11 and 24 customers have rated the product as 5 star, 4 star, 3 star, 2 star and 1 star respectively. So the average rating is: (Rounded to eight digits after the decimal point).

      Most web portals display the total number of people who have rated the product (As more people rates the product the more reliable the rating is) but do not display the numeric value of the average rating. In the web portal of warzone (A renowned web portal) the total number of customers that have rated a product (In the figure above the total 847 customers have rated the product) and the average rating is stored in two different tables. The average rating is stored, rounded to n (0<n<9) digits after the decimal point so its value is not always the exact average value. Unfortunately, the table that stored the total number of people that rated different products somehow got corrupted. All information available in the database now is the average rating (rounded to at most eight digits after the decimal point). They do not want to lose the huge number of customer ratings they have received throughout 10-15 years but also they cannot cheat with their customers by guessing the number of raters or voters. So from the average rating they want to determine the minimum possible number of people that rated that product. You have to help them find it out by writing a program.

      Input

      The input file can contain up to 2000 lines of inputs. Each line contains a non-negative floating- point number v (1 ≤ v ≤ 5). This number will have minimum one digit and maximum eight digits after the decimal point. If this number has n digits after the decimal point then you have to assume that the value of the average is given rounded to n digits after the decimal point. Input is terminated by a line containing a negative number.

      Output

      For each line of input produce one line of output. This line contains the serial of output followed by an integer T which denotes the minimum number of voter that is required for this average rating.

      Example

      Input: 
      1.15
      4.56316411
      4.56316
      3.67
      3.66
      -1.00
      Output: 
      Case 1: 13
      Case 2: 847
      Case 3: 190
      Case 4: 3
      Case 5: 29

      Added by:Race with time
      Date:2010-09-25
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:ACM ICPC Phuket 2009 - 2010









      SPOJ Problem Set (classical)

      7402. Repair Depots

      Problem code: PC8H

      RoboCorp Oregon has already deployed several of its PoliceBots throughout the state, and suddenly they have remembered the importance of being able to repair these bots when they break. They are willing to build only a limited number of repair depots in the state, and they want to locate these depots so that each PoliceBot's city is within a given distance of some depot. You are given the locations of where the n (1 ≤ n ≤ 16) PoliceBots have been deployed, and the maximum number (1 ≤ c ≤ n) of repair depots that RoboCorp is willing to construct. Your job is to locate these repair depots to minimize the distance any bot has to be transported for repair, and return what that maximum distance is. You can assume that any bot can be repaired at any depot.

      Input

      The first line contains the integer t (1 ≤ t ≤ 350), the number of cases. Each case starts with a line containing n and c. Following this line is one line per deployed bot; that line contains two floating point values, separated by a single space, giving the Cartesian coordinates of the bot. Each such value will be between 0.0 and 10.0, inclusive (NOTE: the Sample Input shows integer values for brevity).

      Output

      You are to print for each input set the minimum value that can be obtained, such that each PoliceBot is within that distance of some depot. You should print your result with at least one digit before and exactly six digits after the decimal point; your value should be within 5e-7 of the true result. To make round-off error less of a concern, the true result will never have a 4 or a 5 as the seventh digit after the decimal point.

      Example

      Input: 
      2
      9 3
      1 1
      1 2
      1 3
      2 1
      2 2
      2 3
      3 1
      3 2
      3 3
      4 2
      0 0
      1 1
      2 4
      3 9
      
      Output: 
      1.000000
      2.236068
      

      Added by:Race with time
      Date:2010-09-25
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:ACM Pacific Northwest 2008









      SPOJ Problem Set (classical)

      7403. Messy Administration

      Problem code: MESS

      For the fall semester 2010, EPFL proudly welcomed 2’300 new students to the campus. Handling their registrations to the different sections and levels requires an administrative masterstroke. Nowadays this process is highly automated and worked impeccably up to this year...

       

       

      The software that handles the registrations wasn’t lead out for such a huge number of new students and the secretaries were close to a heart attack when they received the registration printouts. Instead of receiving one sheet per class (defined by the orientation of studies and the level, e.g. Architecture, Bachelor 1) containing the list of all the students registered to that class, the printouts contained sentences in 5 different formats:

      • ! STUDENT_ID1 studies SECTION
      • ! STUDENT_ID1 enters semester SEMESTER
      • ! STUDENT_ID1 and STUDENT_ID2 chose the same studies
      • ! STUDENT_ID1 and STUDENT_ID2 are in same semester
      • ! STUDENT_ID1 and STUDENT_ID2 are in same class

      STUDENT_ID1 and STUDENT_ID2 are the 6-digit sciper numbers, SEMESTER is an integer number in the range from 1 to 10 and SECTION is a one-worded string.

      The secretaries were very puzzled and couldn’t figure out how to recreate the expected lists from these printouts. But luckily they remembered PolyProg. The desperate secretaries provide you with the printouts and you are to answer their impatient questions to your best.

      • ? What does STUDENT_ID1 study
      • ? Which semester will STUDENT_ID1 enter
      • ? Are STUDENT_ID1 and STUDENT_ID2 classmates

      Two students are considered to be classmates if and only if they study the same subject and enter the same semester. Answering to your best means that your answer must be as complete as possible, you must never give an erroneous answer, but you can just admit that the input was insufficient to answer a question at the point in time it was asked.

      Your answers shall respect the following priority:

      Question

      Answer

      ? What does STUDENT_ID1 study

      STUDENT_ID1 studies SECTION

      Sorry, I have no clue yet

       

      ? Which semester will STUDENT_ID1 enter

      STUDENT_ID1 enters semester SEMESTER

      Sorry, I have no clue yet

      ? Are STUDENT_ID1 and STUDENT_ID2 classmates

       

      Yes, STUDENT_ID1 and STUDENT_ID2 are classmates

      No, this is not possible

      Possible, given that STUDENT_ID1 and STUDENT_ID2 study the same subject

      Possible, given that STUDENT_ID1 and STUDENT_ID2 are in the same semester

      Sorry, I have no clue yet

       

      INPUT

      The input consists of a single test-case with no more than 1’000 printout sentences and no more than 500 questions. They may be mixed and you are to go through them in sequential order, which means that in order to answer a question, you must not rely on any information further down the list. You may safely assume that the sentences are not contradictory! Input terminates on a line containing the single word END.

       

      OUTPUT

      Output your answers, one per line and terminate with a newline. Be aware of typos :)

       

      SAMPLE INPUT

      ! 166554 and 175129 chose the same studies

      ! 175129 and 170113 are in same semester

      ! 166554 studies electronics

      ! 169983 and 170113 chose the same studies

      ? Are 170113 and 169983 classmates

      ! 169983 enters semester 9

      ! 175129 and 169983 are in same semester

      ? Which semester will 170113 enter

      ? Are 169983 and 170113 classmates

      ? Which semester will 166554 enter

      ? What does 175129 study

      ! 169983 studies communicationsystems

      ? Are 166554 and 169983 classmate

      END

       

      SAMPLE OUTPUT

      Possible, given that 170113 and 169983 study the same subject

      170113 enters semester 9

      Yes, 169983 and 170113 are classmates

      Sorry, I have no clue yet

      175129 studies electronics

      No, this is not possible


      Added by:Christian Kauth
      Date:2010-09-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS









      SPOJ Problem Set (classical)

      7404. Just on Time

      Problem code: ONTIME

      Last week’s campaign on healthy and environmentally friendly mobility was a big success. Hundreds of commuters to the EPFL campus traded their car for a ride by bus or metro and gave a very positive feedback. They merely complained about earlier wake-up times necessary to reach the campus on time.

       

       

      This is where you enter the story. Try to improve the mood of the people by indicating them the latest time they can leave their house such that they can reach the campus no later than 8h15. Any means are ok to maximize their sleeping time, and all would accept to change bus or metro lines several times during their journey if this helps your planning.

      The public transport network is made up of S (0<=S<=100)  stations (numbered from 1 to S) and counts C (0<=C<=1'000)  unidirectional connections that link two stations in regular time intervals, starting from a certain time in the morning and up to 8h15. Note that for any two stations, there might exist several direct shuttle services with different starting time and frequency. You are to answer some students’ request on the latest possible time they can leave from home in order not to be late.

       

      INPUT

      The input consists of several test-cases separated by an empty line. Each test-case starts with the number of stations S, the number of connections C and the number of requests R on a line. Then come C lines, each describing one shuttle service in the format ‘from’ ‘to’ ‘firstRide’ ‘travelTime’ ‘frequency’ (in minutes). The next R lines each hold two integers, the first being the closest station to the student’s home (come what may, but so early no student would like to walk more than necessary) and the second the time (in minutes) it takes the student to reach that station. The campus is located at station S. Input terminates on a test-case with S=C=R=0, which must not be evaluated.

       

      OUTPUT

      Answer the requests in the same order as they appeare in the input. For each request, print a line in the form “Leave no later than ‘time’”, where ‘time’ is in the format hh:mm. Add an empty line after each test-case. If there is no way the students can make it on time, output “Doomed to be late”. You can safely assume that the commuters are so experienced in hopping on and off busses that they can change busses in no time at all.

       

      SAMPLE INPUT

      3 2 2

      1 3 07:10 50 15

      2 3 08:20 5 5

      1 3

      2 0

       

      3 4 3

      2 3 05:30 6 5

      1 3 06:11 5 15

      1 2 07:01 2 5

      3 2 08:00 1 8

      1 2

      2 1

      3 10

       

      0 0 0                            

       

      SAMPLE OUTPUT

      Leave no later than 07:22

      Doomed to be late

       

      Leave no later than 07:59

      Leave no later than 08:04

      Leave no later than 08:05

       


      Added by:Christian Kauth
      Date:2010-09-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS









      SPOJ Problem Set (classical)

      7405. Delicious Pancakes

      Problem code: PANCAKES

      Just as promised, PolyProg will invite you to a bounteous pancake buffet right after this contest. Can you already feel the seductive odours dazing your senses? Well, before your mouth starts watering, you should solve this last problem.

      As you might know, the basic ingredients to pancakes are flour, milk and eggs. These may be completed by a passel of additional toppings such as sugar, jam, berries, cheese, ham, mushrooms etc. As the chef of the evening was yet uncertain about the recipe he’d whip up tonight, he asked his assistant simply to buy random quantities of each ingredient.

      With these quantities he could make N1 pancakes according to recipe 1, N2 if he decides to follow recipe 2, N3 for recipe 3 and so on and so forth. As the end of the competition is close, the chef will not have enough time to combine several recipes: All pancakes tonight will be of the same taste (too bad :( ). The repertoire of recipes is huge, and as we imagine you to have a ravenous appetite, you are to select the recipe that yields the largest number of pancakes.

       

      INPUT

      The input consists of several test-cases separated by an empty line. The first line of each test-case holds the number of ingredients N (1<=N<=50) the assistant bought followed by the number of recipes R (1<=R<=100) in the chef’s repertoire. Each of the next lines contains exactly N non-negative integers (no larger than 106) informing about the ingredients. The first of these lines lists the quantities the assistant bought of each ingredient. The remaining R lines list the quantities (in the same order as the previous line) necessary to make ten pancakes according to the recipe ri (from 1 to R). The input ends on a test-case having both N and R zero, which must not be processed.

       

      OUTPUT

      Your program should produce one line per test-case containing the recipe that yields the largest number of pancakes followed by the number of entire pancakes that can be made then. If there is a tie, prefer the recipe that appears first in the input.

       

      SAMPLE INPUT

      3 2

      20 20 20

      5 10 1

      2 1 3

       

      6 3

      100 60 130 80 100 90

      10 5 10 5 10 5

      1 2 1 2 20 7

      0 0 0 10 30 1

       

      0 0

       

      SAMPLE OUTPUT

      2 66

      1 100

       


      Added by:Christian Kauth
      Date:2010-09-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS









      SPOJ Problem Set ()

      7406. Beehive Numbers

      Problem code: BEENUMS

      A beehive is an enclosed structure in which some honey bee species live and raise their
      young. In this problem we consider a two-dimensional sketch of the beehives. Each
      beehive is composed of a certain number of cells, where each cell is a regular hexagon.
      Each cell may have some neighbors, which are other cells that share a side with that cell.
      A cell with exactly 6 neighbors is an internal cell, while a cell with fewer neighbors is an
      external one. Notice that an external cell can always be changed to internal by adding
      some neighbor cells.


      We are interested in a particular class of beehives. This class of valid beehives is defined
      recursively as follows: a) a single cell is a valid beehive; and b) given a valid beehive B,
      if we add the minimum number of cells such that each external cell of B becomes an
      internal cell, the result is a valid beehive.

      The number of cells in a valid beehive is called a beehive number. Given an integer N ,
      you must decide whether it is a beehive number.

      Input

      Each test case is described using a single line. The line contains an integer N (1 ≤ N ≤
      109 ). The end of input is indicated with a line containing a single −1.

      Output

      For each test case, output a single line containing an uppercase “Y” if N is a beehive
      number, or an uppercase “N” otherwise.

      Example

      Input:
      43
      1
      7
      19
      15
      -1 Output:
      N
      Y
      Y
      Y
      N

      Added by:Pablo Ariel Heiber
      Date:2010-09-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set (classical)

      7408. Camelot

      Problem code: CAMELOT

      Camelot is a solitaire game that is played with a deck of French cards. The deck contains
      52 cards, each of them having a suit and a face value. There are 4 possible suits and 13
      possible face values. Since for this solitaire suits are not important, we consider that the
      deck contains 4 repetitions of each possible face value. Face values are A, 2, 3, 4, 5, 6, 7,
      8, 9, 10, J, Q and K.

      The solitaire starts with the full deck placed, face down, on the table. There is also a
      board containing 16 empty slots arranged in a 4 by 4 grid. The game repeatedly alternates
      two phases: a dealing phase and a removal phase.
      The first phase is a dealing phase. During this phase cards are dealt from the deck one
      at a time. Each card is placed, face up, in an empty slot. However, certain cards can
      only be placed in specific slots: Jacks (face value J) can only occupy the middle two slots
      of first and last columns. Queens (face value Q) can only occupy the middle two slots of
      first and last rows. Finally, Kings (face value K) can only occupy the corner slots. Cards
      having other face values can be placed in any empty slot. The game is lost whenever a
      card is dealt from the deck for which no valid empty slot exists. Each time the last empty
      slot has just been occupied, or when the deck is empty, a removal phase starts.

      During a removal phase, it is possible to remove from the board any card or pair of cards
      that add up to 10. For this purpose, Aces (face value A) are considered as having value 1,
      while Jacks, Queens and Kings cannot be removed. For instance, it is possible to remove
      a 10 on its own, a pair formed by a 3 and a 7, a pair formed by an Ace and a 9, etcetera.
      Cards removed from the board are not used anymore during the game. The removal
      phase ends when no card can be removed from the board, or when the player decides not
      to continue removing cards. Notice that it is not mandatory to remove from the board
      every card that can be removed. However, since the player cannot decide the moment
      in which a new removal phase will begin, leaving removable cards on the board must be
      done carefully. Besides, note that if during a removal phase no card is removed, then the
      game is lost. When the removal phase ends, a new dealing phase starts, unless the deck
      is empty, in which case the game is over.

      The game is won if the deck is empty and only Jacks, Queens and Kings are left on the
      board.

      Camelot is really nice to play, but is frustrating to discover at the end of a game that it
      was impossible to win because of the initial arrangement of the deck. Even if the initial
      deck allows the player to win, he may fail to do so because of bad decisions or bad luck
      when placing or removing cards. Your job in this problem is to find out whether it is at
      least possible to win the game, given the order in which the cards will be dealt from the
      deck.

      Input

      Each test case is described using a single line. The line contains a single string of exactly
      52 characters representing the initial arrangement of the deck. The first card dealt from
      the deck is given by the first character of the string, and so on. Each card is represented
      by its face value, with the exception of cards with face value 10 that are represented by
      the digit “0”. You may assume that the string corresponds to a valid initial arrangement
      of the deck, i.e., it contains exactly 4 repetitions of each possible face value. The end of
      input is indicated with a line containing a single asterisk (“*”).

      Output

      For each test case, output a single line containing an uppercase “Y” if it is possible to win
      the game with the given initial arrangement of the deck, or an uppercase “N” otherwise.

      Example

      Input: 
      AAAA222233334444555566667777888899990000JJJJQQQQKKKK
      JJJJQQQQKKKKA9A9A9A928282828373737374646464655550000
      JJJJQQQQKKKKA9A9A9A928282828333377774646464655550000
      28333377774646464655550000JJJJQQQQKKKKA9A9A9A9282828
      * Output:
      N
      Y
      N
      Y

      Added by:Pablo Ariel Heiber
      Date:2010-09-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set (main)

      7409. Drawing Quadrilaterals

      Problem code: DRAWQUAD

      A quadrilateral consists of 4 points A, B, C and D in the plane, together with the
      segments AB, BC, CD and DA. Points are called vertices, while segments are called
      sides. The quadrilateral is simple if opposite sides (i.e., sides that do not share a vertex)
      do not intersect. Notice that it is possible to have a simple quadrilateral that looks like
      a triangle, with exactly 3 collinear vertices.
      Demetrio has just drawn N points on the wall of his room. He planned to draw a
      simple quadrilateral having 4 of these points as vertices, and then paint it with blue ink.
      Demetrio is going to buy the ink right now, but he has not chosen the 4 points yet. Can
      you tell him the maximum area a simple quadrilateral drawn on his wall can have? In
      this way Demetrio will be sure he will not run out of blue ink before the work is done.

      Input

      Each test case is described using several lines. The first line contains an integer N
      indicating the number of points drawn on the wall (4 ≤ N ≤ 1000). Each of the next N
      lines describes a different point of the set using two integers X and Y (−107 ≤ X, Y ≤
      107 ); these values represent the coordinates of the point in the XY plane. You may
      assume that within each test case no two points have the same location, neither are all
      collinear. The end of input is indicated with a line containing a single −1.

      Output

      For each test case, output a single line with a single decimal number representing the
      maximum area of a simple quadrilateral having as vertices 4 different points of the input
      set. Round the result to the closest rational number with one decimal place. In case of
      ties, round up. Always use exactly one digit after the decimal point, even if it means
      finishing with a zero.

      Example

      Input: 
      6
      -100 0
      100 0
      -100 50
      0 55
      0 -65
      1 1
      4
      -1 0
      10000 0
      0 0
      0 1
      -1 Output:
      12000.0
      5000.5

      Added by:Pablo Ariel Heiber
      Date:2010-09-26
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK NODEJS PYTH 3.2.3 n SED
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set (classical)

      7422. Escape from Jail Again

      Problem code: ESCJAILA

      A new International Common Prison for Criminals (ICPC) was built, and your old friend
      Harry was moved there as a prisoner. As before, the new ICPC is one of the most secure
      prisons in the world. It was designed by and old gamer and as such, the prison is not
      necessarily closed, but only an incredibly logical and fast mind can get out.
      The new ICPC can be represented as a grid of square cells. Each cell is empty, or it
      contains a wall, a door, an opening button or a closing button. Harry was accommodated
      in an empty cell, and all doors were closed. Nevertheless, Harry told you that he will
      try to escape. Each time Harry is in a cell, he can move in a single step to an adjacent
      cell (i.e., a cell that shares a side with his current location). Each time Harry steps on a
      cell that contains an opening button, all doors open, while each time he steps on a cell
      that contains a closing button, all doors close. Harry can walk around as he wants within
      the prison, although he cannot move to a cell that contains a wall, neither to a cell that
      contains a door if the doors are closed.
      To escape from the prison, Harry needs to step outside, which means placing himself in
      one of the cells on the sides and then taking one extra step out in the direction opposite
      to the prison.
      You obtained a map of the prison, and Harry deserves your advise. Tell him the minimum
      number of steps he needs to escape, or warn him that there is no way to get out.

      Input

      Each test case is described using several lines. The first line contains two integers N and
      M indicating respectively the number of rows and columns of the grid that represents
      the prison (1 ≤ N, M ≤ 100). Line i of the next N lines describes row i of the grid
      using a string of exactly M characters, where character j represents cell j of that row.
      This string only contains the following characters with the indicated meanings: “H” is
      the empty cell where Harry is at the beginning; “.” is an empty cell where Harry is not
      at the beginning; “W” is a wall; “D” is a door; “O” is an opening button; and “C” is closing
      button. You may assume that within each test case there is exactly one character “H”.
      The end of input is indicated with a line containing the number −1 twice.

      Output

      For each test case, output a single line with a single integer representing the minimum
      number of steps Harry needs to escape the prison, or the number −1 if it is impossible
      for him to do so.

      Example

      Input: 
      5 8
      WWWWWWW.
      WHDC...D
      W.WW.WCW
      W.OW..OW
      .WWWWWWW
      3 3
      ODO
      DHD
      ODO
      3 7
      WWWWWWW
      DH..OCD
      WWWWWWW
      4 1
      W
      H
      O
      W
      1 13
      HOW.DO.COW.DO
      -1 -1 Output:
      21
      -1
      8
      1
      1

      Added by:Pablo Ariel Heiber
      Date:2010-09-27
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set (classical)

      7423. File Recover Testing

      Problem code: FILRTEST

      In a recent programming contest appeared a problem named “File Recover”. In that
      problem, repeated strings of a given text were to be counted. You are preparing test
      cases for that problem, and in order to test for border cases you want to generate a text
      with many repetitions of a particular string.
      Of course, test cases cannot be arbitrarily long, so you decided to choose a length and a
      string, and then fit in a text of that length as many repetitions as possible of the string.
      For instance, if the length is 14 and the string is “abcab”, you may generate the text
      “abcabcabcabcab” whose length is 14 and where the string “abcab” appears 4 times
      (starting at positions 1, 4, 7 and 10).
      You would like to know how good your idea is before implementing. Given a length and
      a string, you must determine the maximum number of times the characters of the string
      can appear consecutively in a text of that length.

      Input

      Each test case is described using a single line. The line contains an integer K (1 ≤ K ≤
      109 ) and a non-empty string S of at most 106 lowercase letters. The end of input is
      indicated with a line containing the number −1 and an asterisk (“*”).

      Output

      For each test case, output a single line with a single integer representing the maximum
      number of times the characters of S can appear consecutively in a text of length K.

      Example

      Input: 
      14 abcab
      1000 abcde
      1000000000 z
      1 zzzzz
      -1 *
      Output:
      4
      200
      1000000000
      0

      Added by:Pablo Ariel Heiber
      Date:2010-09-27
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set (classical)

      7424. Girls and Boys

      Problem code: GIRLSNBS

      There are G girl students and B boy students in a class that is about to graduate. You
      need to arrange them in a single row for the graduation. To give a better impression of
      diversity, you want to avoid having too many girls or too many boys seating consecutively.
      You decided to arrange the students in order to minimize the gender regularity. The
      gender regularity of an arrangement is the maximum number of students of the same
      gender (all girls or all boys) that appear consecutively.
      Given G and B, calculate the minimum gender regularity among all possible arrange-
      ments.

      Input

      Each test case is described using a single line. The line contains two integers G and B
      representing the number of girls and boys in the class, respectively (0 ≤ G, B ≤ 1000).
      The end of input is indicated with a line containing the number −1 twice.

      Output

      For each test case, output a single line with a single integer representing the minimum
      gender regularity that an arrangement of G girls and B boys can have.

      Example

      Input: 
      10 10
      5 1
      0 1000
      -1 -1
      Output:
      1
      3
      1000

      Added by:Pablo Ariel Heiber
      Date:2010-09-27
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set (classical)

      7425. Hackers

      Problem code: HACKERS

      The network of your office is composed of several computers and bidirectional links. Each
      link connects a given pair of computers and has an access value. Each user in the network
      has an access privilege, and is able to use any link with access value not exceeding his
      access privilege.
      Everything was fine until suddenly you notice that a bunch of hackers are accessing the
      network. You know that if there is a link between computers A and B, with access value
      V , and a hacker with access privilege of at least V controls A, then he can control B.
      Hackers wish to control the most important computers by exploiting problems in the
      network. They are trying to increase their access privileges in order to use the links, and
      your task is to measure how safe the network is.
      Given the description of the network, the computer each hacker currently controls and
      the target computer each hacker wishes to control, you need to calculate the minimum
      access privilege each hacker needs to get in order to control his target computer.
      Hackers act independently, neither they collaborate nor interfere with each other. This
      means that each hacker may control each computer and use each link independently of
      what the other hackers do.

      Input

      Each test case is described using several lines. The first line contains three integers
      C, L and H, indicating the number of computers, links and hackers in the network,
      respectively (2 ≤ C ≤ 3000, 1 ≤ L, H ≤ 105 ); each computer is identified by an integer
      number between 1 and C. Each of the next L lines describes a different bidirectional link
      using three integers A, B and V ; the numbers A and B identify two distinct computers
      that are the endpoints of the link (1 ≤ A < B ≤ C); the number V is the access value
      of the link, that is, any hacker must have an access privilege of at least V to use the
      link (1 ≤ V ≤ 109 ). Each of the last H lines describes a different hacker using two
      distinct integers S and T that identify the computer that the hacker currently controls
      and the computer that the hacker wishes to control, respectively (1 ≤ S, T ≤ C). You
      may assume that within each test case no two links connect the same pair of computers,
      and that for any pair of computers there is at least one sequence of links that allow to
      reach one computer starting from the other. The end of input is indicated with a line
      containing the number −1 three times.

      Output

      For each test case, output a single line with H integers representing the minimum access
      privilege each hacker needs to achieve its goal. The result for each hacker must appear
      in the same order that the hackers are described in the input.

      Example

      Input: 
      5 6 4
      1 2 4
      1 3 5
      2 4 3
      2 5 1
      3 4 2
      4 5 2
      3 2
      2 4
      1 5
      3 1
      2 1 1
      1 2 1
      2 1
      2 1 3
      1 2 1000000000
      2 1
      2 1
      1 2
      -1 -1 -1
      Output:
      2 2 4 4
      1
      1000000000 1000000000 1000000000

      Added by:Pablo Ariel Heiber
      Date:2010-09-27
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set (classical)

      7426. Imperial Units

      Problem code: IMPUNITS

      As you may know, there are currently two main sets of measurement units in the world:
      the metric system and the imperial system. The imperial system receives its name from
      the British empire, which was the place of its invention and its main user until recently.
      Nowadays, Britain’s heir, the United States of America, is the only country where a
      variation of the imperial system is the official measurement system.
      For a particular magnitude, in a given measurement system there are N different units
      U1 , U2 , . . . UN (the number of units depends on both the magnitude and the system). For
      every i (1 ≤ i ≤ N − 1), a certain number of Ui is equivalent to a certain number of
      Ui+1 . In the metric system we always have that 1Ui is equivalent to 10Ui+1 . For instance,
      1 decimeter is equivalent to 10 centimeters, 1 gram is equivalent to 10 decigrams, and
      1 decaliter is equivalent to 10 liters. On the contrary, in some variations of the imperial
      system we may have other positive integers instead of 1 and 10. For instance, 32 drams
      are equivalent to 875 grains.
      Since you were born and raised using the much more sensible metric system, you need help
      learning the imperial system and its variations. You want to be able to transform directly
      from U1 to UN , that is, you need to know that a certain number of U1 is equivalent to a
      certain number of UN . To ease further calculations, you want to express the equivalence
      using only integers values, and these values must be as small as possible.

      Input

      Each test case is described using several lines. The first line contains an integer N
      indicating the number of units in the measurement system (2 ≤ N ≤ 10). Line i of the
      next N − 1 lines describes the relationship between units Ui and Ui+1 with two integers
      Ai and Bi representing that Ai Ui is equivalent to Bi Ui+1 (1 ≤ Ai < Bi ≤ 100). The end
      of input is indicated with a line containing a single −1.

      Output

      For each test case, output a single line with two positive integers C and D representing
      that CU1 is equivalent to DUN . If there are several alternatives, choose the minimum
      possible value for C.

      Example

      Input: 
      5
      1 2
      2 3
      3 4
      2 5
      2
      6 9
      -1
      Output:
      1 10
      2 3

      Added by:Pablo Ariel Heiber
      Date:2010-09-27
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set ()

      7427. Jara’s Legacy

      Problem code: JARA

      Victor Jara was a Chilean teacher, theater director and political activist. He is widely
      recognized because of his talent as poet and song writer. His most recognized work is
      probably the song “A Desalambrar” that can be translated from Spanish as “Unwire”.
      In this song Jara assures that people is the rightful owner of the lands, and so wire fences
      that delimit private properties should be cut down to allow access to everybody.
      Although Jara’s proposal is far from being fulfilled, some of his convinced listeners keep
      trying to make it happen. Since they must face several enemies, they try to make their
      job efficient by only cutting down the necessary number of fences and not more.
      Each fence can be modeled as a segment (straight line) connecting two points in the XY
      plane. These endpoints are considered to be part of the fence. A cut in a fence removes
      any contiguous part of the fence except the endpoints.
      An area is said to be free if and only if, for any pair of points not lying over a fence, there
      is a (not necessarily straight) line that connect these points without crossing any fence.
      Given the location of the fences, your job is to calculate the minimum number of fences
      that need to be cut down to make the area free, according to the above definition.

      Input

      Each test case is described using several lines. The first line contains an integer N
      indicating the number of fences in the area (1 ≤ N ≤ 105). Each of the next N lines
      describes a different fence using four integers X0 , Y0 , X1 and Y1 (−104 ≤ X0 , Y0 , X1 , Y1 ≤
      104 ). These values represent that there is a fence whose endpoints in the XY plane are
      (X0 , Y0 ) and (X1 , Y1 ). You may assume that for each fence its two endpoints are distinct.
      Besides, within each test case, the intersection of any pair of fences is either empty or
      it is an endpoint of both fences. The end of input is indicated with a line containing a
      single −1.

      Output

      For each test case, output a single line containing a single integer representing the mini-
      mum number of fences that need to be cut down to make the area free.

      Example

      Input: 
      9
      -50 0 0 0
      0 0 50 0
      -50 0 0 50
      0 50 50 0
      -50 0 0 -50
      0 -50 50 0
      0 0 0 -50
      0 -50 50 -50
      50 -50 50 0
      2
      0 1 2 3
      0 0 2 2
      -1
      Output:
      4
      0

      Added by:Pablo Ariel Heiber
      Date:2010-09-27
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:FCEyN UBA ICPC Selection 2010









      SPOJ Problem Set (classical)

      7430. Tower Of Hanoi - Revisited

      Problem code: RANJAN02

      Given 3 three pegs: leftmost peg A, middle peg B and rightmost peg C.Find the shortest sequence of moves that transfers a tower of n disks from the left peg A to the right peg C, if direct moves between A and C are disallowed. (Each move must be to or from the middle peg B.)

      Constraints:
      1. Initially the left peg A in stacked by n disks in the order of decreasing size.
      2. Only one move cand be done at a time and never moving a larger one onto a smaller.
      3. Number of moves will always be less than 2^64.
      4. 1 <= n <= 35

      Input

      Input begins with a integer t, followed by t lines. Each line has the no. of pegs n.

      Output

      For each test case, output the minimum no. of move required to transfer the n disks from peg A to peg C.

      Example

      Input:
      4
      1
      2
      5
      10

      Output:
      2
      8
      242
      59048

      Added by:`
      Date:2010-09-28
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IIITM Local Contest









      SPOJ Problem Set (classical)

      7486. Rooks

      Problem code: BIO1

      Aly being one of the smartest guys in his third grade class solved the question "How many ways to assign K cells for rooks in an N*M such that no two rooks are attacking each other" (A rook is a chess piece that can attack other pieces on the same row or the same column) but he was only able to solve it when N*M didn't exceed 10. After some days one of his classmates said he was able to solve it even if N*M reached 100. Aly kept asking how he did it and after questioning a lot of people he knew that he used a program to calculate this for him so he decided to challenge him in front of all his classmates but to do that he also needed a program that not only solve the problem when N*M reaches 100 but when N and M each reach 1,000,000 and he came for you to do that program for him but as he knows that the answer can be really big he wanted the program to output the number of ways modulo 1,000,000,007.

      Input

      The first and only line of input contains three numbers N, M and K( 1 <= N,M <= 1,000,000 , 1 <= K <= N*M ).

      Output

      The number of ways required modulo 1,000,000,007.

      Example

      Input:
      4 4 4
      
      Output:
      24

      Added by:Omar ElAzazy
      Date:2010-10-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ F# GO NODEJS PYTH 3.2.3 PYTH 3.2.3 n SED
      Resource:own problem









      SPOJ Problem Set (classical)

      7487. Flibonakki

      Problem code: FLIB

      G(n) is defined as

      G(n) = G(n-1) + f(4n-1) , for n > 0

      and G(0) = 0

      f(i) is ith Fibonacci number. Given n you need to evaluate G(n) modulo 1000000007.

      Input

      First line contains number of test cases t (t<40000). Each of the next t lines contain an integer n ( 0 <= n < 2^51).

      Output

      For each test case print G(n) modulo 1000000007.

      Example

      Input:
      2
      2
      4


      Output:

      15
      714




      Added by:Prof_Utonium_ಉಮೆಶ್
      Date:2010-10-05
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: JS
      Resource:MNNIT IOPC 2010









      SPOJ Problem Set (classical)

      7488. LCM GCD Love

      Problem code: LGLOVE

      Bob fell in love with LCM and GCD. So much that he started seeing LCMs and GCDs everywhere.

      Betty, his girl friend was jealous and she gave Bob an array A[ ] of integers, which had nothing to do with LCMs or GCDs.

      Quickly, naughty Bob evaluated a new array B[ ] containing n integers, such that B[i] is LCM(1,2,3,...,A[i]), A[i]>0. When A[i] is 0, B[i] is also 0.

      Angry Betty decided to give m queries to Bob, each being one of the following type:

      - "0 i j p", meaning add 'p' to each element in A[i..j]. -300000<= p <= 300000 , 0<=i<=j<n

      - "1 i j" , meaning print the LCM of all elements in B[i..j]. 0<=i<=j<n

      - "2 i j" , meaning print the GCD of all elements in B[i..j].0<=i<=j<n

      Input

      First line contains n(n <= 100000 ) and m( m <= 35000 ).

      Second line contains n integers in the original array A[ ] .

      Next m lines contain one of the above said queries.

      It is guaranteed that A[i] after any number of updates will satisfy 0<=A[i]<=300000.

      Output

      Output one line for each query of type 1 or 2, modulo 1000000007.

      Example

      Input:
      5 5
      4 1 3 6 2
      1 2 4
      2 1 3
      0 0 3 2
      1 1 2
      2 2 4



      Output:
      60
      1
      60
      2



      Added by:Prof_Utonium_ಉಮೆಶ್
      Date:2010-10-05
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: JS
      Resource:MNNIT IOPC 2010 , Co-author: ashish_pant









      SPOJ Problem Set (classical)

      7489. Slow Growing Bacteria

      Problem code: SBACT

       

       Given an nxn grid of cells, a bacteria colony can colonize these cells. Their growth after every second is governed by the following rules:

      1) One new bacteria is born in cell (i ,j) if and only if either one of its four neighboring cells or the cell(i,j) itself has a bacteria population more than or equal to the threshold value, k.

      2) Already living bacterias do not die.

      Given, the initial state of the nxn cell grid, you need to accurately estimate the time by when the total bacteria population reaches m.

      Input

      First line contains t, number of test cases.

      Each test case starts with n (side length of grid) , k (growth threshold) and m (final population).

      Next n lines contain an nxn grid of integers, where ith row,jth column has an integer representing the number of bacteria's present initially at cell(i,j).

      1< n <= 100 , 0< k <= 2^45 , 0< m <= 2^45,

      There are no more than n cells with initial population equal to or greater than k.

      Output

      For each test case print the number of seconds required for the total bacteria population to reach m. If m can never be reached print "Not possible" (quotes for clarity).

      Example

      Input:
      1
      3 5 15
      0 0 0
      0 3 0
      0 0 5




      Output:
      3



      Added by:Prof_Utonium_ಉಮೆಶ್
      Date:2010-10-05
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: JS
      Resource:MNNIT IOPC 2010, Co-author: jitendra_kumar









      SPOJ Problem Set (classical)

      7490. Biology

      Problem code: BIO

      It was no later than 1869 that Jules Verne succeeded to vulgarize interest in the depths of the oceans through his science-fiction novel “Twenty thousand leagues under the sea”. On board the Nautilus manoeuvred by captain Nemo, the crew visits the lost city of Atlantis and gets to know strangest kinds of sea dwellers.

      Nearly a century later, one of the deepest points on Earth, the Challenger Deep was visited by Piccard and Walsh and a Swiss flag was dibbled at 10’924 metres below sea level. The ridership of the Trieste submarine was amazed by the animal life in these depths.

       

       

      Recently a team of biologists decided to investigate these depths of the Mariana Trench and especially their So Weird Exotic Rare Citizens (SWERC). To this goal a preliminary study was performed, which showed that the species in the Mariana Trench have very local biotopes, which if projected onto the sea surface, can be described by convex polygons. All the biotopes are located at the same depth and some may overlap. The biologists now want to install racks and cameras in each biotope in order to attract and film them. As delicious as the food at the racks might be, no species would ever take the risk to transgress the borders of its habitat. As these cameras and the associated telecommunication system are extremely expensive, their number is to be minimized. Can you tell the biologists for how many cameras they need to account in their budget planning in order not to miss any species if they choose the locations in a clever way? You may consider each camera-rack couple as a mathematical point which must lie strictly inside the biotope in order to attract the related species.

       

      INPUT

      The input consists of several test-cases separated by an empty line. Each test-case starts with the number of species S (0<=S<=20) . Each of the next S lines describes one biotope. The first entry indicates the number ni  of vertices of the convex polygon. Then follow their coordinates in the order x1 y1 x2 y2 ... xni yni (|xi|,|yi|<=1000). Input terminates on a test-case with S=0, which must not be evaluated.

       

      OUTPUT

      For each test-case, output the minimum number of camera-rack couples necessary to screen all the species listed in the input.

       

      SAMPLE INPUT

      3

      3 11.00 0.00 -2.50 7.79 -2.50 -7.79

      4 4.00 -3.00 -3.00 4.00 -10.00 -3.00 -3.00 -10.00

      4 4.00 2.00 3.00 3.00 2.00 2.00 3.00 1.00

       

      10

      7 -317.00 99.00 -330.55 127.15 -361.01 134.10 -385.43 114.62 -385.43 83.38 -361.01 63.90 -330.55 70.85

      6 -99.00 93.00 -238.50 334.62 -517.50 334.62 -657.00 93.00 -517.50 -148.62 -238.50 -148.62

      4 113.00 -134.00 42.00 -63.00 -29.00 -134.00 42.00 -205.00

      3 90.00 -68.00 -261.00 134.65 -261.00 -270.65

      7 218.00 -342.00 147.22 -195.02 -11.83 -158.71 -139.38 -260.43 -139.38 -423.57 -11.83 -525.29 147.22 -488.98

      6 131.00 -286.00 38.00 -124.92 -148.00 -124.92 -241.00 -286.00 -148.00 -447.08 38.00 -447.08

      4 -170.00 -247.00 -172.00 -245.00 -174.00 -247.00 -172.00 -249.00

      4 -332.00 -102.00 -395.00 -39.00 -458.00 -102.00 -395.00 -165.00

      6 -52.00 -224.00 -196.50 26.28 -485.50 26.28 -630.00 -224.00 -485.50 -474.28 -196.50 -474.28

      5 -101.00 163.00 -210.87 314.22 -388.63 256.46 -388.63 69.54 -210.87 11.78

       

      0

       

      SAMPLE OUTPUT

      2

      5

       

          

                     Sample input 1                                         Sample input 2


      Added by:Christian Kauth
      Date:2010-10-05
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7507. Wonderful Randomized Sum

      Problem code: CF33C

      Learn, learn and learn again — Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of n numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by  - 1. The second operation is to take some suffix and multiply all numbers in it by  - 1. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations?

      Input

      The first line of the input gives the number of test cases, T. T test cases follow, each with two lines. The first line contains integer n (1 ≤ n ≤ 105) — amount of elements in the sequence. The second line contains n integers ai ( - 104 ≤ ai ≤ 104) — the sequence itself.

      Output

      For each test case, output one line containing the answer to the problem.

      Example

      Input:
      3
      3
      -1 -2 -3
      5
      -4 2 0 5 0
      5
      -1 10 -5 10 -2
      
      Output:
      6
      11
      18
      

      Added by:Ruslan Sennov
      Date:2010-10-08
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Codeforces #33









      SPOJ Problem Set (classical)

      7555. A - Crazy Rows

      Problem code: HAROWS

      Crazy Rows

      You are given an N x N matrix with 0 and 1 values. You can swap any two adjacent rows of the matrix.

      Your goal is to have all the 1 values in the matrix below or on the main diagonal. That is, for each X where 1 ≤ X ≤ N, there must be no 1 values in row X that are to the right of column X.

      Return the minimum number of row swaps you need to achieve the goal.

      Input

      The first line of input gives the number of cases, T. T test cases follow.
      The first line of each test case has one integer, N. Each of the next N lines contains N characters. Each character is either 0 or 1.

      Output

      For each test case, output

      Case #X: K

      where X is the test case number, starting from 1, and K is the minimum number of row swaps needed to have all the 1 values in the matrix below or on the main diagonal.

      You are guaranteed that there is a solution for each test case.

      Limits

      1 ≤ T ≤ 60

      1 ≤ N ≤ 8

      Input
       
      Output
       
      3
      2
      10
      11
      3
      001
      100
      010
      4
      1110
      1100
      1100
      1000

      Case #1: 0
      Case #2: 2
      Case #3: 4

       


      Added by:Alvaro Javier Medina Balboa
      Date:2010-10-15
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS









      SPOJ Problem Set (classical)

      7556. B - Stock Charts

      Problem code: HASTOCK

      B - Stock Charts

      You're in the middle of writing your newspaper's end-of-year economics summary, and you've decided that you want to show a number of charts to demonstrate how different stocks have performed over the course of the last year. You've already decided that you want to show the price of n different stocks, all at the same k points of the year.

      A simple chart of one stock's price would draw lines between the points (0, price0), (1, price1), ... , (k-1, pricek-1), where pricei is the price of the stock at the ith point in time.

      In order to save space, you have invented the concept of an overlaid chart. An overlaid chart is the combination of one or more simple charts, and shows the prices of multiple stocks (simply drawing a line for each one). In order to avoid confusion between the stocks shown in a chart, the lines in an overlaid chart may not cross or touch.

      Given a list of n stocks' prices at each of k time points, determine the minimum number of overlaid charts you need to show all of the stocks' prices.

      Input

      The first line of input will contain a single integer T, the number of test cases. After this will follow T test cases on different lines, each of the form:

      n k
      price0,0 price0,1 ... price0,k-1
      price1,0 price1,1 ... price1,k-1
      ...
      pricen-1,0 pricen-1,1 ... pricen-1,k-1

      Where pricei,j is an integer, the price of the ith stock at time j.

      Output

      For each test case, a single line containing "Case #X: Y", where X is the number of the test-case (1-indexed) and Y is the minimum number of overlaid charts needed to show the prices of all of the stocks.

      Limits

      1 ≤ T ≤ 100
      2 ≤ k ≤ 25
      0 ≤ pricei,j ≤ 1000000

      1 ≤ n ≤ 16

      Sample


      Input
       

      Output
       
      3
      3 4
      1 2 3 4
      2 3 4 6
      6 5 4 3
      3 3
      5 5 5
      4 4 6
      4 5 4
      5 2
      1 1
      2 2
      5 4
      4 4
      4 1
      Case #1: 2
      Case #2: 3
      Case #3: 2

      Added by:Alvaro Javier Medina Balboa
      Date:2010-10-15
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS









      SPOJ Problem Set (classical)

      7558. D - Alphabetomials

      Problem code: HAALPHA

      Alphabetomials

      As we all know, there is a big difference between polynomials of degree 4 and those of degree 5. The question of the non-existence of a closed formula for the roots of general degree 5 polynomials produced the famous Galois theory, which, as far as the author sees, bears no relation to our problem here.

      We consider only the multi-variable polynomials of degree up to 4, over 26 variables, represented by the set of 26 lowercase English letters. Here is one such polynomial:

      aber+aab+c

      Given a string s, we evaluate the polynomial on it. The evaluation gives p(S) as follows: Each variable is substituted with the number of appearances of that letter in S.
      For example, take the polynomial above, and let S = "abracadabra edgar". There are six a's, two b's, one c, one e, and three r's. So

      p(S) = 6 * 2 * 1 * 3 + 6 * 6 * 2 + 1 = 109.

      Given a dictionary of distinct words that consist of only lower case letters, we call a string S a d-phrase if

      S = "S1 S2 S3 ... Sd",

      where Si is any word in the dictionary, for 1 ≤ i ≤ d. i.e., S is in the form of d dictionary words separated with spaces. Given a number K ≤ 10, your task is, for each 1≤ dK, to compute the sum of p(S) over all the d-phrases. Since the answers might be big, you are asked to compute the remainder when the answer is divided by 10009.

      Input

      The first line contains the number of cases T. T test cases follow. The format of each test case is:
      A line containing an expression p for the multi-variable polynomial, as described below in this section, then a space, then follows an integer K.
      A line with an integer n, the number of words in the dictionary.
      Then n lines, each with a word, consists of only lower case letters. No word will be repeated in the same test case.

      We always write a polynomial in the form of a sum of terms; each term is a product of variables. We write at simply as t a's concatenated together. For example, a2b is written as aab. Variables in each term are always lexicographically non-decreasing.

      Output

      For each test case, output a single line in the form

      Case #X: sum1 sum2 ... sumK

      where X is the case number starting from 1, and sumi is the sum of p(S), where S ranges over all i-phrases, modulo 10009.

      Limits

      1 ≤ T ≤ 100.
      The string p consists of one or more terms joined by '+'. It will not start nor end with a '+'. There will be at most 5 terms for each p. Each term consists at least 1 and at most 4 lower case letters, sorted in non-decreasing order. No two terms in the same polynomial will be the same.
      Each word is non-empty, consists only of lower case English letters, and will not be longer than 50 characters. No word will be repeated in the same dictionary.

      Small dataset

      1 ≤ n ≤ 20
      1 ≤ K ≤ 5

      Large dataset

      1 ≤ n ≤ 100
      1 ≤ K ≤ 10

      Sample


      Input
       

      Output
       
      2
      ehw+hwww 5
      6
      where
      when
      what
      whether
      who
      whose
      a+e+i+o+u 3
      4
      apple
      orange
      watermelon
      banana

      Case #1: 15 1032 7522 6864 253
      Case #2: 12 96 576

      Added by:Alvaro Javier Medina Balboa
      Date:2010-10-15
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS









      SPOJ Problem Set (classical)

      7559. E - Football Team

      Problem code: HATEAM

      Football Team

      A football team will be standing in rows to have a photograph taken. The location of each player will be given by two integers x and y, where y gives the number of the row, and x gives the distance of the player from the left edge of the row. The x values will be all different.

      In order to make the photo more interesting, you're going to make sure players who are near each other have shirts of different colors. To do this, you set the following rule:
      For each player P:

      • The closest player to the right of P in the same row, if there is such a player, must have a different shirt color.
      • The closest player to the right of P in the previous row, if there is such a player, must have a different shirt color.
      • The closest player to the right of P in the next row, if there is such a player, must have a different shirt color.

      More formally, if there is a player at (x1,y1) and (x2,y2), where x1<x2, then those two players must have different shirt colors if:

      • y1 - 1 ≤ y2 ≤ y1 + 1, and
      • there is no x3 such that there is a player at (x3, y2) and x1 < x3 < x2.

      Find the minimum number of distinct shirt colors required so that this is possible.

      Input

      The first line of input contains a single integer T, the number of test cases. Each test case starts with a line that contains an integer N, the number of players, followed by N lines of the form

      x y

      each specifying the position of one player.

      Output

      For each test case, output

      Case #X: c

      where X is the test case number, starting from 1, and c is the minimum number of colors required.

      Limits

      1 ≤ T ≤ 100
      1 ≤ x ≤ 1000
      The values of x will all be different.

      Small dataset

      1 ≤ y ≤ 15
      1 ≤ N ≤ 100

      Large dataset

      1 ≤ y ≤ 30
      1 ≤ N ≤ 1000

      Sample


      Input
       

      Output
       
      3
      3
      10 10
      8 15
      12 7
      5
      1 1
      2 1
      3 1
      4 1
      5 1
      3
      1 1
      2 2
      3 1
      Case #1: 1
      Case #2: 2
      Case #3: 3

      Added by:Alvaro Javier Medina Balboa
      Date:2010-10-15
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS









      SPOJ Problem Set (classical)

      7560. F - Interesting Ranges

      Problem code: HARANGES

      Interesting Ranges

      A positive integer is a palindrome if its decimal representation (without leading zeros) is a palindromic string (a string that reads the same forwards and backwards). For example, the numbers 5, 77, 363, 4884, 11111, 12121 and 349943 are palindromes.

      A range of integers is interesting if it contains an even number of palindromes. The range [L, R], with L ≤ R, is defined as the sequence of integers from L to R (inclusive): (L, L+1, L+2, ..., R-1, R). L and R are the range's first and last numbers.

      The range [L1,R1] is a subrange of [L,R] if L ≤ L1 ≤ R1 ≤ R. Your job is to determine how many interesting subranges of [L,R] there are.

      Input

      The first line of input gives the number of test cases, T. T test cases follow. Each test case is a single line containing two positive integers, L and R (in that order), separated by a space.

      Output

      For each test case, output one line. That line should contain "Case #x: y", where x is the case number starting with 1, and y is the number of interesting subranges of [L,R], modulo 1000000007.

      Limits

      1 ≤ T ≤ 120

      Small dataset

      1 ≤ LR ≤ 1013

      Large dataset

      1 ≤ LR ≤ 10100

      Sample


      Input
       

      Output
       
      3
      1 2
      1 7
      12 110

      Case #1: 1
      Case #2: 12
      Case #3: 2466

      Added by:Alvaro Javier Medina Balboa
      Date:2010-10-15
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS









      SPOJ Problem Set (classical)

      7561. Lexicographic position

      Problem code: LEXIPOS

      Let us consider the set of integer numbers between 1 and N inclusive. Order them lexicographically (i. e. like in the vocabulary), for example, for N = 11 the order would be: 1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9.

      Denote the position of the number K in this ordering as QN,K. For example, Q11,2 = 4.

      Given N and K, compute QN,K.

      Input

      The first line contains a number T, which is the number of test cases. T lines follow, each contains 2 integers N and K separated by a single space.

      Output

      For each test case, print QN,K on a single line.

      Constraint

      1 ≤ T ≤ 100

      1 ≤ K ≤ N ≤ 10100

      Example

      Input: 
      7
      1 1
      11 2
      215 211
      215 215
      215 26
      215 99
      1000000000 999999999

      Output:
      1
      4
      126
      130
      135
      215
      1000000000

      Added by:Race with time
      Date:2010-10-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Based on a problem from ACM NEERC 2002 - 2003









      SPOJ Problem Set (classical)

      7562. Help in organizing

      Problem code: HLP

      During, the meeting held to organize a competition in Memory strengthOne of

      the attendant suggested an idea that was accepted by almost all the organizers.


      First, The competition is held such that all competitors oppose each other and

      the winner is the one who got the highest score.

       

      At the begin of the competition a sequence of pictures are shown to all the

      competitors where their task, during every match, is to arrange the pictures

      in front of him/her as quickly as possible in the same order he had seen in

      the show.



      Let's return to our suggestion, One of the Organizers 
      suggested to put the

      pictures in order where each two pictures where shown consecutively in the

      show aren't beside each other. Also he suggested that, for each one, along

      the competition, isn't allowed to try to put in order the same arrangement of

      the pictures he had tried to do that with before.


      In order not to help any competitor to remember easily.


      Then, he needed to calculate the
      minimum number of pictures 
      that can be

      in the sequence that allow organizing the competition.

      Hint:

            All competitors will face each other one through out the competition.


      ----------------------------------------------

       
      Task

       

      write a program th reads the number of the competitors 
      and calculate the

      minimum number of elements needed in the sequence, that can be arranged,

      where no two pictures that where originally next to each other are next to

      each other, M times.


      M is calculated, such that no one is allowed to try to arrange the same

       sequence more than once, along the competition.



      Input

      N (number of the competitors), where 1≤ 10309 


      Output

       
      The minimum number of elements needed in the sequence that
       will be

      shown to all the competitors.


      INPUT:
      5


      OUTPUT:
      5


      Explanation:

         M (minimum number of available arrangements needed) will be 5, in this case,

      also a sequence of length 5 can allow 14 unique arrangements.


      + For 5 competitors there are 10 matches (4.0*5.0/2.0)

      Notice that each arrangement can be used for more than one match, but one time for each player at maximum.


      Hint:
      4 can not b the right answer, as with a sequence of length 4
      the number of

      available arrangements is 2 only - less than needed -.

      INPUT: 

      89


      OUTPUT:

      6


      • Number of test-cases is 52.



      Added by:Rofael Emil
      Date:2010-10-15
      Time limit:0.100s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7563. Hi6

      Problem code: HISIX

       

      "I read somewhere that everybody on this planet is separated by only six other people. Six
      degrees of separation between us and everyone else on this planet. The President of the United
      States, a gondolier in Venice, just ll in the names. I nd it A) extremely comforting that
      we're so close, and B) like Chinese water torture that we're so close because you have to nd
      the right six people to make the right connection... I am bound to everyone on this planet by
      a trail of six people." { Ouisa Kitteridge, "Six Degrees of Separation"
      Is widely know that one is separated from everyone in the world in no more than 6 degrees of
      separation. A degree of separation is de ned by the minimum numbers of connections you need
      to make to contact someone else. For instance, if you know personally another person, then
      you are separated by one degree. If you know somebody through some friend but not directly
      (a friend of a friend), then you are separated by two degrees, and so on.
      Nevertheless, young Kevin Smith is not convinced about this theory and wants to probe it false.
      To achieve this, he has hacked the Hi6! social network and requested you to help him knock
      down the theory of six degrees of separation

      "I read somewhere that everybody on this planet is separated by only six other people. Six degrees of separation between us and everyone else on this planet. The President of the United States, a gondolier in Venice, just ll in the names. I find it A) extremely comforting that we're so close, and B) like Chinese water torture that we're so close because you have to find the right six people to make the right connection... I am bound to everyone on this planet by a trail of six people." - Ouisa Kitteridge, "Six Degrees of Separation"

      Is widely know that one is separated from everyone in the world in no more than 6 degrees of separation. A degree of separation is defi ned by the minimum numbers of connections you need to make to contact someone else. For instance, if you know personally another person, then you are separated by one degree. If you know somebody through some friend but not directly (a friend of a friend), then you are separated by two degrees, and so on.

      Nevertheless, young Kevin Smith is not convinced about this theory and wants to probe it false. To achieve this, he has hacked the Hi6! social network and requested you to help him knock down the theory of six degrees of separation.

       

      Input

       

      The first line contains an integer T, which specifi es the number of test cases. Then, T test case descriptions will follow. Each test case will start with a line with one positive integer, N meaning the number of connections. The next N lines will contain the following pattern:

      <name_1> <name_2> <D>

      meaning that person "<name_1>" is connected with the person "<name_2>" by making D connections and viceversa. Note that both persons can know each other by a lower degree of separation using other connections.

       

      Output

       

      For each input case you must print the string "Case #i: ", where i is the test case number, starting from 1, following by the maximum degree of separation between the specifi ed people. If there is someone that cannot connect to another person, print "INFINITE" instead.

       

      Constraints

      • All names will be non-empty strings composed only by lowercase characters.
      • All names will have between 1 and 10 characters, inclusive.
      • "<name_1>" will be diff erent than "<name_2>" for all connections.
      • There will be no pair of connections between the same pair of persons.
      • D will be an integer between 1 and 1000, inclusive, for all connections.
      • T will be between 1 and 100, inclusive.
      • N will be between 1 and 10^5, inclusive.

       

       

      Example

      Input:
      3
      2
      john judy 1
      mary peter 1
      3
      john judy 7
      john peter 2
      judy peter 2
      7
      john judy 3
      katie peter 4
      john peter 2
      judy mary 1
      peter mary 2
      john katie 1
      katie mary 1


      Output:
      Case #1: INFINITE
      Case #2: 4
      Case #3: 3

      Added by:Daniel Ampuero
      Date:2010-10-15
      Time limit:7s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      7565. Another Sorting Algorithm

      Problem code: IITD1

      Dexter keeps doing strange things with numbers.
      Yesterday he found a new algorithm to sort a sequence of numbers & he implemented the following pseudocode to sort the list Seq of N numbers (0-based) in ascending order :

      Seq = Given sequence of N numbers

      swap(i,j)
      {
          temp = Seq[i]
          Seq[i] =Seq[j]
          Seq[j] = temp
      }


      reverse(i,j)
      {
          Do for k from i to (i+j-1)/2
              swap(k,i+j-k)
      }

      sort()
      {
          Do for i from 0 to N-1
              Do for j from i+1 to N-1    
                  if(Seq[i]>Seq[j]) then reverse(i,j)
          
      }

      However unknown to Dexter, his sister Dee Dee added another loop inside the outer loop so that the changed sort function now looks like :

      sort()
      {
          Do for i from 0 to N-1    
              Do for j from i+1 to N-1    
                  if(Seq[i]> Seq[j]) then reverse(i,j)
              
              Do for j from N-2 to i+2    
                  reverse(i+1,j)

      }

      When today Dexter tested his program he was frustrated to find that the program was sorting the numbers but it was taking more time than it should(DeeDee's plans always work !).
      You have been asked to help esitmate the time taken. Given the sequence of numbers that Dexter wants to sort,  your job is to find the number of times the swap function has been called.

      Input Format :

      First line contains the number N, the size of the sequence to be sorted. N lines follow, each containing a single integer (the (i)th of these lines contains the value Seq[i])

      Output Format:

      Output a single number representing the number of times the swap function has been called.


      Sample Input File:

      5
      1
      2
      3
      4
      5


      Sample Output File:

      4

      Constraints:
      1<=N<=4000
      0<=Seq[i]<=1,000,000,000

       


      Added by:Nikhil Garg
      Date:2010-10-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Written by Rudradev Basak for IIT Delhi ACM ICPC provinical contest 2010









      SPOJ Problem Set (classical)

      7566. Expected Cycle Sums

      Problem code: IITD5

      We are given a sequence S of N distinct integers. Denote by S[i] as ith element of S.
      Hardik picks up a random permutation of S , breaks it into product of disjoint cycles & looks at cycle containing S[i].He notes down the sum of all element of this cycle. Call the expected value of this sum as cycleSum[i]. Your task is to find the minimum value amongst all cycleSums.

      Assume all permutations of these N numbers are equally likely.


      Input Format :

      First line contains an integer T which denotes the number of test cases. Then follow description of T test scenarios. Each test scenario takes 2 lines. First line contains a single integer N, the size of S. Then follows second line containing N elements of S.


      Output Format :


      Print answer for each test case , rounded to exactly one decimal place , in one line each.

      Sample Input :
      2
      1
      1
      2
      1 2


      Sample Output:
      1.0
      2.0


      Note: Notion of cycles for any sequence is defined by using index in the sequence (1-N).

      Explaination for sample output :

      In first case only possible permutation is (1)  So answer is trivially 1.0

      In second case possible permutations are (1)(2) & (12).  As both of these are equally likely, cycleSum[1] = 1/2 * 1 + 1/2 * (1+2) = 2.0

      And cycleSum[2] = 1/2 * 2 + 1/2 * (1+2) = 2.5.  Smaller of these is 2.0 , hence the answer.

      Constraints :

      1<=T<=500
      1<=N<=5000
      All elements of S are distinct integers in range 0 to 10^5


      Added by:Nikhil Garg
      Date:2010-10-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:own problem, used for IIT Delhi ACM ICPC provincial contest 2010









      SPOJ Problem Set (classical)

      7567. Divisor Summation Powered

      Problem code: IITD4

      Define F(n,k) = Sum of kth powers of all divisors of n
      So for example F(6,2) = 1^2 + 2^2 + 3^2 + 6^2 = 50

      Define further G(a,b,k) as : Sum of F(j,k) where j varies from a to b both inclusive

      Your task is to find G(a,b,k) given a,b & k.
      As values of G can get very large , you only need to output the value of G(a,b,k) modulo 10^9+7.

      Input Format:


      First line of input file contains a single integer T - denoting the number of test cases.
      The follow description of T test cases. Each test case occupies exactly one line which contains three space separated integers a,b & k.

      Output Format:


      Output your result for each test case in a new line.


      Sample Input File:

      2
      2 2 1
      1 3 2

      Sample Output File:

      3
      16


      Description of sample output:

      In case 1, we are to find sum of divisors of 2. which is nothing but 1+2=3.
      In case 2, we are to find sum of squares of divisors of 1 2 & 3. So for 1 sum is = 1. For 2 sum is = 1^2+ 2^2= 5. For 3 sum is = 1^2 + 3^2=10.
      So ans is 16.

      Constraints :


      1<=a<=b<=10^5
      1<=k<=10^5
      Number of test cases <=20


      Added by:Nikhil Garg
      Date:2010-10-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:own problem, used for IIT Delhi ACM ICPC provincial contest 2010









      SPOJ Problem Set (classical)

      7579. Power Calculus

      Problem code: YOKOF

      Starting with x and repeatedly multiplying by x, we can compute x31 with thirty multiplications:

      x2 = x * x,     x3 = x2 * x,     x4 = x3 * x,     ...  ,     x31 = x30 * x.

      The operation of squaring can appreciably shorten the sequence of multiplications. The following is a way to compute x31 with eight multiplications:

      x2 = x * x,     x3 = x2 * x,     x6 = x3 * x3,     x7 = x6 * x,     x14 = x7 * x7,
      x15 = x14 * x,     x30 = x15 * x15,     x31 = x30 * x.

      This is not the shortest sequence of multiplications to compute x31. There are many ways with only seven multiplications. The following is one of them:

      x2 = x * x,     x4 = x2 * x2,     x8 = x4 * x4,     x10 = x8 * x2,
      x20 = x10 * x10,     x30 = x20 * x10,     x31 = x30 * x.

      There however is no way to compute x31 with fewer multiplications. Thus this is one of the most efficient ways to compute x31 only by multiplications.

      If division is also available, we can find a shorter sequence of operations. It is possible to compute x31 with six operations (five multiplications and one division):

      x2 = x * x,     x4 = x2 * x2,     x8 = x4 * x4,     x16 = x8 * x8,     x32 = x16 * x16,     x31 = x32 ÷ x.

      This is one of the most efficient ways to compute x31 if a division is as fast as a multiplication.

      Your mission is to write a program to find the least number of operations to compute xn by multiplication and division starting with x for the given positive integer n. Products and quotients appearing in the sequence of operations should be x to a positive integer's power. In other words, x-3, for example, should never appear.

      Input

      The input is a sequence of one or more lines each containing a single integer n. n is positive and less than or equal to 1000. The end of the input is indicated by a zero.

      Output

      Your program should print the least total number of multiplications and divisions required to compute xn starting with x for the integer n. The numbers should be written each in a separate line without any superfluous characters such as leading or trailing spaces.

      Example

      Input: 
      1
      31
      70
      91
      473
      512
      811
      953
      0
      
      Output: 
      0
      6
      8
      9
      11
      9
      13
      12
      

       



      Added by:Race with time
      Date:2010-10-17
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:ACM Yokohama 2006









      SPOJ Problem Set (classical)

      7581. The Best Name for Your Baby

      Problem code: YOKOH

      In the year 29XX, the government of a small country somewhere on the earth introduced a law restricting first names of the people only to traditional names in their culture, in order to preserve their cultural uniqueness. The linguists of the country specifies a set of rules once every year, and only names conforming to the rules are allowed in that year. In addition, the law also requires each person to use a name of a specific length calculated from one's birth date because otherwise too many people would use the same very popular names. Since the legislation of that law, the common task of the parents of new babies is to find the name that comes first in the alphabetical order among the legitimate names of the given length because names earlier in the alphabetical order have various benefits in their culture.

      Legitimate names are the strings consisting of only lowercase letters that can be obtained by repeatedly applying the rule set to the initial string ``S'', a string consisting only of a single uppercase S.

      Applying the rule set to a string is to choose one of the rules and apply it to the string. Each of the rules has the form A $ \rightarrow$ $ \alpha$, where A is an uppercase letter and $ \alpha$ is a string of lowercase and/or uppercase letters. Applying such a rule to a string is to replace an occurrence of the letter A in the string to the string $ \alpha$. That is, when the string has the form `` $ \beta$A$ \gamma$'', where $ \beta$ and $ \gamma$ are arbitrary (possibly empty) strings of letters, applying the rule rewrites it into the string `` $ \beta$$ \alpha$$ \gamma$''. If there are two or more occurrences of A in the original string, an arbitrary one of them can be chosen for the replacement.

      Below is an example set of rules.

      S $ \rightarrow$ aAB
      (1)
      A $ \rightarrow$

      (2)
      A $ \rightarrow$ Aa
      (3)
      B $ \rightarrow$ AbbA
      (4)

      Applying the rule (1) to ``S'', ``aAB'' is obtained. Applying (2) to it results in ``aB'', as A is replaced by an empty string. Then, the rule (4) can be used to make it ``aAbbA''. Applying (3) to the first occurrence of A makes it ``aAabbA''. Applying the rule (2) to the A at the end results in ``aAabb''. Finally, applying the rule (2) again to the remaining A results in ``aabb''. As no uppercase letter remains in this string, ``aabb'' is a legitimate name.

      We denote such a rewriting process as follows.

      S  $ \;\stackrel{{\mbox{\tiny (1)}}}{{\longrightarrow}}\;$  aAB  $ \;\stackrel{{\mbox{\tiny (2)}}}{{\longrightarrow}}\;$  aB  $ \;\stackrel{{\mbox{\tiny (4)}}}{{\longrightarrow}}\;$  aAbbA  $ \;\stackrel{{\mbox{\tiny (3)}}}{{\longrightarrow}}\;$  aAabbA  $ \;\stackrel{{\mbox{\tiny (2)}}}{{\longrightarrow}}\;$  aAabb  $ \;\stackrel{{\mbox{\tiny (2)}}}{{\longrightarrow}}\;$  aabb

      Linguists of the country may sometimes define a ridiculous rule set such as follows.

      S $ \rightarrow$ sA
      (1)
      A $ \rightarrow$ aS
      (2)
      B $ \rightarrow$ b
      (3)

      The only possible rewriting sequence with this rule set is:

      S  $ \;\stackrel{{\mbox{\tiny (1)}}}{{\longrightarrow}}\;$  sA  $ \;\stackrel{{\mbox{\tiny (2)}}}{{\longrightarrow}}\;$  saS  $ \;\stackrel{{\mbox{\tiny (1)}}}{{\longrightarrow}}\;$  sasA  $ \;\stackrel{{\mbox{\tiny (2)}}}{{\longrightarrow}}\;$   ...

      which will never terminate. No legitimate names exist in this case. Also, the rule (3) can never be used, as its left hand side, B, does not appear anywhere else.

      It may happen that no rules are supplied for some uppercase letters appearing in the rewriting steps. In its extreme case, even S might have no rules for it in the set, in which case there are no legitimate names, of course. Poor nameless babies, sigh!

      Now your job is to write a program that finds the name earliest in the alphabetical order among the legitimate names of the given length conforming to the given set of rules.

      Input

      The input is a sequence of datasets, followed by a line containing two zeros separated by a space representing the end of the input. Each dataset starts with a line including two integers n and l separated by a space, where n (0 <= n <= 50) is the number of rules and l (0 <= l <= 20) is the required length of the name. After that line, n lines each representing a rule follow. Each of these lines starts with one of uppercase letters, A to Z, followed by the character ``='' (instead of `` $ \rightarrow$'') and then followed by the right hand side of the rule which is a string of letters A to Z and a to z. The length of the string does not exceed 10 and may be zero. There appears no space in the lines representing the rules.

      Output

      The output consists of the lines showing the answer to each dataset in the same order as the input. Each line is a string of lowercase letters, a to z, which is the first legitimate name conforming to the rules and the length given in the corresponding input dataset. When the given set of rules has no conforming string of the given length, the corresponding line in the output should show a single hyphen, ``-''. No other characters should be included in the output.

      Example

      Input: 
      4 3
      A=a
      A=
      S=ASb
      S=Ab
      2 5
      S=aSb
      S=
      1 5
      S=S
      1 0
      S=S
      1 0
      A=
      2 0
      A=
      S=AA
      4 5
      A=aB
      A=b
      B=SA
      S=A
      4 20
      S=AAAAAAAAAA
      A=aA
      A=bA
      A=
      0 0
      
      Output: 
      abb
      -
      -
      -
      -
      
      aabbb
      aaaaaaaaaaaaaaaaaaaa
      

      Added by:Race with time
      Date:2010-10-17
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:ACM Yokohama 2006









      SPOJ Problem Set (classical)

      7583. Cubic Eight-Puzzle

      Problem code: YOKOC

      Let's play a puzzle using eight cubes placed on a 3 x 3 board leaving one empty square.

      Faces of cubes are painted with three colors. As a puzzle step, you can roll one of the cubes to the adjacent empty square. Your goal is to make the specified color pattern visible from above by a number of such steps.

      The rules of this puzzle are as follows.

       

      1. Coloring of Cubes: All the cubes are colored in the same way as shown in Figure 3. The opposite faces have the same color.

         

        \epsfbox{p3618a.eps}

         

        Figure 3: Coloring of a cube

         

      2. Initial Board State: Eight cubes are placed on the 3 x 3 board leaving one empty square. All the cubes have the same orientation as shown in Figure 4. As shown in the figure, squares on the board are given x and y coordinates, (1, 1), (1, 2), ..., and (3, 3). The position of the initially empty square may vary.

         

        \epsfbox{p3618b.eps}

         

        Figure 4: Initial board state

         

      3. Rolling Cubes: At each step, we can choose one of the cubes adjacent to the empty square and roll it into the empty square, leaving the original position empty. Figure 5 shows an example.

         

        \epsfbox{p3618c.eps}

         

        Figure 5: Rolling a cube

         

      4. Goal: The goal of this puzzle is to arrange the cubes so that their top faces form the specified color pattern by a number of cube rolling steps described above.

      Your task is to write a program that finds the minimum number of steps required to make the specified color pattern from the given initial state.

       

      Input

      The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. The number of datasets is less than 16. Each dataset is formatted as follows.

      x y  
      F11 F21 F31
      F12 F22 F32
      F13 F23 F33

      The first line contains two integers x and y separated by a space, indicating the position (x, y) of the initially empty square. The values of x and y are 1, 2, or 3.

      The following three lines specify the color pattern to make. Each line contains three characters F1j, F2j, and F3j, separated by a space. Character Fij indicates the top color of the cube, if any, at position (i, j) as follows:

      B: Blue,
      W: White,
      R: Red,
      E: the square is Empty.

      There is exactly one `E' character in each dataset.

      Output

      For each dataset, output the minimum number of steps to achieve the goal, when the goal can be reached within 30 steps. Otherwise, output ``-1'' for the dataset.

      Example

      Input: 
      1 2 
      W W W 
      E W W 
      W W W 
      2 1 
      R B W 
      R W W 
      E W W 
      3 3 
      W B W 
      B R E 
      R B R 
      3 3 
      B W R 
      B W R 
      B E R 
      2 1 
      B B B 
      B R B 
      B R E 
      1 1 
      R R R 
      W W W 
      R R E 
      2 1 
      R R R 
      B W B 
      R R E 
      3 2 
      R R R 
      W E W 
      R R R
      0 0
      
      Output: 
      0 
      3 
      13 
      23 
      29 
      30 
      -1 
      -1
      

      Added by:Race with time
      Date:2010-10-17
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:ACM Yokohama 2006









      SPOJ Problem Set (classical)

      7586. Number of Palindromes

      Problem code: NUMOFPAL

      Each palindrome can be always created from the other palindromes, if a single character is also a palindrome. For example, the string "malayalam" can be created by some ways:


      * malayalam = m + ala + y + ala + m
      * malayalam = m + a + l + aya + l + a + m

      We want to take the value of function NumPal(s) which is the number of different palindromes that can be created using the string S by the above method. If the same palindrome occurs more than once then all of them should be counted separately.


      Input

      The string S.


      Output

      The value of function NumPal(s).


      Limitations

      0 < |s| <= 1000


      Example


      Input:

      malayalam

      Output:

      15


      Added by:The quick brown fox jumps over the lazy dog
      Date:2010-10-18
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Udit Agarwal









      SPOJ Problem Set ()

      7588. Wise And Miser

      Problem code: MISERMAN

      Jack is a wise and miser man. Always tries to save his money.

      One day, he wants to go from city A to city B. Between A and B, there are N number of cities(including B and excluding A) and in each city there are M buses numbered from 1 to M. And the fare of each bus is different. Means for all N*M busses, fare (K) may be different or same. Now Jack has to go from city A to city B following these conditions:

      1. At every city, he has to change the bus.

      2. And he can switch to only those buses which have number either equal or 1 less or 1 greater to the previous.

      You are to help Jack to go from A to B by spending the minimum amount of money.

      N,M,K<=100.

      Input

      Line 1:    N M
      Line 2:    NxM Grid

      Each row lists the fares the M busses to go form the current city to the next city.

      Output

      Single Line containing the minimum amount of fare that Jack has to give.

      Example

      Input:
      5 5
      1 3 1 2 6
      10 2 5 4 15
      10 9 6 7 1
      2 7 1 5 3
      8 2 6 1 9

      Output:
      10

      Explanation:
      1->4->1->3->1 = 10

       


      Added by:The quick brown fox jumps over the lazy dog
      Date:2010-10-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Udit Agarwal









      SPOJ Problem Set (classical)

      7589. Cave Crisis

      Problem code: PC8C

      R2D2 was exploring a tunnel when a cave-in suddenly occurred. Oh no, is he trapped?

       

      \epsfbox{p4434.eps}

       

      Figure1: Overhead view of the cave crisis from the third example test case.

      From an overhead view, we can see all the obstacles (debris) on a two-dimensional Cartesian plane. The tunnel is w cm wide, bounded by the lines y = w/2 and y = - w/2. R2D2 starts at (0, 0), and has a perfectly circular footprint of radius r. The exit of the tunnel lies to the right of the line x = 1000. Between R2D2 and the exit lie a number of polygonal obstacles.

      Is it possible for R2D2 to navigate between the obstacles and make it to the exit?

      Input

      The input file will contain multiple test cases. Each test case begins with a single line containing an even integer w ( 2$ \le$w$ \le$1000), the width of the tunnel, and an integer N ( 0$ \le$N$ \le$100), the number of obstacles. The next N lines each contain the description of a single obstacle. The i-th obstacle is a simple polygon, specified on a single line containing an integer ni ( 3$ \le$ni$ \le$10), the number of vertices, followed by ni pairs of integers, xij and yij ( 0$ \le$xij$ \le$1000 and - w/2$ \le$yij$ \le$w/2 for j = 1,..., ni), specifying the coordinates of the vertices in counterclockwise order. Note that obstacles in the input may touch or even overlap. However, you are guaranteed that R2D2's initial location will not touch or overlap any obstacle. The vertices of each polygon are unique, no two nonconsecutive edges of the polygon intersect (even at their endpoints), and each polygon is guaranteed to have nonzero area.

      The end-of-input is denoted by an invalid test case with w = N = 0 and should not be processed.

      Output

      For each input test case, you must determine the maximum radius r > 0 that R2D2 could have and still be able to plan a path from his starting location (0, 0) to the tunnel exit without overlapping with any of the obstacles. You should print either this maximum radius r (rounded to two decimal places) or the message "impossible" if no such radius exists.

      Example

      Input: 
      6 2
      4 2 -1 4 -1 4 1 2 1
      3 3 0 6 -1 6 1
      8 2
      3 1 -1 4 -1 4 4
      3 3 -4 6 1 3 1
      10 7
      4 0 5 4 2 5 3 4 5
      3 4 -5 9 -5 9 0
      4 8 -5 11 -5 11 -2 8 -2
      3 8 3 16 1 11 5
      4 21 -5 23 -3 20 -2 15 -4
      3 22 3 26 -1 28 0
      3 24 0 29 4 25 3
      0 0
      Output: 
      1.00
      impossible
      1.33
      

      Added by:Race with time
      Date:2010-10-19
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:ACM Pacific Northwest 2008









      SPOJ Problem Set (classical)

      7599. Optimal Strategy for the ICPC

      Problem code: PC8F

      The following is taken from the official rules for the International Collegiate Programming Contest, as reported at http://www.acmicpc-pacnw.org/rules.htm

       

      The total time is the sum of the time consumed for each problem solved. The time consumed for a solved problem is the time elapsed from the beginning of the contest to the submittal of the first accepted run plus 20 penalty minutes for every previously rejected run for that problem. There is no time consumed for a problem that is not solved.

      Quite simply, one element of the optimal strategy is not to have any erroneous submissions, so the androids do not have to worry about the penalty minutes. All that remains is to determine the order in which they should submit problems.

      Let's assume perfect knowledge -- hey, these androids are good -- so that they can make a very good estimate of the development time required for each of the problems. The task is to determine the order in which the problems should be submitted. The androids realize that their best approach is for each to think independently about different problems rather than having all three work on a single problem. Furthermore, each android types infinitely fast, and does not use the computer terminal while thinking. Hence, up to three problems can be simultaneously in progress at any given time, and it is actually possible for all three bots to submit a problem within the same minute. For the same reason, the number of problems posed is larger than those posed in the contest for biological entities. Being innately fussy, if there are multiple ways to submit the problems and obtain the same score, they will submit the problem order that comes lexicographically first.

      Determine the algorithm to solve the most problems and to obtain the best possible score for those problems. Then implement it.

      Input

      The first line of input to your program is a single integer n ( 0 < n < 100), giving the number of data sets -- one for each set of problems. Following that are exactly n lines, giving information about each data set. The first number is the number of problems in that dataset as an integer k ( 5 <= k <= 15). On the same line, separated by single spaces, are k integers, all between 1 and 300 inclusive, giving the estimated time required to solve each problem. The problems themselves are labeled by alphabetic characters starting with A. Note that there are exactly 300 minutes in the contest.

      Output

      Each data set generates one line of output, giving the data set number, the sequence the problems are submitted, the total number solved, and the final penalty score. See the sample output for format -- all non-blank entries are separated by single blank spaces.

      Example

      Input:  
      4
      9 25 50 100 150 100 100 150 225 300
      10 60 120 99 129 15 150 225 135 50 123
      12 6 60 99 45 135 66 231 63 96 39 50 123
      15 75 75 75 75 75 75 75 75 75 75 75 75 75 75 75

      Output: 
      Data set 1: A B C D E F G H 8 1450
      Data set 2: E I A J C B F H D 9 1473
      Data set 3: A J D B K F H I C E L 11 1452
      Data set 4: A B C D E F G H I J K L 12 2250


      Added by:Race with time
      Date:2010-10-19
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:ACM Pacific Northwest 2008









      SPOJ Problem Set ()

      7600. Milk Trading

      Problem code: MLK

      Hareedi and Hanadt live in a village with N houses built next to each other along one

      straight roadway with equal distances between adjacent houses. Some people own cows

      and sell the milk their cows produce, while others do not own cows and may need to buy

      milk.

      Every morning, Hareedi and Hanadi transport milk around the village such that everyone

      buys or sells the exact number of bottles they want. Transporting one bottle of milk from

      one house to an adjacent house results in one unit of work. Fortunately, the number of

      milk bottles needed by people is always equal to the number of milk bottles sold by

      cow owners.

       

      Task

      write a program that is given the number of milk bottles that people at each house needs

      to buy or sell, represented as an integer, finds the minimum work necessary to transport

      the bottles from sellers to buyers.

       

      Constraints

      2 ≤ N ≤ 1,000,000     The number of houses.

      -1000 Bi 1000      Integer representing the number of bottles to be bought from or

                                    sold to people at the house at position i.

      Input

      • Line 1 contains the integer N, the number of houses.
      • Each of the next N lines contains an integer Bi. If Bi > 0 then people in house i are cow

        owners and want to sell Bi bottles of milk, If Bi ≤ 0 then people at house i are not cow owners

           and want to buy Bi bottles of milk.

       Output

      • A single line containing a single integer, the minimum work units necessary to

        transport the bottle of milk.

      Example

      Input:
      5
      5
      -4
      1
      -3
      1
      Output:
      9
      There are 5 houses as shown in the table.

      Position

      1

      2

      3

      4

      5

      Bottles

      5

      -4

      1

      -3

      1

      4 bottles are transported from house 1 to house 2, 1 bottle from house 1 to
      house 4, 1 bottle from house 3 to house 4, 1 bottle from house 5 to house 4.
      
      
      • Number of test-cases is 28.
      
      
      
      
      
      Added by:Rofael Emil
      Date:2010-10-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Egyptian Olympiad in Informatics ( EOI ) 2009, August 14 - 21, Cairo









      SPOJ Problem Set (classical)

      7602. New Game with a Chess Piece

      Problem code: CF36D

      Petya and Vasya are inventing a new game that requires a rectangular board and one chess piece. At the beginning of the game the piece stands in the upper-left corner of the board. Two players move the piece in turns. Each turn the chess piece can be moved either one square to the right or one square down or jump k squares diagonally down and to the right. The player who can’t move the piece loses.

      The guys haven’t yet thought what to call the game or the best size of the board for it. Your task is to write a program that can determine the outcome of the game depending on the board size.

      Input

      The first input line contains one integer 1  ≤  t  ≤  20202. Each of the following t  lines contains three numbers: k and n, m - the jump length and the board’s length and width (1  ≤  n, m ,k ≤  109).

      Output

      Output t lines that can determine the outcomes of the game on every board. Write «+» if the first player is a winner, and «-» otherwise.

      Example

      Input:
      10
      1 1 1
      1 2 1
      2 1 2
      2 2 2
      1 3 2
      2 3 2
      3 1 3
      3 2 3
      3 3 3
      4 3 3
      
      Output:
      -
      +
      +
      -
      +
      +
      -
      +
      -
      -
      

      Added by:Ruslan Sennov
      Date:2010-10-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Codeforces #36









      SPOJ Problem Set (classical)

      7603. Fibonacci Factor

      Problem code: FIBFACT


      Let F(n) be nth fibonacci number. F(0) = 0, F(1) = 1, F(2) = 1, F(3) = 2, F(4) = 3 and so on. Given a positive integer n > 2, print the smallest prime number P such that P divides F(n) but it does not divide any F(k) smaller than F(n). Maximum value of n is limited by P where P < 2^64. You should print IMPOSSIBLE if no such P exists.

      Input

      First line of input contains a single positive integer T denoting number of test cases. T <= 20. Next T lines contains value of n.

      Output

      Output value of P corresponding to each n in separate lines.

      Example

      Input:
      2
      3
      8

      Output:
      2
      7

      PS : Source Code Limit changed to 700B.

      Added by:XeRoN!X
      Date:2010-10-19
      Time limit:20s
      Source limit:700B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7623. Divisors VI

      Problem code: DIVISER9

      Find the the smallest integer with exactly N odd divisors, where each divisor is greater or equal to 1 !!!

      For example for 3 odd divisors, 9 (factors 1, 3, 9) is minimum.


       

      Input

      Each line contain N (0 < N < 1014).  There are 100 inputs total.

      Output

      One answer on each line for each N, Modulo 1000000007.

      Example

      Input: 
      3
      1024

      Output:
      9
      97947700


      Added by:Chen Xiaohong
      Date:2010-10-22
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS









      SPOJ Problem Set (classical)

      7627. Driving Direction

      Problem code: NE06D

      Contrary to the popular belief, alien flying saucers cannot fly arbitrarily around our planet Earth. Their touch down and take off maneuvers are extremely energy consuming, so they carefully plan their mission to Earth to touch down in one particular place, then hover above the ground carrying out their mission, then take off. It was all so easy when human civilization was in its infancy, since flying saucers can hover above all the trees and building, and their shortest path from one mission point to the other was usually a simple straight line -- the most efficient way to travel. However, modern cities have so tall skyscrapers that flying saucers cannot hover above them and the task of navigating modern city became quite a complex one. You were hired by an alien spy to write a piece of software that will ultimately give flying saucers driving directions throughout the city. As your first assignment (to prove your worth to your alien masters) you should write a program that computes the shortest distance for a flying saucer from one point to another. This program will be used by aliens as an aid in planning of mission energy requirements.

      The problem is simplified by several facts. First of all, since flying saucer can hover above most of the buildings, you are only concerned with locations of skyscrapers. Second, the problem is actually twodimensional -- you can look at everything ``from above" and pretend that all objects are situated on OXY Cartesian plane. Flying saucer is represented by a circle of radius r , and since modern cities with skyscrapers tend to be regular, every skyscraper is represented with a rectangle whose sides are parallel to OX and OY axes.

      By definition, the location of flying saucer is the location of its center, and the length of the path it travels is the length of the path its center travels. During its mission flying saucer can touch skyscrapers but it cannot intersect them.

      At the first picture a flying saucer of r = 1 has to get from point A to point B . The straight dashed line would have been the shortest path if not for skyscraper 1. The shortest way to avoid skyscraper 1 is going around its top right corner, but skyscraper 2 is too close to fly there. Thus, the answer is to go around the bottom left corner of skyscraper 1 for a total path length of 10.570796.

      In the second picture it is impossible for a flying saucer of r = 2 to get from point A to point B , since all skyscrapers are too close to fly in between them.

      In the third picture flying saucer of r = 1 has to fly in a slalom-like way around two skyscrapers in order to achieve the shortest path of length 11.652892 between A and B .

       

      \epsfbox{p3705.eps}

      Input

      The input file contains several test cases, each of them as described below.

      The first line of the input file contains integer numbers r and n (1$ \le$r$ \le$100, 0$ \le$n$ \le$30) , where r is the radius of the flying saucer, and n is the number of skyscrapers. The next line contains four integer numbers xA , yA , xB , and yB (- 1000$ \le$xA, yA, xB, yB$ \le$1000) , where (xA, yA) are the coordinates of the starting point of the flying saucer's mission and (xB, yB) are the coordinates of its finishing point.

      The following n lines describe skyscrapers. Each skyscraper is represented by four integer numbers x1 , y1 , x2 , and y2(- 1000$ \le$x1, y1, x2, y2$ \le$1000, x1 < x2, y1 < y2) -- coordinates of the corners of the corresponding rectangle.

      Skyscrapers neither intersect nor touch each other. Starting and finishing points of the flying saucer's mission are valid locations for flying saucer, that is, it does not intersect any skyscraper in those points, but may touch some of them.

      Output

      For each test case, write to the output a line with the text ``no solution" (without quotes) if the flying saucer cannot reach its finishing point from the starting one. Otherwise, write to the output a line with a single number -- the shortest distance that the flying saucer needs to travel to get from the starting point to the finishing point. Answer has to be precise to at least 6 digits after the decimal point.

      Example

      Input:
      1 3 
      2 7 7 1
      3 2 6 4
      7 5 9 8
      1 8 5 9
      2 4
      0 0 5 6
      8 3 10 6
      5 9 9 10
      1 4 2 8
      3 1 5 3
      1 2
      0 5 10 5
      2 2 4 5
      6 5 8 8

      Output:
      10.570796 
      no solution
      11.652892


      Added by:Race with time
      Date:2010-10-22
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS
      Resource:Northeastern European Regional Contest









      SPOJ Problem Set (main)

      7628. Mathematics

      Problem code: MATHS

      One could define mathematics as the study of quantity, structure, space and change and as the science of infinity. Sometimes very abstract, mathematics finds nevertheless applications in many engineering domains. The figure below shows so-called Ford circles. These circles are disjoint or tangent and fill the space in a very compact way! Starting with large circles, the space between these circles can be filled with circles of smaller diameter, and so on and so forth.

       

       

      Mathematicians observed that the diameters and positions of the centers of these circles follow a given scheme, which can be described with the help of Farey sequences. The Farey sequence of order N is the sequence of completely reduced fractions between 0 and 1, which have denominators less than or equal to N, arranged in increasing size. Thus each Farey sequence starts with the value 0, denoted by the fraction 01, and ends with the value 1, denoted by the fraction 11.

      The Amazing Circle Mathematicians (ACM) are interested in the number of terms contained in such a Farey sequence as well as in certain precise terms, which they name Interesting and Curious Position In Circle (ICPC). Your job is to provide the ACMs with this abstract information, which helps them to better understand the Ford circles.

       

      INPUT

      The input consists of several test-cases, one per line. Each test-case consists of two numbers, the first is the order N (2<=N<=106) of the Farey sequence the ACM is interested in and the second is the ICPC P (1<=P<=104) . Input terminates on a line containing 0 0 which must not be processed.

       

      OUTPUT

      For each test-case, output first the ICPC, then the total number of terms in the given Farey sequence.

       

      SAMPLE INPUT

      2 2

      6 12

      14 35

      0 0

       

      SAMPLE OUTPUT

      1/2 3

      5/6 13

      6/11 65

       


      Added by:Christian Kauth
      Date:2010-10-22
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ F# GO NODEJS PYTH 3.2.3 PYTH 3.2.3 n SED









      SPOJ Problem Set (classical)

      7629. Building Ports

      Problem code: BPORT


      N ports are to be constructed on the bytelandian river. Since trade occurs only along a Y miles stretch of the river, the distance between the start point and the last port must be Y. (Consider start point has the 0th port.)

      To optimize the ship movement between important ports, the distance between any two consecutive ports has been fixed to be within a range of possible distances. Also, distance between two consecutive ports can only be an integer number of miles.

      As a programmer you have been assigned the job of evaluating the number of different possible arrangements of ports modulo 1000000007.

       

      Input

      First line of input contains t. The number of test cases. (t<100)

      First line of each test case contains two integers: N, the number of ports to be built (N<=20) and Y, the ditance between the start point and the last port. (Y<100000)

      Next N lines of the test case contains the range of distances between consecutive ports, with ith line giving two integers, the minimum and maximum gap between (i-1)th and ith port.

       

      Output

      Print one of output for each test case which is the number of possible arrangements modulo 1000000007.

       

      Example

      Input:
      1
      2 4
      0 3
      0 3
      Output:
      3

      Added by:P != NP
      Date:2010-10-22
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict JAVA PAS fpc PAS gpc PYTH 2.7
      Resource:MNNIT IOPC 2010









      SPOJ Problem Set (classical)

      7630. SHOPPERS

      Problem code: SHOPPERS


      A group of N shoppers go to a supermarket. The supermarket has M items. Each shopper wants to buy only the items he likes.

      They plan to buy K items in all. A shopper can buy at max only one item. Some shoppers may not buy anything and some items might not be bought.


      Input


      First line contains the number of test cases.


      Each test case contains three integers N , M and K separated by spaces. Then follow N lines containing M characters each.

      If jth character of ith line is 1 then ith shopper likes item j.


      1<= K <= N, M <=13


      Output


      For each test case, output the number of ways K items in all can be bought.


      Example


      Input:
      1
      4 4 2
      1111
      0100
      0100
      1100


      Output:
      14


      Added by:P != NP
      Date:2010-10-22
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 C99 strict JAVA PYTH 2.7
      Resource:MNNIT IOPC 2010









      SPOJ Problem Set (classical)

      7632. Architecture

      Problem code: ARCHI

      Architecture, a tightrope walk between engineering and art! There are probably few invariants shared by the architectural styles around the world and throughout time. Precisely this diversity makes the domain so interesting and challenging.

       

       

      Any domains may serve as sources of inspiration, mathematical shapes, nature, organisms and even arched slices of Swiss cheese J. Some of our university friends from architecture plan to participate in the prestigious Erect a Palace From Lines (EPFL) contest. This contest is about designing a huge single-floor palace by building horizontal and vertical walls inside the preset square fundament.

      The students just finished their creative prototypes, and you are to revise their projects before they enter the contest. Some were obviously overwhelmed by the cryptographic protocol required for the palace description and do not know how many rooms their palace has. Walls are one unit thick and are described by their horizontal and vertical start and end positions. As the palace is huge, these coordinates are expressed in a base 26 system (the latin alphabet). Having overlapping walls is not a problem. For the encryption, read ‘A’ as zero and ‘Z’ as twenty-five. All other letters cover the remaining range in the conventional lexicographic order.

       

      INPUT

      The input consists of several test-cases, separated by an empty line. Each test-case starts with the side length of the square palace n (A<=n<=ZZ) and the number of walls w (0<=w<=500) the student placed inside the palace. The palace’s interior spreads thus from 0 to n-1, vertically and horizontally. The following w lines each describe a wall in the form x1 y1 x2 y2, the horizontal and vertical endpoints of the wall such that (0<=x1,y1,x2,y2<=n-1). Input terminates on a test-case with n=A and w=0, which must not be processed. You may safely assume that no student placed walls that transgress the fundaments of the palace and that no palace has more than 10’000 rooms.

       

      OUTPUT

      For each test-case, output the number of rooms in the palace.

       

      SAMPLE INPUT

      P 17

      G N G F

      F G C G

      F O F K

      G M N M

      C F C M

      I E K E

      O C O E

      B L B N

      J M J E

      M O J O

      H O C O

      L H L I

      N F K F

      M E O E

      N D O D

      E C E L

      G O G L

       

      ZZZZZZZZZZZZZZZZ 4

      A GH ZZZZZZZZZZZZZZZY GH

      POLYPROG SELECTION POLYPROG CONTEST

      TOBE ORNOT TOBE THATSTHEQUESTION

      LEADINGZEROS NO LEADINGAS NO

       

      SAMPLE OUTPUT

       

      4

      2


      Added by:Christian Kauth
      Date:2010-10-23
      Time limit:10s-30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7637. Road Map

      Problem code: RANJAN05

      There are x villages in Andhere Nagar. Each village has its index — an integer number from 1 to x. The capital has index a. All the roads in Andhere Nagar are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Andhere Nagar's chronicles the road map is kept in the following way: for each village i, different from the capital, there is kept number pi — index of the last village on the way from the capital to i.

      Once the king of Andhere Nagar, Choupat Raja, decided to move the capital from village a to village b. Naturally, after this the old representation of the road map in Andhere Nagar 's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above.

      Input

      The first line contains three space-separated integers x, a, b (2 ≤ x ≤ 5· 104, 1 ≤ a ≠ b ≤ n) — amount of villages in Andhere Nagar, index of the old capital and index of the new one, correspondingly.

      The following line contains x - 1 space-separated integers — the old representation of the road map. For each city, apart from a, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes.

      Output

      Output x - 1 numbers — new representation of the road map in the same format.

      Example 1

      Input:
      3 2 3
      2 2

      Output:
      2 3

      Example 2

      Input:
      6 2 4
      6 1 2 4 2

      Output:
      6 4 1 4 2


      Added by:`
      Date:2010-10-23
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:IIITM Local Contest









      SPOJ Problem Set (classical)

      7666. Telecommunications

      Problem code: TELECOM

      From beacons over telegraphs and telephones towards radio and television and ultimately computer networks and internet – telecommunication systems knew a tremendous evolution within the last century! This was also clear to Richard Hamming, who was bothered by erroneous data transmission.

      As the transmission channel is often very noisy, the received information is not necessarily the information that was sent out. Looking at digital data transmission, a straight-forward way to check for errors would be a supplementary bit of information, a so-called parity bit. Each package of data on n-1 bits is completed by 1 parity bit, whose value is chosen such that the number of ones in the n-bit package is even. Although there is little overhead, parity checking is not very robust. If an even number of bits is flipped during transmission, the check bit remains valid and the error will not be detected. Moreover, although parity can detect errors, it provides no indication on the position of the flipped bit. The data must be discarded entirely and re-transmitted.

       

       

      If more error-correcting bits are included with a message, and if those bits can be arranged such that different incorrect bits produce different error results, then bad bits could be identified and corrected! Among others, Hamming invented the following algorithm that generates a single-error correcting code for any number of bits.

      Hamming Codes:

      1. Number the bits starting from 1: bit 1, 2, 3, 4, 5, etc.
      2. Write the bit numbers in binary. 1, 10, 11, 100, 101, etc.
      3. All bit positions that are powers of two (have only one 1 bit in the binary form of their position) are parity bits.
      4. All other bit positions, with two or more 1 bits in the binary form of their position, are data bits.
      5. Each data bit is included in a unique set of 2 or more parity bits, as determined by the binary form of its bit position.

      a)      Parity bit 1 covers all bit positions which have the least significant bit set: bit 1 (the parity bit itself), 3, 5, 7, 9, etc.

      b)      Parity bit 2 covers all bit positions which have the second least significant bit set: bit 2 (the parity bit itself), 3, 6, 7, 10, 11, etc.

      c)      Parity bit 4 covers all bit positions which have the third least significant bit set: bits 4–7, 12–15, 20–23, etc.

      d)      Parity bit 8 covers all bit positions which have the fourth least significant bit set: bits 8–15, 24–31, 40–47, etc.

      e)      In general each parity bit covers all bits where the binary AND of the parity position and the bit position is non-zero.

      Imagine you want to transmit the data ‘42’. Its binary representation is 101010. According to the above algorithm, some of these data bits must shift their position and will be interlaced by parity bits. We obtain 10-101-0--, where each hyphen is a placeholder for a parity bit. To get an even number of ones on positions 1,3,5,7,9, parity bit 1 must be 0. Setting parity bit 2 to 0 ensures an even number of ones on positions 2,3,6,7,10. For similar reasons on positions 4,5,6,7, parity bit 4 must be 0 and parity bit 8 must be 1 because of positions 8,9,10. Thus the Hamming code for data ‘42’ is ‘1011010000’ i.e. ‘720’. Let’s suppose the transmission channel is noisy and the received code is ‘724’, i.e.’1011010100’. Then the parity check for parity bit 1 counts an odd number of ones and so does the check for parity bit 2. Parity bit checks 4 and 8 result in an even value. Thus the bit that occurs in parity checks 1 and 2 (i.e. position 3) is wrong and can be corrected! We found back the ‘720’ code. Removing the parity overhead (bits 1,2,4,8) yields the correct data ‘42’!

      Assuming that the noise in the channel is not sufficient to flip more than one bit per package, you are to write a program that extracts the data from a received Hamming code. 

       

      INPUT

      The input consists of several test-cases, one per line. Each test-case consists of a single decimal number C (0<=C<264) , which is the received Hamming code. The last line is -1, which is obviously not a Hamming code and terminates the test sequence.


      OUTPUT

      For each test-case, output the correct data that was transmitted, assuming the above algorithm was used to generate the Hamming code.

       

      SAMPLE INPUT

      7

      28

      109

      -1

       

      SAMPLE OUTPUT

      1

      3

      5

       

      From beacons over telegraphs and telephones towards radio and television and ultimately computer networks and internet – telecommunication systems knew a tremendous evolution within the last century! This was also clear to Richard Hamming, who was bothered by erroneous data transmission.

      As the transmission channel is often very noisy, the received information is not necessarily the information that was sent out. Looking at digital data transmission, a straight-forward way to check for errors would be a supplementary bit of information, a so-called parity bit. Each package of data on n-1 bits is completed by 1 parity bit, whose value is chosen such that the number of ones in the n-bit package is even. Although there is little overhead, parity checking is not very robust. If an even number of bits is flipped during transmission, the check bit remains valid and the error will not be detected. Moreover, although parity can detect errors, it provides no indication on the position of the flipped bit. The data must be discarded entirely and re-transmitted.

      If more error-correcting bits are included with a message, and if those bits can be arranged such that different incorrect bits produce different error results, then bad bits could be identified and corrected! Among others, Hamming invented the following algorithm that generates a single-error correcting code for any number of bits.


      Added by:Christian Kauth
      Date:2010-10-24
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7668. Pebble Solver

      Problem code: PEBBLE


      Pebble is a popular turn-based multi-player game played by kids. In this game, all the players are given a binary string (i.e., a string consisting only of 0's and 1's) of some fixed length. The goal of the game is to convert this binary string to a string containing all 0's.

      In a turn, a player is allowed to perform only one operation:- Replace a 1 by a 0 or vice-versa. But each such operation will flip the states of all the bits following the bit you changed.

      Take for example, the string: 1001010. You decide to flip the 1 located at the 4th position. The new string after the operation will be : 1000101. (Note that 5th to 7th bits flipped as a result of flipping the 4th bit.)

      Your small sister loves to play this game very much. So, you decide to gift her the pebble-solver software which solves this game with the minimum number of operations(how else will you make sure that she always wins?!). And we want to make sure that your software doesn't have any bugs. (he he)

      Input

      There are going to multiple test cases. Each test case consists of a single line which is the initial bit-string.

      Output

      Output corresponding to the each test case in the following format :

      "Game #x: y", where x indicates the test case number and y is the minimum number of steps required for your program to solve the game.

      Example

      Input:
      0101
      10000
      00
      Output:
      Game #1: 3
      Game #2: 2
      Game #3: 0

      Added by:Siddharth Kothari
      Date:2010-10-25
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      7676. Sum of Digits

      Problem code: CPCRC1C

      Majid is a 3rd-grade elementary student and quite well in mathematics. Once, Majid's teacher asked him to calculate the sum of numbers 1 through n.

      Majid quickly answered, and his teacher made him another challenge. He asked Majid to calculate the sum of the digits of numbers 1 through n.

      Majid did finally find the solution. Now it is your turn, can you find a solution?

      Input

      Two space-separated integers 0 <= a <= b <= 109.

      Program terminates if a and b are -1.

      Output

      The sum of the digits of numbers a through b.

      Example

      Input:
      1 10
      100 777
      -1 -1
      Output:
      46
      8655

      Added by:Tii
      Date:2010-10-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://cs.ikiu.ac.ir/cms/icpc/training/7-contest/86-contest1









      SPOJ Problem Set (classical)

      7680. Electrical Engineering

      Problem code: ELEC

      The electrical engineers’ indefatigable strive towards environmentally friendly energy production translated into the recent boom of hydro, solar, wind and geothermal power plants. While the production side seems ready, these ambitious projects have their bottleneck in the transportation and distribution: Besides the energy losses that occur during transportation over long distances, the renewable energy sources cannot provide power on demand – they must be taken as provided by nature. Used at large scale in today’s networks, unreliable green energy can disrupt the balance of power grids easily and cause huge damage along with large-scale power outages.

       

       

      Serious effort is thus put on researching transient and dynamic phenomena in power grids. You are offered a position in the lab for linear and planar distribution networks. Given a description of the distribution network’s line impedances Zi , you are to find the equivalent impedance between some couples of nodes. The knowledge of such equivalent impedances may speed up the network analysis considerably! Impedances are complex number whose real part represents the resistive line behaviour while the imaginary part stands for the capacitive (negative) or inductive (positive) characteristic. Lines are bidirectional, that is impedance(a,b) equals impedance (b,a).

      It was proven that any linear and planar graph (can be drawn in a way that its edges intersect only at their endpoints) can be reduced into a single equivalent edge that represents the equivalent impedance between its ending nodes, using the following six transformations:

       

       

      Now that you have all the necessary operations available, are you able to determine the equivalent impedance between several couples of nodes?

       

      INPUT

      The input consists of several test-cases separated by an empty line. Each test-case starts with the number of nodes N (1<=N<=100), the number of bidirectional connections C (0<=C<=1000) and the number of equivalent impedances to compute Z (0<=Z<=10) on a line. Then follow C lines, each describing one bidirectional connection in the form ‘EndPoint_1’ ‘EndPoint_2’ ‘Impedance’. ‘EndPoint_1’ and ‘EndPoint_2’ are in the range 1 to N and impedance has the format ‘re im’ where re and im designate the real and imaginary parts respectively, both being real numbers d such that 10-3 < |d| < 103. The next Z lines each hold two integers, the indices of the nodes between which you are to compute the equivalent impedance. Input terminates on a test-case with N=C=Z=0, which must not be evaluated.

       

      OUTPUT

      For each couple of endpoints, output the equivalent impedance in the form ‘re im’ where re and im designate the real and imaginary parts respectively. If the nodes are not connected, output ‘no connection’. Electrical engineers will consider your result as correct if the absolute error on the real and imaginary parts is below 10-2. Finish each test-case on a blank line.

       

      SAMPLE INPUT

      5 10 3

      3 1 12.317 -0.779

      5 3 30.107 0.289

      5 1 27.447 -22.649

      4 2 15.351 24.371

      5 5 19.63 -3.549

      2 2 11.841 18.757

      4 5 4.834 -16.542

      3 5 5.022 -22.387

      2 5 24.768 -22.356

      5 2 27.351 12.053

      1 2

      2 3

      3 3


      10 10 4

      9 8 6.36 17.411

      1 3 27.596 -6.484

      9 10 4.735 -8.282

      8 8 6.901 27.939

      8 4 14.894 3.729

      5 4 14.311 -2.422

      10 10 11.009 6.225

      4 4 3.196 -32.703

      10 9 15.282 -14.799

      3 9 20.473 27.158

      10 9

      8 1

      2 9

      9 6

       

      SAMPLE OUTPUT

      23.37 -7.26
      19.61 -6.97
      0.00 0.00

      3.79 -5.46
      54.43 38.09
      no connection
      no connection

                      

      Sample input 1                                      Sample input 2


      Added by:Christian Kauth
      Date:2010-10-25
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7683. Powered and Squared

      Problem code: CSQUARE

      Description :

      Marko is learning method of successive squaring so that he can calculate a^b mod m quickly. To give himself practice he wrote many tuples of a, b and m and went to school thinking that he will do it after school.

      After school he found that tuples he wrote are modified by his little sister. His sister converted each b into base 3. Marko wrote everything in base 10.

      Help Marko to do his excercise.

      Input:

      First line of input contains a number t, number of test cases. Then t test cases follows each containing three numbers a(<=10^9), b and m(<=10^5) (a in base 10, b in base 3 and m in base 10). Number of digits in b will be less than 250.

      Output:

      Output a number for each test case a^b mod m in base 10.

      Sample

      Input:

      2
      2 10 10
      3 21101 19

      Output:
      8
      3


      Added by:Divyanshu Ranjan
      Date:2010-10-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ F# GO NODEJS PYTH 3.2.3 PYTH 3.2.3 n SED









      SPOJ Problem Set (classical)

      7685. Flowers

      Problem code: FLWRS

      Hanadi has N flower pots each with a unique flower. The pots are arranged along in a line.

      One day, She decided to change their order under the condition that no two pots that were

      originally next to each other remain next to each other.

       

      Task

      write a program that is given the number of pots, calculates the number of possible orders

      satisfying the condition modulo a given integer M.

       

      Constraints

      1N2,000                         The number of pots.

      2M1,000,000,000


      Input

      • Line 1 contains the integer N, the number of flower pots.
      • Line 2 contains the integer M.

      Output

      A single line containing one integer between 0 and M-1 (inclusive): the number of possible

      orders modulo M.

       

      Example

      Input:
      5
      11
      Output:
      3
      For 5 pots, there are 14 orders satisfying Hanadi's condition, assuming the original order
      of pots was "ABCDE"
      Then the 14 possible orders are:

      ACEBD

      ADBEC

      BDACE

      BDAEC

      BECAD

      CADBE

      CAEBD

      CEADB

      CEBDA

      DACEB

      DBEAC

      DBECA

      EBDAC

      ECADB


      14 modulo 11 = 3

      So the answer is 3


       

      • Number of test-cases is 28.


      Added by:Rofael Emil
      Date:2010-10-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:(modified) Egyptian Olympiad in Informatics ( EOI ) 2009, August 14 - 21, Cairo









      SPOJ Problem Set (classical)

      7691. Homo or Hetero

      Problem code: HOMO

       

      Consider a list of numbers with two operations:
      • insert number — adds the specified number to the end of the list.
      • delete number — removes the first occurrence of the specified number from the list. If the list
      does not contain the number specified, no changes are performed.
      For example: the result of the insertion of a number 4 to the list [1, 2, 1] is the list [1, 2, 1, 4]. If we delete
      the number 1 from this list, we get the list [2, 1, 4], but if we delete the number 3 from the list [1, 2, 1, 4],
      the list stays unchanged.
      The list is homogeneous if it contains at least two equal numbers and the list is heterogeneous if it
      contains at least two different numbers. For example: the list [2, 2] is homogeneous, the list [2, 1, 4] is
      heterogeneous, the list [1, 2, 1, 4] is both, and the empty list is neither homogeneous nor heterogeneous.
      Write a program that handles a number of the operations insert and delete on the empty list and
      determines list’s homogeneity and heterogeneity after each operation.

       

      Consider a list of numbers with two operations:

      • insert number — adds the specified number to the end of the list.

      • delete number — removes the first occurrence of the specified number from the list. If the list does not contain the number specified, no changes are performed.

      For example: the result of the insertion of a number 4 to the list [1, 2, 1] is the list [1, 2, 1, 4]. If we delete the number 1 from this list, we get the list [2, 1, 4], but if we delete the number 3 from the list [1, 2, 1, 4], the list stays unchanged.

      The list is homogeneous if it contains at least two equal numbers and the list is heterogeneous if it contains at least two different numbers. For example: the list [2, 2] is homogeneous, the list [2, 1, 4] is heterogeneous, the list [1, 2, 1, 4] is both, and the empty list is neither homogeneous nor heterogeneous.

      Write a program that handles a number of the operations insert and delete on the empty list and determines list’s homogeneity and heterogeneity after each operation.

      Input

       

      The first line of the input file contains an integer number n — the number of operations to handle (1 ≤ n ≤ 100 000).

      Following n lines contain one operation description each. The operation description consists of a word “insert” or “delete”, followed by an integer number k — the operation argument (−10^9 ≤ k ≤ 10^9 ).

       

      Output

       

      For each operation output a line, containing a single word, describing the state of the list after the operation:

      • “both” — if the list is both homogeneous and heterogeneous.

      • “homo” — if the list is homogeneous, but not heterogeneous.

      • “hetero” — if the list is heterogeneous, but not homogeneous.

      • “neither” — if the list is neither homogeneous nor heterogeneous.

       

      Example

      Input:
      11
      insert 1
      insert 2
      insert 1
      insert 4
      delete 1
      delete 3
      delete 2
      delete 1
      insert 4
      delete 4
      delete 4


      Output:
      neither
      hetero
      both
      both
      hetero
      hetero
      hetero
      neither
      homo
      neither
      neither

      Added by:Daniel Ampuero
      Date:2010-10-27
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK NODEJS PYTH 3.2.3 n SED
      Resource:ACM ICPC 2009–2010, NEERC, Northern Subregional Contest









      SPOJ Problem Set (classical)

      7692. Chemistry

      Problem code: CHEM

      The story started some 5’000 years ago in Ancient Egypt, was continued by the Greeks and Arabs, reached France, Europe, and finally conquered the world. The studies on the compositions of waters, the humans’ greed for purified materials, millions of experiments and many brilliant minds made chemistry what it is today: No more the quest of the Philosopher’s stone, but the study of matter and the changes it undergoes.

       

       

      There remain nevertheless still groups of stout-hearted followers of ancient believes, so-called alchemist. Keeping their research top-secret, they meet once a year for a conference where they share their recent findings. This year’s location is Lausanne and Extremely Purified Fluorescent Liquids (EPFL) is the topic. The idea is that the chemists brew together some new EPFLs. As we speak about state of the art EPFLs, it is necessary that certain chemists put their very specific knowledge together. Thus for a certain EPFL E1, the presence of chemists C1, C2 and C3 may be required. For another E2, chemists C1 and C4 might be necessary.

       Although chemists are generally very patient people, as their reactions might take long times, they get very impatient if they are to observe experiments in which they are not involved. As an example, chemist C4 would go crazy if he had to assist to the brewage of E1. To ensure a pleasant stay in Lausanne to every chemist, you are to arrange their departure and arrival dates so that each chemist is available whenever his knowledge is required, but is not in Lausanne when other EPFLs are created.

      To this purpose, you are given a schedule with ones and zeros. Each column stands for one EPFL, each row for one chemist. There is a 1 at position (Ci,Ei) if chemist Ci is needed for EPFL Ei, and a zero otherwise. Your task boils now down on rearranging the columns in a way that all ones are consecutive in every line. For traditional reasons, the organizers’ EPFL is always brewed first and corresponds to the first column of the input schedule (E1).

      INPUT

      The input consists of several test-cases separated by an empty line. Each test-case starts with the number of chemists C (1<=C<=400), followed by the number of EPFLs E (1<=E<=400). Then follow C lines of E characters, ‘1’ or ‘0’. You may assume that there exists exactly one order of EPFLs (initiated by E1) that meets the above constraints. Input terminates on a test-case with C=E=0, which must not be processed.

       

      OUTPUT

      Print each output on a line by itself, which holds E numbers, corresponding to the initial position in the planning, arranged such that all chemists are available when necessary and away from Lausanne otherwise. (the first number must always be 1 as a tribute to the host).

       

      SAMPLE INPUT

      6 5

      00010

      01000

      10101

      10100

      00011

      00101

       

      0 0

       

       

      SAMPLE OUTPUT

      1 3 5 4 2

       


      Added by:Christian Kauth
      Date:2010-10-27
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7693. Environmental Engineering

      Problem code: ENVIRON


      One of the major challenges for environmental engineers in the future will be the overall scarcity of potable water. Not only vegetation and wildlife are fundamentally dependent upon adequate freshwater resources, but also humans. Several desalination processes were developed to make sea water drinkable.

      Nonetheless, the water distribution is not uniform on planet, and so some regions are lacking water while others possess it on excess. The International Committee for Precious Consumables (ICPC) worked out an ambitious project fostering the uniform distribution of water on Earth (a perfect ball). The richest and poorest regions in terms of water resources were found to lie equidistantly distributed along a circle of maximum length around the Earth (i.e. the centre of the Earth is also the centre of this circle). So the idea came to construct gigantic pipelines that can transport water along this circle.

       

       

      Each pipeline has two terminals, starting at a location with water abundance and ending in a region with water scarcity. As drilling the Earth on so long distances is not a reasonable option, all pipelines will be above Earth. Further are there dedicated ducts for the pipelines at different heights. That is, a pipeline grows vertically into the sky until one of the allowed heights is reached, makes a 90° angle, and follows the duct at constant height until it is above the depletion region, where it forms another 90° angle to descent vertically to ground.

      As all pipelines’ projection to ground must follow the same circle, the ICPC faces a serious problem. They must make sure that no pipelines cross each other in this 2D plane! Further they are concerned about the total length of the pipes, which they’d like to minimize. Your task is to calculate the minimal total length of all the pipes, knowing that the allowed duct heights are non-zero integer multiples of the distance between two adjacent locations (measured along the circle on surface level), which for our purpose has a value of 1.

       

      INPUT

      The input consists of several test-cases separated by an empty line. Each test-case starts with the number of locations N (0<=N<=500), followed by a line containing N numbers (‘0’ or ‘1’) and describing the locations along the circle. A ‘0’ stands for a location with water depletion, a ‘1’ for a region with water abundance. You may safely assume that there are as many ‘0’ as ‘1’. Input terminates on a test-case with N=0, which must not be evaluated.

       

      OUTPUT

      For each test-case, output the minimum total length (to a precision of 10-2) of the pipes so that each abundance region connects to exactly one depletion region.

       

      SAMPLE INPUT

      4

      1 0 0 1

       

      8

      1 1 1 1 0 0 0 0

       

      0

       

      SAMPLE OUTPUT

       

      9.14

      31.00

       

                

      Sample input 1                   Sample input 2                   A larger test-case


      Added by:Christian Kauth
      Date:2010-10-27
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7696. Encryption

      Problem code: CENCRY


      Marko is going to write a secret letter to a friend. He thought it is better to encrypt letter so that no other person can read it. After long thought he came up with an encryption scheme which was lame but he thought it will work anyways.

      To encrypt a text he first wrote two infinite strings of characters first string consists only of vowels and second string consists of consonants only.

      aeiouaeiouaeiouaeiouaeiou....................
      bcdfghjklmnpqrstvwxyzbcdfghjklmnpqrstvwxyz...
       
      Following is the scheme for encryption :
      1. let c be any character to be encrypted.
      2. let k be the count of number of times c character occured in text to be encrypted till now.
      3. first find which of two infinite string contains that character.
      4. then look for kth occurence of that character in that string.
      5. replace charcter c by corresponding character in second string.

      For example encrypted text of "baax" will be "abho".

      Input

      First line of input will contains t, number of test cases. Then t test case follows each test case in a line. Each test case will be a string of small latin alphabets. Length of string will be less than 5*10^4

      Output

      For each test case print encrpyted text.

      Sample :

      Input:

      2
      baax
      aaa

      Output:

      abho
      bhn


      Added by:Divyanshu Ranjan
      Date:2010-10-27
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (main)

      7704. Civil Engineering

      Problem code: CIVIL

      Civil engineers are people who build impressive structures from concrete and steel. Throughout the world, sky scrapers get ever higher, bridges get ever wider, and tunnels get ever longer. Most recently, the Gotthard Base Tunnel just pushed the limits a bit further...

      Gotthard base tunnel

      In this task, you take the role of a civil engineer who is to build a tunnel through a mountain. Unfortunately, you have a very limited budget, and must construct the cheapest possible tunnel.

      Because engineers have a habit of simplifying things, we will model the mountain and the tunnel using basic geometric shapes. First of all, consider that the earth is flat, and two-dimensional. On this flat surface stands a mountain of height h and width w. Each side of the mountain is parabolic (i.e. satisfies y = ax² + bx + c for some a, b, c). You also know that the base of the mountain is smooth, which means that its steepness at the base is zero.

      Graphical view of a tunnel

      The tunnel is modeled as a horizontal line through the mountain. The best possible tunnel is the one which minimizes construction cost. This cost is proportional to the length of the road which leads to the tunnel, plus the length of the tunnel itself. Consider that each meter of the tunnel is a factor f times as expensive as a meter of road.

      Input

      The input file consists of several test cases. Each case is given on a line by itself and consists of the three numbers h, w and f, separated by a space. All these are strictly positive floating point numbers. The input file ends with a test case where all numbers are zero (which must not be processed).

      Output

      Print for each test case a single number, the optimal height t of the tunnel. Always print three digits after the decimal point. You may assume that it is always cheaper to build some tunnel than to drive over the top of the mountain.

      Example

      Input:
      1 2 1.5
      9033.66 29752.4 1.56382
      0 0 0

      Output:

      0.313
      8852.956

      Added by:Jonas Wagner
      Date:2010-10-29
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ F# GO NODEJS PYTH 3.2.3 PYTH 3.2.3 n SED









      SPOJ Problem Set (classical)

      7709. Jumping Zippy

      Problem code: JZPCIR

      Jumping Zippy likes to jump. He jumps every day and feels boring. Then he think of a new way to jump. He jumps on a big round plaza. The plaza is divided into n sectors numbered clockwise from 0 to n-1. Firstly, he stands on sector 0. Each time, when he is stand on sector x, he can jump to sector (x-2)%n, (x-1)%n, (x+1)%n or (x+2)%n. His goal is to jump to each sector exactly once and jump back to sector 0 at last. And for the first jump, he never jumps to sector n-1 or sector n-2. He wants to find the number of different ways in which he can complete his goal.

      Input

      First line is a number t, which is the number of testcases. (1<=t<=1000)

      The following t lines, each line contains a integer n, which is the number of sectors. (5<=n<=10^18)

      Then following t lines, each line contains a integer n, which is the number of sectors. (5<=n<=10^18)

      Output

      For each query n, output a line which contains one integer, the number of different ways Zippy can complete his goal in, modulo 10^9+9.

      Example

      Input:
      5
      5
      6
      7
      8
      9
      
      Output:
      12
      16
      23
      29
      41
      

      Added by:sevenkplus
      Date:2010-10-29
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      7718. Number of common divisors

      Problem code: COMDIV

      You will be given T (T<=10^6) pair of numbers. All you have to tell is the number of common divisors between two numbers in each pair.

      Input

      First line of input: T (Number of test cases)
      In next T lines, each have one pair A B (0<A,B<=10^6)

      Output

      One integer describing number of common divisors between two numbers.

      Example

      Input:
      3
      100000 100000
      12 24
      747794 238336


      Output:
      36
      6
      2


      Added by:Mir Wasi Ahmed
      Date:2010-10-31
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem, used in UODA TST









      SPOJ Problem Set (classical)

      7733. Happy Numbers I

      Problem code: HPYNOS

      The process of “breaking” an integer is defined as summing the squares of its digits. For example, the
      result of breaking the integer 125 is (12 + 22 + 52) = 30. An integer N is happy if after “breaking” it
      repeatedly the result reaches 1. If the result never reaches 1 no matter how many times the
      breaking” is repeated, then N is not a happy number.

      TASK

      Write a program that given an integer N, determines whether it is a happy number or not.

      CONSTRAINTS

      2 ≤ N ≤ 2,147,483,647

      Input

          • A single line containing a single integer N.

      Output

          • A single line containing a single integer T which is the number of times the process had to be
            done to determine that N is happy, or -1 if N is not happy.

      Example

      Input:
      19

      Output:
      4


      1) 19 : 12 + 92 = 82
      2) 82 : 82 + 22 = 68
      3) 68 : 62 + 82 = 100
      4) 100 : 12 + 02 + 02 = 1

      The solution is 4 because we discovered that the integer 19 is happy after we repeated the process 4
      times.


      Example


      Input:
      204

      Output:
      -1




      204 –> 20 –> 4 –> 16 –> 37 –> 58 –> 89 –> 145 –> 42 –> 20 –> 4 –> 16 –> 37 –> 58 –> 89 –> 145 ……..



      204 is not a happy number because after breaking it several times the results start repeating so we
      can deduce that if we continue breaking it, the result will never reach 1.




      Number of test cases is 32.


      Don't use pre-calculated values (Don't Cheat)!!!


      Added by:Rofael Emil
      Date:2010-11-03
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Egyptian Olympiad in Informatics ( EOI ) 2009, August 14 - 21, Cairo









      SPOJ Problem Set (classical)

      7737. Escape

      Problem code: BOI7ESC


      A group of war prisoners are trying to escape from a prison. They have thoroughly planned the escape from the prison itself, and after that they hope to find shelter in a nearby village. However, the village (marked as B, see picture below) and the prison (marked as A) are separated by a canyon which is also guarded by soldiers. These soldiers sit in their pickets and rarely walk; the range of view of each soldier is limited to exactly 100 meters. Thus, depending on the locations of soldiers, it may be possible to pass the canyon safely, keeping the distance to the closest soldier strictly larger than 100 meters at any moment.

      You are to write a program which, given the width and the length of the canyon and the coordinates of every soldier in the canyon, and assuming that soldiers do not change their locations, first determines whether prisoners can pass the canyon unnoticed. If this is impossible then the prisoners (having seen enough violence) would like to know the minimum number of soldiers that have to be eliminated in order to pass the canyon safely. A soldier may be eliminated regardless of whether he is visible to any other soldier or not.

      Input

      The first line contains three integers L, W , and N – the length and the width of the canyon, and the number of soldiers, respectively. Each of the following N lines contains a pair of integers Xi and Yi – the coordinates of i-th soldier in the canyon (0 ≤ Xi ≤ L, 0 ≤ Yi ≤ W ). The coordinates are given in meters, relative to the canyon: the southwestern corner of the canyon has coordinates (0, 0), and the northeastern corner of the canyon has coordinates (L, W ), as seen in the picture above.
      Note that passing the canyon may start at coordinate (0, ys ) for any 0 ≤ ys ≤ W and end at coordinate (L, ye ) for any 0 ≤ ye ≤ W . Neither ys nor ye need to be integer.

      Output

      In the first and only line of the output file the program should print the minimum number of soldiers that have to be eliminated in order for the prisoners to pass the canyon safely. If the prisoners can escape without any elimination, the program should print 0 (zero).

      Constraints

      1 ≤ W ≤ 50,000 1 ≤ L ≤ 50,000
      1 ≤ N ≤ 250

      Example

      Input:
      130 340 5
      10 50
      130 130
      70 170
      0 180
      60 260

      Output:
      1




      Added by:Race with time
      Date:2010-11-04
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Baltic Olympiad 2007









      SPOJ Problem Set (classical)

      7739. Sound

      Problem code: BOI7SOU

      In digital recording, sound is described by a sequence of numbers representing the air pressure, measured at a rapid rate with a fixed time interval between successive measurements. Each value in the sequence is called a sample. An important step in many voice-processing tasks is breaking the recorded sound into chunks of non-silence separated by silence. To avoid accidentally breaking the recording into too few or too many pieces, the silence is often defined as a sequence of m samples where the difference between the lowest and the highest value does not exceed a certain treshold c. Write a program to detect silence in a given recording of n samples according to the given parameter values m and c.

      Input

      The first line of the file contains three integers: n (1 ≤ n ≤ 1,000,000), the number of samples in the recording; m (1 ≤ m ≤ 10,000), the required length of the silence; and c (0 ≤ c ≤ 10,000), the maximal noise level allowed within silence. The second line of the file contains n integers ai (0 ≤ ai ≤ 1,000,000 for 1 ≤ i ≤ n), separated by single spaces: the samples in the recording.

      Output

      The file should list all values of i such that max(a[i . . . i + m − 1]) − min(a[i . . . i + m − 1]) ≤ c. The values should be listed in increasing order, each on a separate line. If there is no silence in the input file, write NONE on the first and only line of the output file.

      Example

      Input:
      7 2 0
      0 1 1 2 3 2 2
      Output: 2
      6

      Added by:Race with time
      Date:2010-11-04
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Baltic Olympiad 2007









      SPOJ Problem Set (classical)

      7740. Fence

      Problem code: BOI7FEN

      Leopold is indeed a lucky fellow. He just won a huge estate in the lottery. The estate contains several grand buildings in addition to the main mansion, in which he intends to live from now on. However, the estate lacks a fence protecting the premises from trespassers, which concerns Leopold to a great extent. He decides to build a fence, but unfortunately he cannot afford to put it round all of his newly acquired land. After some thinking, he decides it is sufficient to have a fence that encloses the main mansion, except for one important restriction: the fence must not lie too close to any of the buildings.
      To be precise, seen from above, each building is enclosed in a surrounding forbidden rectangle within which no part of the fence may lie. The rectangles’ sides are parallel to the x- and y-axis. Each part of the fence must also be parallel either to the x-axis or the y-axis.

      Figure 5.1: The main mansion (black) and three other buildings with sur- rounding forbidden rectangles. The thick black line shows a shortest allowed fence enclosing the main mansion.

      Figure 5.1: The main mansion (black) and three other buildings with surrounding forbidden rectangles. The thick black line shows a shortest allowed fence enclosing the main mansion.

      Input

      The first line of the input file contains a positive integer m (1 ≤ m ≤ 100), the number of buildings of the estate. Then follow m lines each describing a forbidden rectangle enclosing a building. Each row contains four space-separated integers tx, ty, bx, and by, where (tx, ty) are the coordinates of the upper left corner and (bx, by) the coordinates of the bottom right corner of the rectangle. All coordinates obey 0 ≤ tx < bx ≤ 10,000 and 0 ≤ ty < by ≤ 10,000. The first rectangle is the forbidden rectangle enclosing the main mansion.

      Output

      Contains one line with a single positive integer equal to the minimum length of any allowed fence enclosing the main mansion.

      Example

      Input:
      4
      8 4 13 8
      2 1 6 7
      4 7 9 11
      14 7 19 11
      Output:
      32

      Added by:Race with time
      Date:2010-11-04
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Baltic Olympiad 2007









      SPOJ Problem Set (classical)

      7741. Sequence

      Problem code: BOI7SEQ

      We are given a sequence a1 , ..., an . We can manipulate this sequence using the operation reduce(i), which replaces elements ai and ai+1 with a single element max(ai , ai+1 ), resulting in a new shorter sequence. The cost of this operation is max(ai , ai+1 ). After n−1 operations reduce, we obtain a sequence of length 1. Our task is to compute the cost of the optimal reducing scheme, i.e. the sequence of reduce operations with minimal cost leading to a sequence of length 1.

      Input

      The first line contains n (1 ≤ n ≤ 1,000,000), the length of the sequence. The following n lines contain one integer ai , the elements of the sequence (0 ≤ ai ≤ 1,000,000,000).

      Output

      In the first and only line of the output print the minimal cost of reducing the sequence to a single element.

      Example

      Input:
      3
      1
      2
      3
      Output: 5

      Added by:Race with time
      Date:2010-11-04
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Baltic Olympiad 2007









      SPOJ Problem Set (classical)

      7742. Onotole needs your help

      Problem code: OLOLO

      Onotole has a lot of pyani. Each pyani has a number, writing on it. Pyanis with equal numbers are indistinguishable. Onotole knows everything, so, he knows that each pyani appeared twice, and only one pyani is unique. He wants to get вздръжни эффект, and he needs the unique pyani. Given the list of pyanis denote which one of them appeared once (it is guaranteed that other pyanis appeared twice).

      Input

      First line of input contains number of pyanis N<=500 000. Next N lines contain a single positive integer 1 <= Pi <= 10^9.

      Output

      Output one positive integer on pyani, which appeared once.

      Example

      Input:
      3
      1
      8
      1
      Output: 8

      Onotole has found not optimal AC algorithms, so all solutions will be rejudged. He is watching you.


      Added by:Ефиме
      Date:2010-11-04
      Time limit:0.75s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7753. Happy Numbers II

      Problem code: HPYNOSII

      The process of “breaking” an integer is defined as summing the squares of its digits. For example, the
      result of breaking the integer 125 is (12 + 22 + 52) = 30. An integer N is happy if after “breaking” it
      repeatedly the result reaches 1. If the result never reaches 1 no matter how many times the
      breaking” is repeated, then N is not a happy number.

      TASK

      Write a program that given an integer T (number of test cases) and T integers, determines for each number whether it is a happy number or not.

      CONSTRAINTS

      1 ≤ T ≤ 1,080,000

      2 ≤ N ≤ 2,147,483,647  (number for determining whether it is happy or not)

      Input

          • The first line contains an integer T.

          • next 1...T lines contain an integer N for detemining whether it is happy or not.

      Output

          • T lines containing a single integer N which is the number of times the process had to be
            done to determine that N is happy, or -1 if N is not happy.

      Example

      Input:
      2
      19
      204

      Output:
      4
      -1


      1) 19 : 12 + 92 = 82
      2) 82 : 82 + 22 = 68
      3) 68 : 62 + 82 = 100
      4) 100 : 12 + 02 + 02 = 1

      The solution for 19 is 4 because we discovered that the integer 19 is happy after we repeated the process 4
      times.


      204 –> 20 –> 4 –> 16 –> 37 –> 58 –> 89 –> 145 –> 42 –> 20 –> 4 –> 16 –> 37 –> 58 –> 89 –> 145 ……..



      204 is not a happy number because after breaking it several times the results start repeating so we
      can deduce that if we continue breaking it, the result will never reach 1.


      Added by:Rofael Emil
      Date:2010-11-05
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:(modified) Egyptian Olympiad in Informatics ( EOI ) 2009, August 14 - 21, Cairo









      SPOJ Problem Set (classical)

      7772. Help a researcher

      Problem code: HLPRSRCH

      A scientist was doing a research on some kinds of bacteria. He found that the kinds, he examined, take T unit of time to grow (be mature) enough in order to can reproduce.

      Also he found that each type reproduces with a constant rate which is N new bacteria every F unit of time.

      (where F=T)

       

      Task

      write a progam that reads L (number of bacteria (at the begining of the experiment)), M (number of mature bacteria of them), T (time of each to get mature which is also the time needed for reproducing N new bacteria), N (rate of reproducing per T unit of time) and Z (period elapsed by the experiment).

      Calculate the number of bacteria after Z unit of time.Regardless of life-span

      Constraints

      1 ≤ L ≤ 5     number of bacteria (at the begining of the experiment)

      1 ≤ ML    number of mature bacteria

      1 ≤ T ≤ 5   time of each to get mature which is also the time needed for reproducing N new bacteria

      1 ≤ N ≤ 50    rate of reproducing per T unit of time

      1 ≤ Z/T ≤ 4,300    period elapsed by the experiment

      Note

      Z is always divisible by T.

      Input

      • L (number of bacteria (at the begining of the experiment))
      • M (number of mature bacteria of them)
      • T (time of each to get mature which is also the time needed for reproducing N new bacteria)
      • N (rate of reproducing per T unit of time)
      • Z (period elapsed by the experiment)

      Output

      • the number of bacteria after Z unit of time.Regardless of life-span.

      Example

      Input:
      3
      2
      3
      1
      3

      Output:
      5

      The experiment begins with 2 mature bacteria and one unmature bacterium.
      For, each of the mature bacteria reproduces after 3 units of time.
      Then th total becomes 4 -as each one got a new one (2*2)-.
      But, for the unmature bacterium after 3 units of time, it only become mature.
      After all of that the experiment finishes with 5 bacteria.


      Input
      2
      0
      1
      1
      100

      Output:
      1146295688027634168202


      Added by:Rofael Emil
      Date:2010-11-07
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7776. Kind of a blur

      Problem code: ANARC09I

      Origin and Blured Image

      Image blurring occurs when the object being captured is out of the camera’s focus. The top two figures on the right are an example of an image and its blurred version. Restoring the original image given only the blurred version is one of the most interesting topics in image processing. This process is called deblurring, which will be your task for this problem.


      In this problem, all images are in grey-scale (no colours). Images are represented as a 2 dimensional matrix of real numbers, where each cell corresponds to the  brightness of the corresponding pixel. Although not mathematically accurate, one way to describe a blurred image is through averaging all the pixels that are within (less than or equal to) a certain Manhattan distance† from each pixel (including the pixel itself ). Here’s an example of how to calculate the blurring of a 3x3 image with a  blurring distance of 1:

      How to compute

      Mahattan distance

      Given the blurred version of an image, we are interested in reconstructing the original version assuming that the image was blurred as explained above.

      Input

      Input consists of several test cases. Each case is specified on H + 1 lines. The first line specifies three non negative integers specifying the width W , the height H of the blurred image and the blurring distance D respectively where (1 ≤ W, H ≤ 10) and (D ≤ min(W/2, H/2)). The remaining H lines specify the gray-level of each pixel in the blurred image. Each line specifies W non-negative real numbers given up to the 2nd decimal place. The value of all the given real numbers will be less than 100. Zero or more lines (made entirely of white spaces) may appear between cases. The last line of the input file consists of three zeros.

      Output

      For each test case, print a W × H matrix of real numbers specifying the deblurred version of the image. Each element in the matrix should be approximated to 2 decimal places and right justified in a field of width 8. Separate the output of each two consecutive test cases by an empty line. Do not print an empty line after the last test case. It is guaranteed that there is exactly one unique solution for every test case.

      Example

      Input:
      2 2 1
      1 1
      1 1
      3 3 1
      19 14 20
      12 15 18
      13 14 16
      4 4 2
      14 15 14 15
      14 15 14 15
      14 15 14 15
      14 15 14 15
      0 0 0

      Output:
      1.00 1.00
      1.00 1.00

      2.00 30.00 17.00
      25.00 7.00 13.00
      14.00 0.00 35.00

      1.00 27.00 2.00 28.00
      21.00 12.00 17.00 8.00
      21.00 12.00 17.00 8.00
      1.00 27.00 2.00 28.00

      Added by:Race with time
      Date:2010-11-08
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ANARC 2009









      SPOJ Problem Set (classical)

      7777. National Treasure

      Problem code: ANARC09J

      The great hall of the national museum has been robbed few times recently. Everyone is now worried about the security of the treasures on display. To help secure the hall, the museum contracted with a private security company to provide additional guards to stay in the great hall and keep an eye on the ancient artifacts. The museum would like to hire the minimum number of additional guards so that the great hall is secured. The great hall is represented as a two dimensional grid of R × C cells. Some cells are already occupied with the museum’s guards. All remaining cells are occupied by artifacts of different types
      (statues, sculptures, . . . etc.) which can be replaced by new hired guards. For each artifact, few other cells in the hall are identified as critical points of the artifact depending on the artifact value, type of vault it is kept inside, and few other factors. In other words, if this artifact is going to stay in the hall then all of its critical points must have guards standing on them. A guard standing in a critical position of multiple artifacts can keep an eye on them all. A guard, however, can not stand in a cell which contains an artifact (instead, you may remove the artifact to allow the guard to stay there). Also you can not remove an artifact and leave the space free (you can only replace an artifact with a new hired guard). Surveying all the artifacts in the great hall you figured out that the critical points of any artifact (marked by a symbol) are always a subset of the 12 neighboring cells as shown in the grid below.

       

      Guard Position

      Accordingly, the type of an artifact can be specified as a non-negative integer where the i-th bit is 1 only if critical point number i from the picture above is a critical point of that artifact. For example an artifact of type 595 (in binary 1001010011) can be pictured as shown in the figure below. Note that bits are numbered from right to left (the right-most bit is bit number 1.) If a critical point of an artifact lies outside the hall grid then it is considered secure.

      Guard Position

      You are given the layout of the great hall and are asked to find the minimum number of additional guards to hire such that all remaining artifacts are secured.

      Input

      Your program will be tested on one or more test cases. Each test case is specified using R+1 lines. The first line specifies two integers (1 ≤ R, C ≤ 50) which are the dimensions of the museum hall. The next R lines contain C integers separated by one or more spaces. The j-th integer of the i-th row is -1 if cell (i, j) already contains one of the museum’s guards, otherwise it contains an integer (0 ≤ T < 212 ) representing the type of the artifact in that cell. The last line of the input file has two zeros.

      Output

      For each test case, print the following line:
      k. G
      Where k is the test case number (starting at one,) and G is the minimum number of additional guards to hire such that all remaining artifacts are secured.

      Example

      Input:
      1 3
      512 -1 2048
      2 3
      512 2560 2048
      512 2560 2048
      0 0

      Output:
      1. 0
      2. 2

      Added by:Race with time
      Date:2010-11-08
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ANARC 2009









      SPOJ Problem Set (classical)

      7778. Land Division

      Problem code: ANARC09H

      The king of the Far, Far Away Kingdom has passed-away and the kingdom must be split amongst his K sons. The kingdom, which can be drawn on a rectangular map, consists of N cities. To divide the land, they will draw K − 1 straight segments on the map, all of them parallel to either
      the vertical or the horizontal axis of the map. This divides the map into exactly K rectangles, all having equal heights (if the dividing lines where vertical), or equal widths (if the dividing lines where horizontal). No segment should pass through any of the cities. Each son will then be assigned one random region out of the K regions and the cities inside that region will be his share. Of course, they want the division to be as fair as possible: theoretically, in the fairest division, each son should get N/K cities (we’ll call this value the baseline), but since the baseline isn’t always a whole number, each of the sons wants to be as close as possible to the baseline. We will calculate the unfairness of each son as the absolute difference between the number of cities assigned to him and the baseline. The fairest division is the one that minimizes the average unfairness of all the sons.

      Land division

      Consider the example above with 3 sons and 6 cities (so the baseline is 6/3 = 2.0) Figure (a) is the original map. Figure (b) shows a non-optimal division (the dashed lines are the 2 dividing lines.) In this case, the middle region contains 3 cities (unfairness of |3 − 2| = 1), the left region contains 1 city (unfairness of |1 − 2| = 1), while the right region contains 2 cities (perfectly fair, unfairness of 0), so the average unfairness is 2/3.
      Figure (c) on the right shows the optimal division since all three regions contain the same number of cities for an average unfairness of 0. Write a program to determine the fairest land division for a given kingdom.

      Input

      Your program will be tested on one or more test cases. Each test case is described on N + 1 lines. The first line of each test case specifies two positive integers: (N ≤ 100, 000) and (K ≤ 10) where N is the number of cities and K is number of children. Note that K ≤ N . N lines follows,  each describing the coordinates of a city by specifying two integers (x, y) where 0 ≤ x, y ≤ 100, 000. Since coordinates are rounded to the  nearest integer, more than one city could have the exact same coordinate on the map. You may assume that the map of the kingdom is any rectangle that contains all of the given points (although such information is not needed by the program.) Note also that while all cities lie on integer coordinates, the dividing lines need not be. The last line of the input file contains two zeros.

      Output

      For each test case, print the following line:
      k. A/B
      Where k is the test case number (starting at one,) and A/B is the minimum average that could be obtained. A/B should be an irreducible fraction. Let B=1 when the result is a whole number.

      Example

      Input:
      6 3
      0 4
      1 3
      2 3
      3 1
      4 4
      5 0
      4 3
      0 0
      0 1
      1 1
      1 0
      0 0

      Output:
      1. 0/1
      2. 8/9

      Added by:Race with time
      Date:2010-11-08
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ANARC 2009









      SPOJ Problem Set (classical)

      7779. Stock Chase

      Problem code: ANARC09G

      I have to admit, the solution I proposed last year for solving the bank cash crisis didn’t solve the whole economic crisis. As it turns out, companies don’t have that much cash in the first place. They have assets which are primarily shares in other companies. It is common, and acceptable, for one company to own shares in another. What complicates the issue is for two companies to own shares in each other at the same time. If you think of it for a moment, this means that each company now (indirectly) controls its own shares.

      New market regulation is being implemented: No company can control shares in itself, whether directly or indirectly. The Stock Market Authority is looking for a  computerized solution that will help it detect any buying activity that will result in a company controlling its own shares. It is obvious why they need a program to do so, just imagine the situation where company A buying shares in B, B buying in C, and then C buying in A. While the first two purchases are acceptable. The third purchase should be rejected since it will lead to the three companies controlling shares in  themselves. The program will be given all purchasing transactions in chronological order. The program should reject any transaction that could lead to one company controlling its own shares. All other transactions are accepted

      Input

      Your program will be tested on one or more test cases. Each test case is specified on T + 1 lines. The first line specifies two positive numbers: (0 < N ≤ 234) is the number of companies and (0 < T ≤ 100, 000) is the number of transactions. T lines follow, each describing a buying transaction. Each transaction is specified using two numbers A and B where (0 < A, B ≤ N ) indicating that company A wants to buy shares in company B. The last line of the input file has two zeros.

      Output

      For each test case, print the following line:
      k. R
      Where k is the test case number (starting at one,) R is the number of transactions that should be rejected.

      Example

      Input:
      3 6
      1 2
      1 3
      3 1
      2 1
      1 2
      2 3
      0 0
      Output: 1. 2

      Added by:Race with time
      Date:2010-11-08
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ANARC 2009









      SPOJ Problem Set (classical)

      7782. Largest Labeled Common Ancestor

      Problem code: LLCA

      Given a labeled complete k-ary tree, find the largest labeled common ancestor of two given nodes. In a complete k-ary tree, the node in the tree is labeled sequentially from the left most child to right most child, level by level. Largest labeled common ancestor of A and B is defined as the largest labeled node in the tree which has A and B as descendants. A node is a descendant of itself.

      Be careful with your finger, the source limit is 256 bytes.

      Input

      The first line of input contains an integer T (1 <= T <= 100) the number of cases. Each cases contains three integers K, A and B (2 <= K <= 100; 1 <= A,B <= 2,000,000,000).

      Output

      For each test case, output in a line the largest labeled common ancestor node.

      Example

      Input:
      


      4
      3 42 7
      2 2 6
      2 1 105
      4 10 13

      Output:


      2
      1
      1
      3

      Whitespace Explanation:
      If there no input in any line, then the output for that line is a blank line :)) Sorry for inconvenience. >:)

      Added by:Lukmanul Hakim
      Date:2010-11-08
      Time limit:1s
      Source limit:256B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM-ICPC Indonesia National Contest 2010, Problem B









      SPOJ Problem Set (classical)

      7783. Commuting Functions

      Problem code: COMFUNC


       

      Two functions f and g (f, g: X → X) are commuting if and only if f(g(x)) = g(f(x)) for each x in X.
      For example, functions f(x) = x + 1 and g(x) = x − 2 are commuting, whereas functions f(x) = x + 1
      and g(x) = 2x are not commuting.
      Each function h (h: N_n → N_n, where N_n = 1, 2, ..., n and n is positive integer) can be represented as a
      value list — a list in which the i-th element is equal to h(i). For example, a function h(x) = ceil(x/2) from
      N_5 to N_5 has the value list [1, 1, 2, 2, 3].
      The value lists are ordered lexicographically: list [a1 ... an] is smaller than list [b1 ... bn] if and only if
      there exists such an index k that a_k < b_k, and a_l = b_l for any index l < k.
      The function f (f: X → X) is bijective if for every y in X, there is exactly one x in X such that
      f(x) = y.
      Given a bijective function f (f: N_n → N_n, n is positive integer), find the function g that is commuting
      with f and has the lexicographically smallest possible value list.

       

      Two functions f and g (f, g: X → X) are commuting if and only if f(g(x)) = g(f(x)) for each x in X. For example, functions f(x) = x + 1 and g(x) = x − 2 are commuting, whereas functions f(x) = x + 1 and g(x) = 2x are not commuting.

       

      Each function h (h: Nn → Nn, where Nn = {1, 2, ..., n} and n is positive integer) can be represented as a value list — a list in which the i-th element is equal to h(i). For example, a function h(x) = ceil(x/2) from N5 to N5 has the value list [1, 1, 2, 2, 3].

       

      The value lists are ordered lexicographically: list [a1 ... an] is smaller than list [b1 ... bn] if and only if there exists such an index k that ak < bk, and al = bl for any index l < k.

       

      The function f (f: X → X) is bijective if for every y in X, there is exactly one x in X such that f(x) = y.

       

      Given a bijective function f (f: Nn → Nn, n is positive integer), find the function g that is commuting with f and has the lexicographically smallest possible value list.

       

       

      Input

      The first line of the input file contains the number of test cases. Each test case is described by a line containing a single integer number n — the number of the elements in the value list of a bijective function f (1 ≤ n ≤ 200000), followed by another line which contains the value list of the function f.

      Output

      For each test case, output a single line containing n integer numbers — the value list of function g that commutes with the function f and has the lexicographically smallest value list.

      Example

      Input:
      2
      10
      1 2 3 4 5 6 7 8 9 10
      10
      2 3 4 5 6 7 8 1 9 10
      
      Output:
      1 1 1 1 1 1 1 1 1 1
      1 2 3 4 5 6 7 8 9 9
      

      Added by:Fidel Schaposnik
      Date:2010-11-08
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC 2010, NEERC, Northern Subregional Contest









      SPOJ Problem Set (classical)

      7804. Defense of a Kingdom

      Problem code: DEFKIN

       

      Theodore implements a new strategy game “Defense of a Kingdom”. On each level a player defends the
      Kingdom that is represented by a rectangular grid of cells. The player builds crossbow towers in some
      cells of the grid. The tower defends all the cells in the same row and the same column. No two towers
      share a row or a column.
      The penalty of the position is the number of cells in the largest undefended rectangle. For example, the
      position shown on the picture has penalty 12.
      [IMAGE]
      Help Theodore write a program that calculates the penalty of the given position.

       

      Theodore implements a new strategy game “Defense of a Kingdom”. On each level a player defends the Kingdom that is represented by a rectangular grid of cells. The player builds crossbow towers in some cells of the grid. The tower defends all the cells in the same row and the same column. No two towers share a row or a column.

       

      The penalty of the position is the number of cells in the largest undefended rectangle. For example, the position shown on the picture has penalty 12.

       

      This position has a penalty of 12.

       

      Help Theodore write a program that calculates the penalty of the given position.

       

       

      Input

       

      The first line of the input file contains the number of test cases.

       

      Each test case consists of a line with three integer numbers: w — width of the grid, h — height of the grid and n — number of crossbow towers (1 ≤ w, h ≤ 40 000; 0 ≤ n ≤ min(w, h)).

       

      Each of the following n lines contains two integer numbers xi and yi — the coordinates of the cell occupied by a tower (1 ≤ xi ≤ w; 1 ≤ yi ≤ h).

       

       

      Output

       

      For each test case, output a single integer number — the number of cells in the largest rectangle that is not defended by the towers.

       

       

      Example

      Input:
      1
      15 8 3
      3 8
      11 2
      8 6
      
      Output:
      12
      

      Added by:Fidel Schaposnik
      Date:2010-11-08
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC 2010, NEERC, Northern Subregional Contest









      SPOJ Problem Set (classical)

      7805. Kitchen Robot

      Problem code: KITROB

      Robots are becoming more and more popular. They are used nowadays not only in manufacturing plants, but also at home. One programmer with his friends decided to create their own home robot. As you may know most programmers like to drink beer when they gather together for a party. After the party there are a lot of empty bottles left on the table. So, it was decided to program robot to collect empty bottles from the table.

      The table is a rectangle with the length l and width w. Robot starts at the point (xr, yr) and n bottles are located at points (xi, yi) for i = 1, 2, ..., n. To collect a bottle robot must move to the point where the bottle is located, take it, and then bring to some point on the border of the table to dispose it. Robot can hold only one bottle at the moment and for simplicity of the control program it is allowed to release bottle only at the border of the table.

       

      Example

       

      You can assume that sizes of robot and bottles are negligibly small (robot and bottles are points), so the robot holding a bottle is allowed to move through the point where another bottle is located. One of the subroutines of the robot control program is the route planning. You are to write the program to determine the minimal length of robot route needed to collect all the bottles from the table.

       

      Input

      The first line of the input file contains T, the number of test cases. T test cases follow.

      The first line of each test case contains two integer numbers w and l — the width and the length of the table (2 ≤ w, l ≤ 1000).

      The second line contains an integer number n — the number of bottles on the table (1 ≤ n ≤ 18). Each of the following n lines contains two integer numbers xi and yi — coordinates of the i-th bottle (0 < xi < w; 0 < yi < l). No two bottles are located at the same point.

      The last line of the test case contains two integer numbers xr and yr — coordinates of the robot’s initial position (0 < xr < w; 0 < yr < l). Robot is not located at the same point with a bottle.

       

      Output

      For each test case, output the length of the shortest route of the robot. Your answer should be accurate within an absolute error of 10-6.

       

      Example

      Input:
      1
      3 4
      2
      1 1
      2 3
      2 1
      
      Output:
      5.60555127546399
      

      Added by:Fidel Schaposnik
      Date:2010-11-09
      Time limit:150s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC 2010, NEERC, Northern Subregional Contest









      SPOJ Problem Set (classical)

      7807. The Lucky Prisoner

      Problem code: LPRISON

      (Maybe) someday there is a planet used to jail much prisoners from universe. One time, the prison manager collects all of prisoners, with handcuff in their hand locked. He orders to officers to unlock all handcuffs. Then, he orders to officers to look at prisoners whose number can divided by two. If his/her handcuff is locked, the open it, otherwise, lock it. Then, he orders again to all officers to look at prisoners whose number can divided by three, and so on.

      You, the universe criminal researcher, is requested to calculate the environmental criminal impact by calculating ratio of freed prisoners about all prisoners to the number of prisoners are known.

      Input

      Line 1 contains one integer T (1 <= T <= 100) number of test cases. Then T next lines contains one number K (1 <= K <= 101000), the number of prisoners.

      Output

      Output contains K lines, contains the probability of freed prisoners about all prisoners. the probabilty accuration is 10-500 with bankers' rounding method.

      Example

      Input:


      2
      5
      100

      Output (splitted to readibility) :
      0.40000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      0.10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

      Whitespace Explanation:

      If there no input in any line, then do not print any line :)) Sorry for inconvenience. >:)

      Added by:Lukmanul Hakim
      Date:2010-11-09
      Time limit:20s-60s
      Source limit:1024B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:My Own Problem









      SPOJ Problem Set ()

      7809. Cow Photographs

      Problem code: COWPIC

      Farmer John wants to take a picture of his entire herd of N (1 <= N <= 100,000) cows conveniently numbered 1..N so he can show off to his friends.

      On picture day, the cows run to form a single line in some arbitrary order with position i containing cow c_i (1 <= c_i <= N). Farmer John has his own ideas about how the cows should line up.

      FJ thinks cow i may stand only to the left of cow i+1 (for all i, 1 <= i <= N-1) and that cow N may only stand to the left of Cow 1.  Of course, no cow will stand to the left of the first (leftmost) cow in the line.

      The cows are hungry for the promised post-photo dinner, so Farmer John wants to take the picture as quickly as possible. Cows are not great at following directions, so he will only choose a pair of adjacent cows and have them switch places once per minute. How quickly is Farmer John able to get them into some acceptable order?


      Consider a set of 5 cows whose initial lineup looks like this:

           Left           Right
              3  5  4  2  1

      He can first swap the second pair of cows:

              3  4  5  2 1

      and then swap the rightmost pair:

              3  4  5  1  2

      to yield an acceptable lineup that required but two minutes of cow swapping.

      Input

      Line 1: A single integer: N
      Lines 2..N+1: Line i+1 contains the number of the i-th cow in line: c_i

      Output

      Line 1: The minimum amount of time, in minutes, that it takes Farmer John to get the cows into some appropriate order.

      Example

      Input:
      5
      3
      5
      4
      2
      1

      Output:
      2

      Added by:Iqram Mahmud
      Date:2010-11-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:USACO November 2010









      SPOJ Problem Set (classical)

      7826. Tree Isomorphism

      Problem code: TREEISO


      Given two undirected trees T1 and T2 with equal number of vertices N (1 ≤ N ≤ 100,000) numbered 1 to N, find out if they are isomorphic.

      Two trees T1 and T2 are isomorphic if there is a bijection f between the vertex sets of T1 and T2 such that any two vertices u and v of T1 are adjacent in T1 if and only if f(u) and f(v) are adjacent in T2.

      Input

      The first line of input contains the number of test cases nTest (1<= nTest <= 400). Each test case contains:

      • The first line contains the number of nodes N.
      • Each of next N-1 lines contain two integers A, B, denoting that there is an edge in T1 between nodes A and B (1 ≤ A, B ≤ N).
      • Each of next N-1 lines contain two integers A, B, denoting that there is an edge in T2 between nodes A and B (1 ≤ A, B ≤ N).

      The sum of N over all test cases will not exceed 100,000.

      Output

      For each test case print YES if T1 and T2 are isomorphic and NO otherwise. 

      Example

      Input:
      2
      4
      4 2
      4 1
      2 3
      4 2
      2 3
      4 1
      5
      3 4
      3 2
      3 5
      3 1
      3 4
      4 2
      2 5
      2 1 Output: YES
      NO

      Added by:Andrey Naumenko
      Date:2010-11-10
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7851. Stacks of Zippy

      Problem code: JZPSTA


      Recently Zippy recieved four stacks, named A B C D respectively. Firstly, there are n elements in stack A (the element sequence is a permutation of 1..n), and stack B C D are empty. He can do four types of operations:

      operation a: push the top element of stack A to stack B (if stack A is not empty, this operation can be done)

      operation b: push the top element of stack B to stack D (if stack B is not empty, this operation can be done)

      operation c: push the top element of stack A to stack C (if stack A is not empty, this operation can be done)

      operation d: push the top element of stack C to stack D (if stack C is not empty, this operation can be done)

      He can do 2*n operations in total. Obviously, there are n elements in stack D after he did the 2*n operations. Then he take out the top element in stack D one by one. If the first element he takes out is n, the second is n-1, ... , the last is 1, he will be very happy. Also, he wants to make the operation sequence he did lexicographic smallest.

      Input
      First line is a number t, which is the number of testcases. 
      The following t lines, each line contains a integer n, which is the number of sectors. (5<=n<=10^18)
      Then following t testcases. For each test case, the first line contains a number n, which denotes the number of the elements in stack A. The second line contains n numbers, separated by a space, which are the elements in stack A, from top to the bottom.
      Output
      For each case, output a line. If there exists an answer, output the lexicographic smallest one. If not, output 0.
      Example
      Input:
      2
      4
      1 3 4 2
      4
      2 3 4 1
      Output:
      a b a c a b b d
      0Zippy jumps for years, and finally knows that jump is very boring. Then he found out a new way to 

      Input

      First line is a number t, which is the number of testcases. 

      Then following t testcases. For each test case, the first line contains a number n, which denotes the number of the elements in stack A. The second line contains n numbers, separated by a space, which are the elements in stack A, from top to the bottom.

      You can be sure that the sum of all n does not exceed 200000, and each n is not bigger than 100000.

      Output

      For each case, output a line. If there exists an answer, output the lexicographic smallest one (the operations Zippy does, separated by a space). If not, output 0.

      Example

      Input:
      2
      4
      1 3 4 2
      4
      2 3 4 1

      Output:
      a b a c a b b d
      0

      Previous testdata wrong. All submissions have been rejudged. Sorry for inconvenience.   (2011.10.5)


      Added by:sevenkplus
      Date:2010-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CNOIP2008 && POI17









      SPOJ Problem Set (classical)

      7857. Tower Game (Hard)

      Problem code: ADV04A1

      Daniel is building towers out of blocks. He has many black and white blocks. He has built n towers out of those. Now he suggests Max playing the following game. Black block will belong to Daniel and white blocks will be Max's blocks. During his turn the player can take any of his blocks from any tower and remove it and all the blocks above it. As usual the player who can't make the move loses. Daniels make the first move. Determine who will win if both players play optimally.

      Input

      The input starts with number t - the amount of test cases. The first line of each test is number n - the number of towers. Then n strings follow. Each string is formed of 'B' and 'W' characters, where 'B' means bleck block and 'W' - white block. Each string describes one tower from bottom to top.

      Constraints

      1 <= t <= 20
      1 <= n <= 1000
      String consist of no less than 1 character and no more than 1000 characters.

      Output

      For each test case print 'Win' if Daniel wins and 'Loss' if Max wins given both players play optimally.

      Example

      Input:
      1
      5
      BBWWB
      BWBB
      BB
      WWW
      WB
      
      Output:
      Win
      
      

      Beware! Much input data.


      Added by:Spooky
      Date:2010-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      7859. Upper Right King (Hard)

      Problem code: ADV04B1

      There is a king in the lower left corner of the n × n checkmate board. The king can move one step right, one step up or one step up-right. How many ways are there for him to reach the upper right corner of the board?

      Input

      The first line of input contains number T - the amount of test cases. Next T lines consist of single integer n - the size of the board.

      Constraints

      1 <= T <= 10000
      1 <= n <= 1000000

      Output

      For each test case output the munber of ways to reach upper right corner of n × n board modulo 1000003.

      Example

      Input:
      2
      2
      3
      
      Output:
      3
      13
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set (classical)

      7860. Deal or No Deal

      Problem code: ADV04C

      Deal or No Deal is played in many different ways around the world. Many different countries have their own version or versions of the show, each with their own twists on the same general format. The general format is the following.

      The game revolves around the opening of a set of numbered briefcases, each of which contains a different prize (cash or otherwise). The contents of all of the cases are known at the start of the game, but the specific location of any prize is unknown. The value of each of the cases is indicated by a label or card sealed within it. The contestant claims (or is assigned) a case to begin the game. The case's value is not revealed until the conclusion of the game.

      The contestant then begins choosing cases to be removed from play. The amount inside each choice is immediately revealed; by process of elimination, the amount revealed cannot be inside the player's chosen case. Throughout the game, after a predetermined number of cases have been opened, the banker offers the contestant an amount of money and/or prizes to quit the game, the offer based roughly on the amounts remaining in play and the contestant's demeanor. The player then answers the titular question, choosing:

      • "Deal", accepting the offer presented and ending the game, or
      • "No Deal", rejecting the offer and continuing the game.

      This process of removing cases and receiving offers continues, until either the player accepts an offer to 'deal', or all offers have been rejected and the values of all unselected cases are revealed. The player wins the value of the deal taken, or if no deal is taken, the contents of the player's case.

      For the sake of this problem we will consider that the banker offers are deal before each removing of cases. Also we will assume that banker follows the particular model of contestants behaviour which is - if the banker offers the contestant the prize x the probability that the contestant accepts the deal is:

      ,

      where min and max are the minimum and maximum prizes left in the game respectively. The banker wants to minimize the expexted prize the contestant wins. Help the banker calculate the expected prize the contestant is going to win if the banker offers optimal deals.

      Input

      The first line of input is n - the number of briefcases. Next lines consists of n integers a1, a2, …, an - the prizes in the briefcases. Number q follows - the amount of situations the banker needs to evaluate. The description of each sitation follows: k – the number of prizes still in the game; b1, b2, …, bk – the prizes themselves.

      Constraints

      2 <= n <= 16
      1 <= q <= 100
      2 <= k <= n
      1 <= ai, bi <= 106

      Output

      For each situation print the expected prize the contestant is going to win and also the optimal deal the banker should offer. Both numbers should be printed with two digits after the dot.

      Example

      Input:
      4
      10 20 30 40
      4
      2 10 20
      2 20 30
      2 40 10
      4 20 30 10 40
      
      Output:
      14.59 12.66
      24.59 22.66
      23.76 17.99
      22.40 17.08
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      7861. UFO

      Problem code: ADV04D

      There is a UFO in the form of the disc of radius r. Currently its center is in point A and it needs to move its center to point B as soon as possible. But the tricky inhabitants of the Earth are starting to suspect something, so they have built a redar in point C with a range of R, which is able to detect a UFO, if any part of it will be in the range. Because of the special features of the UFO it cannot change its height and always maintain vertical alignment. Determine the shortest path for the UFO to reach its destination not being caught by the radar.

      Input

      The first line of input contains number T — the amount of test cases. Next T line consist of eight integers each xA, yA, xB, yB, xC, yC, r and R — the coordinates of points A, B, C and radii of the UFO and radar coverage. It is guaranteed that the UFO won't be within the radar coverage in points A and B.

      Constraints

      1 <= T <= 1000
      -1000 <= xA, yA, xB, yB, xC, yC, r, R <= 1000

      Output

      For each test case output a real number which is the shortest UFO path with two decimals after the dot.

      Example

      Input:
      1
      0 0 8 0 4 0 1 1
      
      Output:
      9.02
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set ()

      7862. Prisoner of Benda

      Problem code: ADV04E

      Daniel enjoys watching TV series. One of his favourite is Futurama. One episode has the following plot.

      Professor Farnsworth switches bodies with Amy using a new invention so that he can relive his youth. Likewise, Amy is reminiscent of her younger days of constantly eating and wishes to use the Professor's skinny body to gorge herself with food once again. Later, they find they cannot switch their bodies back with each other, because the device will not operate on the same pairing of bodies. The Professor thoughtlessly suggests they might be able to switch back to their original bodies with a third person. Bender switches bodies with the Professor (Amy's body) so he can perform a robbery without being identified. After realizing his mistake, the Professor, now in Bender's body, tires of trying to solve the problem. He decides to live a life of daring stunts and joins a robot circus. Bender, now in Amy's body, is caught aboard the yacht of Robo-Hungarian emperor Nikolai. When Bender states that he is really a robot who has switched bodies with a human, Nikolai reveals that he feels trapped by his wealth and wishes to live the life of a normal, "peasant" robot. Bender tricks him into switching bodies with a robot wash bucket and inhabits Nikolai's body, planning to live like an emperor. However, he discovers that Nikolai's fiancée and first officer are plotting to kill him. Bender is saved with the assistance of the Professor and the circus' loyal Robo-Hungarian citizens. Meanwhile, Leela switches bodies with Amy, thus inhabiting the Professor's body, when she comes to believe that Fry only loves her for her beauty. In order to beat Leela at her own game, Fry switches bodies with Dr. Zoidberg in an attempt to repulse Leela. This leads them to one-up each other using various disgusting acts while on a date, which climaxes when the two have sex with each other in their equally grotesque bodies, and reconcile. During this time, Amy has overeaten in Leela's body, making it overweight. She switches bodies with Hermes, so she can continue eating while Hermes slims Leela's body back down. While eating, she witnesses Fry and Leela making out in the Professor and Dr. Zoidberg's bodies and loses her appetite for food. Concurrently, Zoidberg and Nikolai, in the respective bodies of Fry and the robot wash bucket, become friends and attempt to assume the lives of Fry and Bender, blowing up their apartment in the process. The bucket, now in Amy's body, professes its love to Scruffy the Janitor, but he turns it away. Finally, two Globetrotters, Ethan "Bubblegum" Tate and "Sweet" Clyde Dixon, mathematically prove that everyone's minds can be restored using two additional bodies and then successfully do so, with themselves as the extras.

      We need to replicate how they have accomplished this. We will consider that a certain amount of body switches already took place. We need to determine the sequence of switches after which everyone is in self body, using no more than two extra bodies. Don't forget that two specific bodies can be mind switched only once.

      Input

      The first line of input contains t - the number of test cases. The description of tests follows. The first line of each test is numbers n - the numbre of characters and m - the number of body swtiches already taken place. Next m lines contain the description of switches. Let us mark all bodies with numbers from 1 to n. Then each switch is defined by two numbers a, b - the numbers of bodies used in the switch. The switches are listed chronologically.

      Constraints

      1 <= t <= 50
      2 <= n <= 200
      1 <= m <= n(n-1)/2
      1 <= a, b <= n

      Output

      Print the number of switches needed to return everyone to their own bodies in the first line of the output. Then you should print the switches themselves in the order they should be performed. The format should be the same as in the input data. You can output any valid solution. However you shouldn't use more than two extra bodies. The extra bodies should be marked as n+1 and n+2. After all the switches the extra characters should be in their own bodies as well. Also you can't use more than 3n swtiches.

      Example

      Input:
      1
      2 1
      1 2
      
      Output:
      5
      1 3
      2 4
      2 3
      1 4
      3 4
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      7864. Four Chips (Hard)

      Problem code: ADV04F1

      There is a n × 1 board. Its cells are numbered with integers from 1 to n. First four cells have indistinguishable chips in them. In one turn you can move one chip to the neighbouring cell or move it symmetrically relatively any other chip (i.e. if you move a chip in cell 10 symmetrically relative to the chip in cell 13 it will end up in cell 16), given that the chip won't leave the board and each cell will have no more than one chip. You need to determine the minimum number of turns needed to reach a certain configuration of chips.

      Input

      The first line of input contains number T - the amount of test cases. Next T lines consist of four integers a1, a2, a3 and a4 — the numbers of cells where the chips should be in the final configuration.

      Constraints

      1 <= T <= 10000
      1 <= a1 < a2 < a3 < a4 <= n
      n = 70

      Output

      For each test case print single integer - the answer to the problem in the statement.

      Example

      Input:
      2
      1 2 3 4
      1 3 4 6
      
      Output:
      0
      1
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      7866. Regular expressions (Hard)

      Problem code: ADV04G1

      Regular expression is an expression which defines a set of strings. In this problem regular expression will contain only small latin letters a-z and special characters ‘?’, ‘*’ и ‘+’. Each letter corresponds to itself in the defined strings. Special character can occur only after some letter and means the number of repetitions of the letter:

      CharacterRepetitions
      ?none or one
      *none or more
      +one or more

      For example “ac”, “abc”, “acc”, “abcccc”, and so on match regular expression “ab?c+”. For the given string find the substring which matches the given regular expression. If there are many such substrings find the most left one. If there are many of those as well fing the longest one.

      Input

      The first line of input contains number T - the amount of test cases. The description of T test cases follows. The first line of each test case is the given string S of length L. Next line contains number n - the amount of regular expressions. Next n lines describe one regular expression Ri each for which you should find the matching substrings.

      Constraints

      1 <= T <= 100
      1 <= n <= 10
      1 <= L <= 200
      1 <= Ri <= 100

      Output

      For each regular expression print the matching substring or -1 if there is no such substring in the given string.

      Example

      Input:
      1
      aabbcc
      5
      b*c
      a?b+c+
      ab?c
      b?c?
      a?b?c?
      
      Output:
      bbc
      abbcc
      -1
      
      a
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6 TCL
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set (classical)

      7868. Join

      Problem code: ADV04H

      There are two tables. These tables are filled with numeric data. Each column of each table has a unique name. You need to implement JOIN operation for those tables. JOIN creates a new result table by combining column values of the two tables based upon the join-predicate. The query compares each row of the first table with each row of the second to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of the table are combined into a result row. The result of the join can be defined as the outcome of first taking the Cartesian product of all records in the tables (combining every record in the first table with every record in the second table) - then return all the records which satisfy the join predicate. After that needed column are picked and printed as the result. Moreover the resulting rows should be output in the lexicographic order.

      Input

      The input starts with the description of the first table. The first line consists of k1 names of the columns of the table separated with spaces. All the names contain only small latin letters and digits. Next line contain number n1 – the amount of records in the table. In each of the next n1 lines there are k1 integers – data written in the table. The description of the second table in the same format follows. Next line is number q – the amount of queries. The description of each query follows in the following format:

      SELECT <list of the names of columns>
      JOIN ON <a name of the column from the first table>=<a name of the column of the second table>
      

      Constraints

      2 <= k1, k2 <= 10
      1 <= n1, n2 <= 50000
      All the integers in the tables are positive and less than 100000.
      1 <= q <= 10

      Output

      For each query print the result of JOIN operation. You should print only the columns given in the query and in the appropriate order. The rows should be ordered lexicographically. The result of each query won't contain more than 50000 records. Print blank line after the answer for each query. See the example for more information.

      Example

      Input:
      id1 a b
      4
      1 2 3
      2 2 3
      3 2 4
      2 4 4
      id2 c d
      3
      3 3 3
      5 2 1
      1 3 4
      3
      SELECT a,b,c
      JOIN ON id1=d
      SELECT id1,d
      JOIN ON a=c
      SELECT id2,id1,d
      JOIN ON b=c
      
      Output:
      a b c
      2 3 2
      2 4 3
      
      id1 d
      1 1
      2 1
      3 1
      
      id2 id1 d
      1 1 4
      1 2 4
      3 1 3
      3 2 3
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:4s-8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set ()

      7870. Invisible point

      Problem code: ADV04J

      Daniel marked a point on a plane with sympathetic ink and he has also drawn a regular n-gon with normal ink. Max can see the n-gon, but can't see the point. Max can draw a line and ask Daniel which side of the line the point is. What is the minimum number of questions Max have to ask to define if the point is inside the n-gon in the worst case?

      Input

      First line of the input contains number t - the amount of test cases. Each test consists of the single integer n - the amount of sides of the n-gon.

      Constraints

      1 <= t <= 100
      3 <= n <= 1000000

      Output

      For each test case print a single number - the anwer to the questiong in the statement.

      Example

      Input:
      1
      4
      
      Output:
      3
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      7874. Calculator

      Problem code: ADV04K

      Once little Petya was learning positional numeral systems. Using such systems the numbers are represented as the sequence of digits

      an an−1 … a2 a1 a0
       = 
      n
      k=0
       ak bk,

      where b is the base of the numeral system, and 0 <= ak < b. Petya was dissapointed that one can represent only non-negative numbers this way. But then he found out that there are systems with negative base such as negabinary system in which b = −2, ak ∈ {0, 1}. One can represent any integer in this system for example 1110−2 = −6. Moving the idea further Petya came up with his own base b using which he could represent even more numbers given ak ∈ {0, 1}. However performing arithmetic operations in this non-standard system turned to be rather difficult. Help Petya implement a calculator for his numeral system.

      Input

      The first line of input is number T - the amount of test cases. Next T lines contain the description of arithmetic expression consisting of two operands and an opertaion separated with spaces. Both operands consist of one ‘0’ and ‘1’ digits and have the length of no more than 100. Operation is one of ‘+’, ‘-’ or ‘*’.

      Constraints

      1 <= T <= 1000

      Output

      For each test case output a number which is the result of evaluating the given expression.

      Example

      Input:
      5
      11 - 11
      1 + 1
      1100 * 1100
      1101 - 11
      111 * 1
      
      Output:
      0
      1100
      111010000
      111010110
      111
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set (classical)

      7875. Miles and kilometers

      Problem code: ADV04L

      If you are travelling a lot you could have met the following problem: different countries use different measurement systems. Notably there are two major measurement systems for distances: metric and imperial. Metric system exploits kilometers while miles are used in the imperial system. It is known that one mile is approximately 1.609 kilometers. By interesting coincidence this is close enough to the value of the golden ration which is about 1.618. On this basis there is an interesting way of converting miles to kilometeres. Let's look into Fibonacci sequence: F1 = F2 = 1, Fn = Fn−1 + Fn−2, для n > 2. The ratio of two successive Fibonacci numbers Fn+1/Fn tends to golden ration as n tends to infinity. So you can partition the amount of miles you have into Fibonacci numbers, and you should use as large Fibonacci numbers as possible, then for each element in the partition you should go to the next Fibonacci number and sum up the elements again. That way you will get the approximate amount of kilometers. For example, 40 ⇒ 34 + 5 + 1 ⇒ 55 + 8 + 2 ⇒ 65. That means that 40 miles is approximately 65 kilometers (more precise value is 64,37 kilometers). Write a program that implements this method.

      Input

      The first line of input contains number t – the amount of test cases. The description of t test cases follows. Each test consists of a single integer m - the amount of miles.

      Constraints

      1 <= t <= 10000
      1 <= m <= 10^15

      Output

      For each test case output the amount of kilometers calculated using the method given in the statement.

      Example

      Input:
      4
      1
      7
      40
      128
      
      Output:
      2
      11
      65
      207
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/









      SPOJ Problem Set (classical)

      7881. Ljutnja

      Problem code: C1LJUTNJ

      Children in a kindergarten have received a large sack containing M candies. It has been decided that the candies are to be distributed among N children.

      Each child has stated the number of candies that it wants. If a child isn’t given the amount of candy it wants, it will get angry. In fact it’ll get angrier for each candy it is deprived of. Some speculate that it’s anger will be equal to the square of the number of candy it is deprived of. For instance, if Mirko states that he wants 32 candies but receives only 29, he would be missing 3 candies, so his anger would be equal to 9.

      Unfortunately, there is an insufficient amount of candy to satisfy all children. Therefore, the candies should be distributed in such a way that the sum of the children’s anger is minimal.

      Input

      The first line contains two integers, M (1 ≤ M ≤ 2.109) and N (1 ≤ N ≤ 100 000).

      The following N lines contain integers (one per line) which represent the wishes of the children. Those numbers are all strictly less than 2.109, and their sum always exceeds M.

      Output

      The first and only line of output must contain the minimum sum of the children’s anger.

      Note: The test cases will ensure that the result fits in a 64-bit unsigned integer: int64 in Pascal, long long in C/C++, long in Java.

      Example

      Input:
      5 3
      1
      3
      2
      Output:
      1

      Input:

      10 4
      4
      5
      2
      3

      Output:

      4

      Added by:Race with time
      Date:2010-11-14
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2010-2011 1-st Round









      SPOJ Problem Set (classical)

      7882. Tabovi

      Problem code: C1TABOVI

      Zvonkec is yet another programmer employed in a small company. Every day he has to refactor one file of source code. Much to his dismay, the source is usually far from being clear and tidy. He is especially bothered by uneven indentation, i.e. the number of tabulators (tabs) indenting each line.

      Fortunately, his editor has a command to select a group of consecutive lines and add or delete a character from the start of each one. Help  Zvonkec tidy up the code as quickly as possible.

      You are given the number of lines N, a sequence specifying the current number of tabs at the start of each line, and a sequence specifying the required number of tabs at the start of each line.

      Zvonkec can execute any number of commands consisting of:

      ● selecting any number of consecutive lines
      ● adding or deleting a single tab to/from the front of each of the selected lines

      The two actions above comprise a single command, regardless of the number of selected lines. It should be noted that it is forbidden to delete more tabs from a line than are actually present at the start of a line, as the editor would start deleting characters other than tabs.

      You are asked to calculate the minimum number of commands required to tidy up the code.

      Input

      The first line of input contains a positive integer N (N ≤ 1000).

      The second line contains a sequence of N integers Pi (0 ≤ Pi ≤ 80), specifying the number of tabs at the start of i-th line before any editing.

      The third line contains a sequence of N integers Ki (0 ≤ Ki ≤ 80), specifying the number of tabs that Zvonkec would like at the start of i-th line.

      Output

      The first and only line of output must contain the required number, as specified in the problem statement.

      Example

      Input:
      3
      3 4 5
      6 7 8

      Output:
      3

      Input:

      4
      1 2 3 4
      3 1 1 0

      Output:

      6

      Input:

      4
      5 4 5 5
      1 5 0 1

      Output:

      10


      Added by:Race with time
      Date:2010-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2010-2011 1-st Round









      SPOJ Problem Set (classical)

      7884. Crni

      Problem code: C2CRNI

      Even though he has found all the most amusing rides, Mirko‟s enthusiasm still isn‟t fading. He opened his graph paper notebook and started colouring squares, and a new, even harder problem dawned on him.

      You are given a square table consisting of N rows by N columns. Each cell is either black or white. A set of cells forming a rectangle, with horizontal and vertical edges following cell borders, shall be called a black rectangle if all cells inside the rectangle are black and it consists of at least two cells.

      (IMAGE)

      The left image shows two rectangles which are not black rectangles. The rectangle labelled 1 is not a black rectangle because it contains a white cell, and the rectangle labelled 2 is not a black rectangle because it consists of only one cell. On the other hand, the right image shows three valid black rectangles.

      Calculate the number of possible selections of two black rectangles that have no common cells. As the required number can be extremely large, you should output the remainder of dividing that number by 10 007.

      Input

      The first line of input contains the integer N (2 ≤ N ≤ 1000).

      Each of the next N lines contains a single row of the table, consisting of N symbols. The symbol 'C' represents a black cell, while 'B' represents a white cell.

      Output

      The first and only line of output must contain the remainder of dividing the required number by 10 007.

      Example

      Input:
      2
      CC
      CC

      Output:
      2

      Input:

      3
      CCB
      CCB
      CBB

      Output:
      5

      Input:

      5
      BCCBB
      BBCBB
      BCCBB
      BBBBB
      CCBBB

      Output:
      8

      Added by:Race with time
      Date:2010-11-14
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2010-2011 2-nd Round









      SPOJ Problem Set (classical)

      7886. Boards (Hard)

      Problem code: ADV04I1

      Super Board Games Inc. is a big company producing board games. A new game was invented within it which may become very popular. A board divided into square cells is required for this game. Left and lower borders of the board should be level and the height of columns of cells should not increase from left to right. Also the board must be entirely paveable with dominoes. After it was found out that the game is the most interesting when played on the board consisting of n cells, it has been decided to release as many versions of the game using different n-cell boards as possible. Help the company count the number of different boards that can be released.

      Input

      The first line of input is number T - the amount of test cases. Each test is a single integer n - the number of cells.

      Constraints

      1 <= T <= 100
      1 <= n <= 100

      Output

      For each test case output the answer to the problem in the statement.

      Example

      Input:
      3
      2
      3
      4
      
      Output:
      2
      0
      5
      
      

      Added by:Spooky
      Date:2010-11-14
      Time limit:1s
      Source limit:1000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Advancement Autumn 2010, http://sevolymp.uuuq.com/, author: Alexey Shchepin









      SPOJ Problem Set (classical)

      7891. Fibonacci Sequence

      Problem code: SPFIBO

      Fibonacci sequence is defined as follow: F1 = 1, F2 = 2, Fi = Fi-1 + Fi-2 (i > 2).

      Each natural number X can be expressed by the maximum numbers that are less than or equal to X in Fibonacci sequence: X = a1xF1 + a2xF2 + … Therefore, in Fibonacci system, X is known as: anan-1…a1. For example, 1 = 1F, 2 = 10F, etc. If we write all natural numbers successively in Fibonacci system, we will obtain a sequence like this: 1_1_0… This is called “Fibonacci bit sequence of natural numbers”.

      Your task is counting the numbers of times that bit 1 appears in the first N bits of this sequence.

      Input

      Line 1: An integer N (1 <= N <= 1015)

      Output

      Line 1: An integer K is the result

      Example

      Input:
      2

      Output:
      2

      Added by:HNUE
      Date:2010-11-16
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Anh Hiếu









      SPOJ Problem Set (classical)

      7897. Skyline

      Problem code: SKYLINE

      The director of a new movie needs to create a scaled set for the movie. In the set there will be N skyscrapers, with distinct integer heights from 1 to N meters. The skyline will be determined by the sequence of the heights of the skyscrapers from left to right. It will be a permutation of the integers from 1 to N.

      The director is extremely meticulous, so she wants to avoid a certain sloping pattern. She doesn’t want for there to be ANY three buildings in positions i, j and k, i < j < k, where the height of building i is smaller than that of building j, and building j’s height is smaller than building k’s height.

      Your task is to tell the director, for a given number of buildings, how many distinct orderings for the skyline avoid the sloping pattern she doesn't like.

      Input

      There will be several test cases in the input. Each test case will consist of a single line containing a single integer N (3 ≤ N ≤ 1,000), which represents the number of skyscrapers. The heights of the skyscrapers are assumed to be 1, 2, 3, ..., N. The input will end with a line with a single 0.

      Output

      For each test case, output a single integer, representing the number of good skylines - those avoid the sloping pattern that the director dislikes - modulo 1,000,000. Print each integer on its own line with no spaces. Do not print any blank lines between answers.

      Example

      Input:
      3
      4
      0

      Output:
      5
      14

      Added by:Iqram Mahmud
      Date:2010-11-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC Southeast USA Regional 2010









      SPOJ Problem Set (classical)

      7934. Operating System Problems (Task Scheduling)

      Problem code: OSPROB1

       

      As you all know, Operating System (OS) is a software that controls the execution of computer programs and may provide various services. Although modern operating systems are very easy to use and give us lots of services, their designing is not so easy. It needs lots of work and time to design a good OS. But no OS is perfect. Either they are not so usable or they are not so secure (got tons of viruses). Lingates, as an excellent programmer, wants perfection in all things. So he decided to not use this OSs and write his own OS. But he found out this work is not so easy to do alone even for a programmer like him. So he needs your help. 

      As a programmer with honor he won’t let you do equal or more work in a turn then him (Means Lingates has to do more work then you on each turn). Each turn you both divide the works between yourself. But the works are related so it’s better to take works which are adjacent. Like if there are 5 works 5, 2, 7, 1, 3 then Lingates would take 1st work and give you the 2nd work. But you can't take 2nd and 3rd work because that sum to 7+2 = 9 which is more than his work (5). Again you can't take 2nd and 4th work because they are not adjacent. After you both finish your work you both will again distribute your works. There is no limit how much work you both can take on a turn. Like Lingates can take 1st and 2nd work on first turn and give you no work on that turn or he can take 1st, 2nd and 3rd turn (total 5+2+7=14) and give you only 4th (1) or both works (1+3=4). As you are helping him he let you to divide the works but it has to be that Lingates has to do more work on each turn. As you are also a programmer with honor you also like to take the turns and divide the work on each turn such that it maximizes your total works.

      Write a program which will take the list of work and give the total amount of work done by Lingates and you if you make the list optimally. Again Lingates will do any amount of work you will give him in any turn as long as your work on that turn is less than his.

      Input

      The first line will be number of test cases (T<=500) and each case will start with an integer n (0<=n<=100). In the flowing line n numbers will given as the amount of works (all will be non negative integer <1000)

      Output

      A single line for each test case first the total work of Lingates and second the work of your.

      Example

      Input:
      4
      3
      1 2 3
      5
      5 2 7 1 3
      5
      6 6 6 6 6
      7
      4 9 5 7 6 5 1
      Output:
      6 0
      12 6
      18 12
      20 17


      Explanation:

      In 1st case you have to give Lingates all 3 works because 1< (2+3) and (1+2) =3, so you can't take any work.

      In 2nd case you can give Lingates 1st work (5) and you can take 2nd (2). Then you can give Lingates the 3rd (7) and you can take the rest (1+3).

      In 3rd case you can give Lingates 1st to 3rd work (6+6+6=18). You can take the left two works (6+6=12).

      In 4th case you can give Lingates 4 and 9 and you will take 5 and 7. Then in next turn you can give him 6 and you own take 5. Then you can give him 1.
      So totaling (4+9+6+1) =20 and (5+7+5) =17.


      ID RESULT TIME
      code...



      Added by:Muhammad Ridowan
      Date:2010-11-21
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: CLOJ FORT ICON ICK PRLG ST
      Resource:Own, thanks for helping Zobayer,Tulip and Shiplu









      SPOJ Problem Set (classical)

      7960. Multiplicative Palindrome

      Problem code: MULPAL

      Given a sequence of N integers. Find two disjoint contiguous palindromic subsequences. Lets call them X and Y. Your task is to find X and Y such that product of their lengths is maximal possible.

      Input

      First line will contain one integer N (1  N  106).
      Second line will contain N integers representing a sequnce from the text of the task (0 Ai 2*109).

      Output

      First and only line of output should contain only one integer, the maximum possible product from the text of problem.

      Example

      Input:
      2
      1 1

      Output:
      1



      Input:
      4
      1 1 2 2

      Output:
      4



      Input:
      6
      10 11 12 12 11 10

      Output:

      4



      Input:
      6
      0 1 0 1 0 1

      Output:
      9

       

      Added by:Zvonimir Medic
      Date:2010-11-28
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (acm)

      7969. A Knights’ Tale

      Problem code: ACPC10G

      Imagine a chess board that extends indefinitely in both horizontal and vertical directions. N identical knights are placed on this board, each in a different square. N different squares are specially marked, which we will call the target squares, which could be different from where the knights are initially at. We would like you to determine the minimum number of knight-steps needed so that each of the target squares is occupied by one of the knights.

      a

      As illustrated in the figure, a knight moves using the normal ”L” move (1 square in one dimension and 2 squares in the other dimension.) For this problem, it is possible for more than one knight to occupy the same square while trying to reach its final destination as long as each knight ends up in a different target square.

      Input

      Your program will be tested on one or more test cases. Each test case is specified using 2N +1 lines.
      The first line specifies (1 ≤ N ≤ 15) which is the number of knights (or targets.) The following N lines each specifies the position of a knight by specifying two integers representing the x and y location. The remaining N lines each specifies the position of a target square again by specifying two integers representing the x and y location. All coordinates are 32-bit signed integers.
      The last case is followed by a line with a single zero.

      Output

      For each test case, print the following line:
      k. m
      Where k is the test case number (starting at one,) and m is the minimum number of moves.

      Example

      Input:
      2
      3 5
      6 5
      5 3
      7 3
      0
      Output:
      1. 3

      Added by:Omar ElAzazy
      Date:2010-11-30
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACPC 2010









      SPOJ Problem Set (classical)

      7970. Jumping Beans

      Problem code: ACPC10H

      N jumping beans are standing in a line. At each second, a bean jumps. Your assignment is to figure the final position of the beans after a given number of seconds. To make the explanation easier, let’s assign a unique letter to each bean, and for simplicity, let’s assume the beans are initially standing in order: A, B, C, etc. To simplify even further, let’s assume N = 4, so initially the beans are standing in the order ABCD. At the first second, A jumps, swapping its place with B. Now the order is BACD. At the second second, it’s B’s turn, but this time swapping its place with A, then C, resulting in the standing order ACBD. More formally: at second s, the left most bean that has jumped the least number of times will do the swap s times, each time swapping its place with the bean on its right. Note that when the right-most bean swaps, it moves to the left-most position, pushing everybody else one place to the right. So, continuing with the previous example, and starting with the arrangement ACBD, it is bean C’s turn, since it is the left-most bean that has jumped the least amount of times. Being at the third second, C will swap three times, first resulting in ABCD, then ABDC, and then CABD. At the fourth second, it’s bean D’s turn to jump. At the fifth second, and since all the four beans have jumped exactly once, the bean that will jump is the bean standing at the left-most position.

      Input

      Your program will be tested on one or more test cases. Each test case is specified on a single line specifying an integer T and a string S where (0 < T < 109 ) is the number of seconds and S is the initial arrangement of the beans. S is a non empty string made of different upper-case letters (’A’. . . ’Z’).
      The last test case is followed by a line having a single 0.

      Output

      For each test case, print the following line:
      k. S
      Where k is the test case number (starting at one,) and S is the arrangement of the beans after jumping for T seconds.

      Example

      Input:
      3 ABCD
      13 ACM
      0

      Output:
      1. CABD
      2. CAM

      Added by:Omar ElAzazy
      Date:2010-11-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACPC 2010









      SPOJ Problem Set (classical)

      7971. The Cyber Traveling Salesman

      Problem code: ACPC10I

      In light of the exploding population on earth, a number of cities are being constructed on the moon. We would like you to assist in determining the best road system for these cities. Considering the high cost associated with building roads on the moon, all what is required is for the roads to form a cycle starting from the city that appears first in the input, passing through all other cities exactly once (but in any arbitrary order,) and then ending back to the first. (Yes, this problem is a variation of the traveling-salesman problem.)
      You are given the cost of building a road between each pair of cities. Roads are one-way, but the cost for building a road from city i to j is the same as the cost of building from city j to i. When roads intersect at a location that is not a city, you must account for the cost of constructing bypassing bridges. Constructing a bypass system costs k ∗ (k − 1) ∗ C/2 where k is the number of roads intersecting at that location, and C is a given constant. Note that the cities are laid out so that no three cities fall on the same straight line.

      Input

      Your program will be tested on one or more test cases. Each test case is specified using 2 ∗ N + 1 lines. The first line specifies two integers: (2 < N < 9) is the number of cities and (0 < C ≤ 1, 000, 000) is the coefficient used in determining the cost of building bridges. Following the first line, the Cartesian coordinates of the cities are specified in order. Each city is specified on a separate line made of two integers: xi and yi where (−1, 000 ≤ xi , yi ≤ 1, 000). No two cities are located at the same (x, y) location.
      The last N lines of a test case specify an N ∗ N matrix representing the cost of building a road between any two cities. The matrix is specified using N lines, each with N integers in a row-major format. The j th value on the ith row, denoted as cij is the cost of building a road from city-i to city-j where (0 < cij ≤ 106 ) and (cij = cji ) and (cii = 0).
      The last case is followed by a line having two zeros.

      Output

      For each test case, print the following line:
      k. M
      Where k is the test case number (starting at one,) and M is minimum cost needed to build the road system.

      Example

      Input:
      4 1
      1 2
      0 1
      2 1
      1 0
      0 1 8 3
      1 0 3 9
      8 3 0 2
      3 9 2 0
      4 100
      1 2
      0 1
      2 1
      1 0
      0 1 8 3
      1 0 3 9
      8 3 0 2
      3 9 2 0
      0 0

      Output:
      1. 10
      2. 20

      a


      Added by:Omar ElAzazy
      Date:2010-11-30
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACPC 2010









      SPOJ Problem Set (classical)

      7972. World of cubes

      Problem code: ACPC10F

      You’ve been assigned the task of programming a new video game called the World of Cubes. The game is played inside a box-shaped object (mathematically speaking: a rectangular cuboid) which we’ll call the hall. Within the hall, the player is assigned N positions, called focal points.
      The player must build N cubes, all parallel to the axes, and each is centered around one of the focal points. The mission is for the N cubes to completely fill the hall. It is acceptable for the cubes to overlap and even to extend beyond the hall. The only restriction is that all the cubes must be of equal side-length. And we would like you to compute the minimum such length.

      Input

      Your program will be tested on one or more test cases. Each test case is specified using N +1 lines.
      The first line specifies four integers: (1 ≤ N ≤ 50) is the number of cubes and (1 ≤ X, Y, Z ≤ 109 ) are the dimensions of the hall. One corner of the hall is at the origin (0, 0, 0), with the opposing corner at (X, Y, Z).
      N lines follow, each specifying the coordinate of a focal point using three integers: (0 ≤ x ≤ X), (0 ≤ y ≤ Y ), and (0 ≤ z ≤ Z).
      The last test case is followed by a line containing four zeros.

      Output

      For each test case, print the following line:
      k. D
      Where k is the test case number (starting at one,) and D is an integer which is the smallest length of the cube edges so that the N cubes would completely fill the hall.

      Example

      Input:
      2 4 4 8
      2 2 2
      2 2 6
      2 4 4 8
      2 2 2
      2 2 5
      0 0 0 0

      Output:
      1. 4
      2. 6

      Added by:Omar ElAzazy
      Date:2010-11-30
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACPC 2010









      SPOJ Problem Set ()

      7973. Sometimes, a penalty is good!

      Problem code: ACPC10E

      FIFA is considering a few changes to the way it organizes the Football World Cup. Currently, 32 teams compete for the World Title in two stages. During the first stage, known as the groups stage, the 32 teams are split evenly into 8 groups. Every team in the group plays 3 games, one against each team in their own group. Teams are then ranked within their group according to some points system. During the second (and final) stage, the top two teams from each group advance to the knockout stage where eight games are played to determine eight winners who would then play four games to determine four winners, then two games to determine the two winners who would then play the final game to determine the world champion. Needless to say, for the knockout stage to work, the number of teams in that stage has to be a power of two. FIFA is considering adding more groups, adding more teams to groups, and possibly changing the number of teams advancing from each group to the knockout stage. In addition, FIFA is considering having certain teams (previous champion, host country, etc.) advance to the knockout stage directly (without having to play in the groups stage.) But FIFA needs to know how many games will be played if any of these changes are applied. Please help them!

      Input

      Your program will be tested on one or more test cases. Each test case is specified on a single line made of 4 natural numbers with the following format:
      G T A D
      Where (G > 0) is the number of groups; T is the number of teams in each group; A is the number of teams advancing from each group to the knockout stage; and D is the number of teams directly advancing to the knockout stage without going through the groups stage. Note that (0 < A ≤ T) and that the four numbers in the input are no larger than 216.
      If the total number of teams in the knockout stage is not a power of two, your program must increase them to the closest power of two.
      The last test case is followed by a dummy line made of four -1’s.

      Output

      For each test case, print:
      G*A/T+D=X+Y
      where G, A, T, and D are as in the input, X is the total number of games, and Y is the number of teams your program determined it must add.

      Example

      Input:
      8 4 2 0
      8 4 2 1
      -1 -1 -1 -1

      Output:
      8*2/4+0=63+0
      8*2/4+1=79+15

      Added by:Omar ElAzazy
      Date:2010-11-30
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACPC 2010









      SPOJ Problem Set (classical)

      7974. What’s Next

      Problem code: ACPC10A

      According to Wikipedia, an arithmetic progression (AP) is a sequence of numbers such that the difference of any two successive members of the sequence is a constant. For instance, the sequence 3, 5, 7, 9, 11, 13, . . . is an arithmetic progression with common difference 2. For this problem, we will limit ourselves to arithmetic progression whose common difference is a non-zero integer.
      On the other hand, a geometric progression (GP) is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed non-zero number called the common ratio. For example, the sequence 2, 6, 18, 54, . . . is a geometric progression with common ratio 3. For this problem, we will limit ourselves to geometric progression whose common ratio is a non-zero integer.
      Given three successive members of a sequence, you need to determine the type of the progression and the next successive member.

      Input

      Your program will be tested on one or more test cases. Each case is specified on a single line with three integers (−10, 000 < a1 , a2 , a3 < 10, 000) where a1 , a2 , and a3 are distinct.
      The last case is followed by a line with three zeros.

      Output

      For each test case, you program must print a single line of the form:
      XX v
      where XX is either AP or GP depending if the given progression is an Arithmetic or Geometric Progression. v is the next member of the given sequence. All input cases are guaranteed to be either an arithmetic or geometric progressions.

      Example

      Input:
      4 7 10
      2 6 18
      0 0 0

      Output:
      AP 13
      GP 54

      Added by:Omar ElAzazy
      Date:2010-11-30
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACPC 2010









      SPOJ Problem Set (classical)

      7975. Tri graphs

      Problem code: ACPC10D

      Here’s a simple graph problem: Find the shortest path from the top-middle vertex to the bottom-middle vertex in a given tri-graph. A tri-graph is an acyclic graph of (N ≥ 2) rows and exactly 3 columns. Unlike regular graphs, the costs in a tri-graph are associated with the vertices rather than the edges.

      a

      So, considering the example with N = 4, the cost of going straight down from the top to bottom along the middle vertices is 7 + 13 + 3 + 6 = 29. The layout of the directional edges in the graph are always the same as illustrated in the figure.

      Input

      Your program will be tested on one or more test cases.
      Each test case is specified using N + 1 lines where the first line specifies a single integer (2 ≤ N ≤ 100, 000) denoting the number of rows in the graph. N lines follow, each specifying three integers representing the cost of the vertices on the ith row from left to right. The square of each cost value is less than 1,000,000.
      The last case is followed by a line with a single zero.

      Output

      For each test case, print the following line:
      k. n
      Where k is the test case number (starting at one,) and n is the least cost to go from the top-middle vertex to the bottom-middle vertex.

      Example

      Input:
      4
      13 7 5
      7 13 6
      14 3 12
      15 6 16
      0

      Output:
      1. 22

      Added by:Omar ElAzazy
      Date:2010-11-30
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACPC 2010









      SPOJ Problem Set (classical)

      7976. Sum the Square

      Problem code: ACPC10B

      Take any positive number, find the sum of the squares of its digits, repeat! You’ll end up with an infinite sequence with an interesting property that we would like to investigate further. Starting with the number 5, the sequence is:
            (5, 25, 29, 85, 89, 145, 42, 20, 4, 16, 37, 58, . . .)
      The interesting part is in what comes after 58: 52 + 82 = 89 which is a number that’s already been seen in the sequence. In other words, after 58, the sequence will fall into the repeating cycle:
            89, 145, 42, 20, 4, 16, 37, 58.
      What’s amazing is that this cycle will appear for many other numbers: 3, 18, 36, and 64 just to name a few. (see figure on the following page.) For some numbers, the sequence will fall into another repeating cycle by reaching 1. (see second figure on the following page) For example, starting with 19, you’ll end up with the sequence:
            (19, 82, 68, 100, 1, . . .)
      And that’s about it. Any number you choose will end up falling into a repeating cycle: Either the 89, 145, . . . cycle or the 1, . . . cycle.
      Given two numbers, your objective is to generate as few numbers in their sequences for the two sequences to intersect at one common number. For example, given 61 and 29, we can achieve what’s required by generating the sequences: (61, 37, 58, 89) and (29, 85, 89). Similarly, for 19 and 100, the sequences would be (19, 82, 68, 100) and (100).

      Input

      Your program will be tested on one or more test cases. Each test case is specified on a single line having two integers (0 < A, B < 109 ).
      The last case is followed by a dummy line made of two zeros.

      Output

      For each test case, print the following line:
      A B S
      Where A, B are as in the input and S is the (minimum) sum of the lengths of the two sequences.
      If the sequences starting at A and B do not intersect, then S = 0.

      Example

      Input:
      89 89
      19 100
      61 19
      0 0

      Output:
      89 89 2
      19 100 5
      61 19 0

      a

      b


      Added by:Omar ElAzazy
      Date:2010-11-30
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACPC 2010









      SPOJ Problem Set (classical)

      8001. Fibonacci Sum

      Problem code: FIBOSUM

      The fibonacci sequence is defined by the following relation:

      F(0) = 0

      F(1) = 1

      F(N) = F(N - 1) + F(N - 2), N >= 2

       

      Your task is very simple. Given two non-negative integers N and M, you have to calculate the sum (F(N) + F(N + 1) + ... + F(M)) mod 1000000007.

      Input

      The rst line contains an integer T (the number of test cases). Then, T lines follow. Each test
      case consists of a single line with two non-negative integers N and M.

       

      The first line contains an integer T (the number of test cases). Then, T lines follow. Each test case consists of a single line with two non-negative integers N and M.

      Output

      For each test case you have to output a single line containing the answer for the task.

      Example

      Input:
      3
      0 3
      3 5
      10 19
      
      Output:
      4
      10
      10857

      Constraints

      • T <= 1000
      • 0 <= N <= M <= 109

      Added by:David Gómez
      Date:2010-12-04
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:My Own









      SPOJ Problem Set (classical)

      8002. Horrible Queries

      Problem code: HORRIBLE

      World is getting more evil and it's getting tougher to get into the Evil League of Evil. Since the legendary Bad Horse has retired, now you have to correctly answer the evil questions of Dr. Horrible, who has a PhD in horribleness (but not in Computer Science). You are given an array of N elements, which are initially all 0. After that you will be given C commands. They are -

      * 0 p q v - you have to add v to all numbers in the range of p to q (inclusive), where p and q are two indexes of the array.

      * 1 p q - output a line containing a single integer which is the sum of all the array elements between p and q (inclusive)

       

      Input

      In the first line you'll be given T, number of test cases.

      Each test case will start with N (N<=100 000) and C (C<=100 000). After that you'll be given C commands in the format as mentioned above. 1 <= p,q <= N and 1 <= v <= 10^7.

      Output

      Print the answers of the queries.

      Example

      Input:
      1
      8 6
      0 2 4 26
      0 4 8 80
      0 4 5 20
      1 8 8
      0 5 7 14
      1 4 8

      Output:
      80
      508




      Added by:Iqram Mahmud
      Date:2010-12-04
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own. Thanks to Emir Habul.









      SPOJ Problem Set (classical)

      8004. Tree Topology

      Problem code: TTOP

      Given a rooted tree, a permutation of its nodes is valid if the following holds: for each pair of nodes a and b, if a is an ancestor of b, then a appears before b in the permutation. Let P(t) be the number of valid permutations for a tree t.

      Given an integer N, you can construct all the possible trees of N nodes, numbered from 1 to N, rooted at 1. I'd like to know what's the sum of P(t) for all t that can be constructed for the given N.

      We consider two trees equal iff each node in the second tree has the same parent as it does in the first one. 

      trees for N = 3

      The picture shows all the possible trees for N = 3.

      Input

      A single integer N ( 1 <= N <= 1000000 ).

      Output

      A single integer representing the solution modulo 1000000007.

      Example

      Input: 
      3
      Output:
      4

      Explanation: If you take a look at the picture, you'll see that the first two trees have one valid permutation each, and the third tree has two, namely { 1, 2, 3 } and { 1, 3, 2 }. The total is, of course, 4.


      Added by:Gustav Matula
      Date:2010-12-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set ()

      8042. Possible Friends

      Problem code: SOCIALNE

      Josué, one of the undergraduate students in PUCMM, is developing a Social Network, but he is having difficulties in identifying the person that has more possible friends. Two persons are possible friends if they are not friends and they have at least one common friend, for example if person A is friend only to person B, and person B is friend of C, then, A and C are possible friends. You are about to help him in this task. Given the network table, you have to write a program that finds the person that has more possible friends, if more than one person matches this criteria, then select the one that comes first ( the one that has the lower ID).

      Input

      The first line is T (1 ≤ T ≤ 1,000), the number of test cases, then T test cases follow.

      Each test case consists in a 'Y' or 'N' square matrix(MxM) representing the friendship of the network, where M is the number of persons.

      Constraints

      M (1 ≤ M ≤ 50)

      The square matrix has M lines, each line has M characters.

      The first line of the matrix corresponds to person 0, the next line to person 1, and so on.

      On each line the leftmost character corresponds to person 0, the next character to person 1, and so on.

      So if character j of the line i is 'Y', it means that person 'i' is a friend of 'j'.

      For each person i, character i of line i will be 'N'.

      For each i,j character j of line i will be the same as character i of line j.

      Output

      For each test case, you have to output one line containing the ID of the person(0-based) that has more possible friends and the number of possible friends this person has, separated by a blank space.

      Example

      Input:
      3
      NYN
      YNY
      NYN
      NYYY
      YNNY
      YNNN
      YYNN
      NNYNNNN
      NNYNNNN
      YYNYNNN
      NNYNYNN
      NNNYNYY
      NNNNYNN
      NNNNYNN
      Output:
      0 1
      2 2
      3 4

      Added by:Olson Ortiz
      Date:2010-12-09
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Used in 1st Programming contest PUCMM ACM-ISC 2010 (Dominican Republic)









      SPOJ Problem Set (classical)

      8044. Fantastic Discovery

      Problem code: IMMERSED

      A fantastic discovery is about to happen in the biology field, and you are part of the team making the research. The research is about measuring the cells growth in an environment oxygenless and in presence of a toxic substance. The team came to a courious hypothesis, the analyzed data tells them that: the growth, the number of days and the toxicity; are related by this formula:

      P = N*NcN ;

      where P is the growth measured in thousands of cells.

      N is the elapsed number of days.

      and c is the constant that relates to the toxicity level of the experiment.

      Your biology partners need to takeout some tissues from the cells when these cells reach a specific growth. They require you to write a program that tells them the exact time when this will happen, given a toxicity level and the growth required.

       

      Input

      The first line is T (1 ≤ T ≤ 40,000), the number of test cases, then T test cases follow.

      Each test case is a line with 2 integers(P c) separated by a space.

      P (1 ≤ P ≤ 1015)

      c (1 ≤ c ≤ 5)

      Output

      For each test case you have to output the expected time in decimal format.

      Example

      Input:
      3
      1 1
      3 4
      100 1
      Output:
      1.000000
      1.207384
      3.086308

      Note 1: your output must contain at least 6 decimal places.
      Note 2: numerical problem. Output generated by submitted program
      should be exactly the same as test case with accuracy of 0.000001.

      Added by:Olson Ortiz
      Date:2010-12-10
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Used in 1st Programming contest PUCMM ACM-ISC 2010









      SPOJ Problem Set (classical)

      8055. Playground

      Problem code: AMR10A

      My kid's school cleared a large field on their property recently to convert it into a playing area.  The field is polygonal.  The school administration decided to separate the field into two areas by building a straight picket fence between the area for the older kids and the area for the younger kids.  The fence would go between two non-adjacent vertices of the polygonal field, and given the shape of the field, all such possible fences would lie strictly and entirely within the field.
      Naturally, the smaller of the two areas would go to the younger kids.  So can you help the school determine what the area of the smaller play-area would be for different fence positions?
       
      INPUT
      The first line contains 2 numbers N denoting the number of points in the convex polygon and Q denoting the number of possible locations of straight line fences.
      The next N lines contain 2 integers each. The ith line contains the integers xi yi denoting the coordinates of the ith point of the polygon. The points are given in clockwise order.
      The next Q lines contain 2 integers a b denoting that a straight line fence is to be drawn connecting a and b.
       
      OUTPUT
      Output Q lines one corresponding to each query. For each query, output the area of the smaller region for the corresponding query truncated to 1 decimal place. Always have 1 digit after the decimal place, so if the answer is 1, output it as 1.0 instead.
       
      CONSTRAINTS
      4 <= N <= 50000
      1 <= Q <= 50000
      -20,000,000 <= x,y <= 20,000,000
      0 <= a < b-1
      b < N
       
      SAMPLE INPUT
      4 2
      0 0
      0 1
      1 2
      1 0
      1 3
      0 2
       
      SAMPLE OUTPUT
      0.5
      0.5
       
      EXPLANATION
      The polygon is given by the points (0,0) (0,1) (1,2) (1,0).  
      In the first query, we join the points (0,1) and (1,0) which leads to the 2 areas given by (0,0) (0,1) (1,0) and (0,1) (1,2) (1,0). The first triangle has an area of 0.5 and the second triangle has an area of 1. The minimum of these 2 is 0.5.
      In the second query, we join the points (0,0) and (1,2) which leads to the 2 areas given by (0,0) (0,1) (1,2) and (0,0) (1,2) (1,0). The first triangle has an area of 0.5 and the second triangle has an area of 1. The minimum of these 2 is 0.5.


      Added by:Varun Jalan
      Date:2010-12-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem, ICPC Asia regionals, Amritapuri 2010









      SPOJ Problem Set (classical)

      8056. Regex Edit Distance

      Problem code: AMR10B

      A regular expression is used to describe a set of strings. For this problem the alphabet is limited to 'a' and 'b'. R is a regular expression if:
      1) R is "a" or "b"
      2) R is of the form "(R1R2)" where R1 and R2 are regular expressions
      3) R is of the form "(R1|R2)" where R1 and R2 are regular expressions
      4) R is of the form "(R1*)" where R1 is a regular expression.

      The set of strings recognised by R are as follows:
      1) If R is "a", then the set of strings recognised = {a}
      2) If R is "b", then the set of strings recognised = {b}
      3) if R is of the form "(R1R2)" then the set of strings recognised = all strings which can be obtained by a concatenation of strings s1 and s2 where s1 is recognised by R1 and s2 by R2.
      4) if R is of the form "(R1|R2)" then the set of strings recognised = union of the set of strings recognised by R1 and R2.
      5) If R is of the form "(R1*)" then the the strings recognised are the empty string and the concatenation of an arbitrary number of copies of any string recognised by R1.

      The edit distance between two strings s1 and s2 is the minimum number of characters to be inserted/deleted or replaced in s1 to make it equal to s2.

      Given two regular expressions R1 and R2, find the minimum edit distance amongst all pairs of strings s1 and s2 such that s1 is recognised by R1 and s2 is recognised by R2.

      INPUT
      The first line contains the number of test cases T. T test cases follow.
      Each test case contains two lines containing two regular expressions R1 and R2. There is a blank line after each test case.

      OUTPUT
      Output T lines one corresponding to each test case containing the required answer for the corresponding test case.

      CONSTRAINTS
      T <= 100
      1 <= length(R1), length(R2) <= 50
      You are guaranteed that R1 and R2 will conform to the definition provided above.

      SAMPLE INPUT
      2
      ((a|b)*)
      (a(b(aa)))

      (a((ab)*))
      (a(b(((ab)b)b)))

      SAMPLE OUTPUT
      0
      2

      EXPLANATION

      For the first case R1 recognises all strings over the alphabet a and b. Thus it recognises the string "abaa" which is also recognised by R2.
      For the second case the strings "aababab" and "ababbb" are recognised by R1 and R2 respectively and have edit distance of 2.


      Added by:Varun Jalan
      Date:2010-12-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem, ICPC Asia regionals, Amritapuri 2010









      SPOJ Problem Set (classical)

      8057. Square Free Factorization

      Problem code: AMR10C

      You all know about factorization of an integer.  Here we want you to factor a number into as few factors as possible.  That is easy, you say, just have the number itself, and that will be the smallest number of factors i.e. 1.
      But wait, I haven't finished -- each of the factors that you find must be square-free.  A square-free number, however you factor it, won't have any factor that is a perfect square.  Of course, you can never include 1 as a factor.
       
      INPUT
      The first line of input is the number of test cases T.
      The next T lines each have an integer N.
       
      OUTPUT
      For each testcase, output the smallest number of square-free factors.
       
      CONSTRAINTS
      T <= 1e4
      2 <= N <= 1e6
       
      SAMPLE INPUT
      2
      6
      8
       
      SAMPLE OUTPUT
      1
      3


      Added by:Varun Jalan
      Date:2010-12-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem, ICPC Asia regionals, Amritapuri 2010









      SPOJ Problem Set (classical)

      8058. Soccer Teams

      Problem code: AMR10D

      My kid's favorite subject is math, as you know by now.  He is learning division now, and his teacher has taught him about even numbers being divisible by 2, numbers whose digits add up to a multiple of 3 being exactly divisible by 3 etc.
      He was familiar with division by 11 during selection for soccer teams on his playground, and was wondering whether there was any easy rule to see if a number was divisible by 11.  For example, he wondered, if he arranged a number of digits 0-9 in a row to form a number, which ones would be divisible by 11?
      He decided to start off with d[1] 1's, d[2] 2's ..., d[9] 9's, and seeing what is the minimum factor of 11 that he could get by using all these digits, together with any number of 0's.  Please help him figure out how many digits there are in this minimum factor. If he will not be able to form a multiple of 11 in this way, print -1.

      INPUT

      The first line will contain the number of test cases T. T lines follow one corresponding to each test case.
      Each line has 9 integers d[1] d[2] .... d[9].

      OUTPUT

      Output T lines one corresponding to each test case. The ith line should contain the required answer for the corresponding test case.

      CONSTRAINTS

      1 <= T <= 100
      1 <= d[1] + ... + d[9] <= 100

      SAMPLE INPUT
      2
      2 0 0 0 0 0 0 0 0
      0 1 0 0 0 0 0 0 1

      SAMPLE OUTPUT
      2
      3

      EXPLANATION
      For the first case, the number 11 can be formed which has 2 digits.
      For the second case, number 209 can be formed which is divisible by 11 and has 3 digits.


      Added by:Varun Jalan
      Date:2010-12-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ICPC Asia regionals, Amritapuri 2010









      SPOJ Problem Set (classical)

      8059. Stocks Prediction

      Problem code: AMR10E

      The department store where my family goes shopping is trying to predict how much of each item they stock they will sell each month.  Keeping a large amount of inventory is costly, and running out of items is also not a good idea.  Since the manager asked for my help as a sales consultant, I decided to formulate a model for predicting each month's sales S of an item based on its sales during the previous R months.  After a lot of trial and error, I came up with such a model, where
      S(n) = a1*S(n-1) + a2*S(n-2) + ... + aR*S(n-R)  
      where S(n) is the predicted sales for the nth month for n > R, and S(1) to S(R) are seed values.
       
      The store manager was pleased with my model's ability to help him in controlling his inventory.  
      He asked me to list out every Kth month's sales, and give him the sum of the first N values from this list.  For example he wanted every Christmas month's sales summed up for the next 10 years (N=10 and K=12, month 1 being January), or every end-of-quarter month's sales for the next 2 years (N=2, K=3).
       
      Can you please help me write a program that does all the above?
       
      INPUT
      The first line of the input T, the number of test cases. Each test case consists of three lines.
      The first line of each test case contains N, R, K.
      The second line of each test case contains R integers denoting S(1), S(2), ..., S(R).
      The third line of each test case contains R integers denoting the coefficients a1, a2, ..., aR of the predictive model.
       
      OUTPUT
      For each test case, output the sum requested by the manager as given in the problem statement, modulo 1,000,000,007.
       
      CONSTRAINTS
      T <= 40
      1 <= N <= 1000000000
      1 <= R <= 8
      1 <= K <= 8
      0 <= All other input values < 1000000007
       
      SAMPLE INPUT
      2
      4 1 1
      1  
      2  
      3 2 3
      1 1  
      1 1  
       
      SAMPLE OUTPUT
      15
      44
       
      EXPLANATION
      In the first test case, it is given that S(1) = 1 and the relation is S(n)=2*S(n-1). The list asked by the store manager consists of all the terms of S since K is 1. Hence, the answer is just the sum of the first 4 terms of S.
      In the second test case, the sequence S is the fibonacci sequence which is: 1, 1, 2, 3, 5, 8, 13, 21, 34. The list consists of 2, 8, 34 which sum up to 44.


      Added by:Varun Jalan
      Date:2010-12-13
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ICPC Asia regionals, Amritapuri 2010









      SPOJ Problem Set (classical)

      8061. Christmas Play

      Problem code: AMR10G

      My kid's kindergarten class is putting up a Christmas play.  (I hope he gets the lead role.)  The kids are all excited, but the teacher has a lot of work.  She has to produce costumes for a scene with K soldiers.  She wants to buy all the costumes in the same size, allowing for some small amount of length alteration to be done by the kids' parents later.  So she has taken all the kids' height measurements.  Can you help her select K kids from her class of N to play the soldier role, such that the height difference between the tallest and shortest in the group is minimized, and alternations will be easiest?  Tell her what this minimum difference is.
       
       
      INPUT
      The first line contains the number of test cases T. T test cases follow each containing 2 lines.
       
      The first line of each test case contains 2 integers N and K.
      The second line contains N integers denoting the height of the N kids.
       
      OUTPUT
      Output T lines, each line containing the required answer for the corresponding test case.
       
      CONSTTRAINTS
      T <= 30
      1 <= K <= N <= 20000
      1 <= height <= 1000000000
       
      SAMPLE INPUT
      3
      3 1
      2 5 4  
      3 2
      5 2 4  
      3 3
      2 5 4  
       
       
      SAMPLE OUTPUT
      0
      1
      3
       
      EXPLANATION
      In the first test case, the teacher needs to only select 1 kid and hence she can choose any kid since the height difference is going to be 0.
      In the second test case, the teacher can choose kids with height 4 and 5.
      In the third test case, the teacher is forced to choose all 3 kids and hence the answer = 5-2 = 3


      Added by:Varun Jalan
      Date:2010-12-13
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ICPC Asia regionals, Amritapuri 2010









      SPOJ Problem Set ()

      8062. Shopping Rush

      Problem code: AMR10H

      A shop-keeper is trying to figure out how to arrange gifts in his shop for Christmas. He runs a peculiar shop such that each customer buys exactly two gifts at the shop (he could buy two of the same gifts too). He knows the probability that a customer might want gift i, is P_i.

      He needs to arrange the gifts across several floors. Each floor should have exactly one gift. It takes A*(|x - y|)^2 + B*(|x - y|) + C seconds to go from floor x to floor y.

      Can you help him arrange the gifts across floors such that, the expected time spent by a shopper is minimized?

      For the purpose of this problem assume that the first gift choice and the second gift choice are independent of each other. i.e., Choosing a first gift as i does not change his probability of choosing the second gift as j. It still remains P_j.

      INPUT
      The first line contains the number of test cases T. 2*T lines follow, 2 per test case. The first line contains 4 integers : N, A, B, C. The second line contains N integers in the range 1 to 100. The ith integer represents the percentage probability P_i. All P_i's will sum to 100.

      OUTPUT
      Output T lines one for each test case. Each line contains the minimum expected travelling time for the corresponding test case. Output the answer as a reduced fraction as below.

      CONSTRAINTS
      1 <= T <= 100
      1 <= N <= 20
      0 <= A,B,C <= 10

      SAMPLE INPUT
      4
      3 0 1 0
      60 10 30
      1 1 1 0
      100
      1 1 1 3
      100
      4 3 7 2
      25 25 25 25

      SAMPLE OUTPUT
      3/5
      0/1
      3/1
      73/4


      Added by:Varun Jalan
      Date:2010-12-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:own problem, ICPC Asia regionals, Amritapuri 2010









      SPOJ Problem Set ()

      8063. Dividing Stones

      Problem code: AMR10I

      There are N stones, which can be divided into some piles arbitrarily. Let the value of each division be equal to the product of the number of stones in all the piles modulo P. How many possible distinct values are possible for a given N and P?
       
      INPUT
      The first line contains the number of test cases T. T lines follow, one corresponding to each test case, containing 2 integers: N and P.
       
      OUTPUT
      Output T lines, each line containing the required answer for the corresponding test case.
       
      CONSTRAINTS
      T <= 20
      2 <= N <= 70
      2 <= P <= 1e9
       
      SAMPLE INPUT
      2
      3 1000
      5 1000
       
      SAMPLE OUTPUT
      3
      6
       
      EXPLANATION
      In the first test case, the possible ways of division are (1,1,1), (1,2), (2,1) and (3) which have values 1, 2, 2, 3 and hence, there are 3 distinct values.
      In the second test case, the numbers 1 to 6 constitute the answer and they can be obtained in the following ways:
      1=1*1*1*1*1
      2=2*1*1*1
      3=3*1*1
      4=4*1
      5=5
      6=2*3


      Added by:Varun Jalan
      Date:2010-12-13
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:own problem, ICPC Asia regionals, Amritapuri 2010









      SPOJ Problem Set ()

      8064. Mixing Chemicals

      Problem code: AMR10J

      There are N bottles each having a different chemical. For each chemical i, you have determined C[i] which means that mixing chemicals i and C[i] causes an explosion. You have K distinct boxes. In how many ways can you divide the N chemicals into those boxes such that no two chemicals in the same box can cause an explosion together?
       
      INPUT
      The first line of input is the number of test cases T. T test cases follow each containing 2 lines.
      The first line of each test case contains 2 integers N and K.
      The second line of each test case contains N integers, the ith integer denoting the value C[i]. The chemicals are numbered from 0 to N-1.
       
      OUTPUT
      For each testcase, output the number of ways modulo 1,000,000,007.
       
      CONSTRAINTS
      T <= 50
      2 <= N <= 100
      2 <= K <= 1000
      0 <= C[i] < N
      For all i, i != C[i]
       
      SAMPLE INPUT
      3
      3 3
      1 2 0
      4 3
      1 2 0 0
      3 2
      1 2 0
       
      SAMPLE OUTPUT
      6
      12
      0
       
      EXPLANATION
      In the first test case, we cannot mix any 2 chemicals. Hence, each of the 3 boxes must contain 1 chemical, which leads to 6 ways in total.
      In the third test case, we cannot put the 3 chemicals in the 2 boxes satisfying all the 3 conditions.


      Added by:Varun Jalan
      Date:2010-12-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:own problem, ICPC Asia regionals, Amritapuri 2010









      SPOJ Problem Set (classical)

      8073. The area of the union of circles

      Problem code: CIRU

      You are given N circles and expected to calculate the area of the union of the circles !

      Input

      The first line is one integer n indicates the number of the circles. (1 <= n <= 1000)

      Then follows n lines every line has three integers

      Xi Yi Ri

      indicates the coordinate of the center of the circle, and the radius. (|Xi|. |Yi|  <= 1000, Ri <= 1000)

      Note that in this problem Ri may be 0 and it just means one point !

      Output

      The total area that these N circles with 3 digits after decimal point

      Example

      Input:
      3
      0 0 1
      0 0 1
      100 100 1


      Output:
      6.283

      Added by:aekdycoin
      Date:2010-12-15
      Time limit:0.100s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:https://www.spoj.pl/problems/VCIRCLES/









      SPOJ Problem Set (classical)

      8074. God of Number Theory

      Problem code: NUMG

      In ACM_DIY, there is one master called “ShaZai”. As we know, he is the god of “Number Theory”. He always kills the problem about “Number Theory” in seconds! But of course we do not have any idea about these problems~ One day in ACM_DIY, ShaZai asks us one problem:

             You are given three non-negative integers A, B and K, you are expected to find the number of number that satisfy

      (1)   X^A = B( mod (2K + 1) )

      (2)   X is in the ranger [0, 2K];

       

             Of course we have no idea about this problem, so could you help us?

       

      Input

      The first line is one integer T indicates the number of the test cases. (T <= 1000)

             Then for every case, only one line contains three integers A, B and K. (1 <= A, B <= 10^9, 1 <= K <= 5 * 10^8)

       

      Output

      Output the answer in a single line.

       

      Example

      Input:

      3
      213 46290770 80175784
      3 46290770 80175784
      3333 46290770 80175784

       


      Output: 27
      27
      297

      Added by:aekdycoin
      Date:2010-12-15
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8075. Sequence

      Problem code: SEQN

      As you know, there number of permutation of the increasing vector {1, 2, 3…n} is exactly n! ;For example, if n = 3, then, {1,2,3} , {1,3,2}, {2,1,3}, {2,3,1}, {3,1,2}, {3,2,1} are all the permutation of the vector {1,2,3 };

             We define D( {A1,A2...An } ) = the number of element that satisfy   Ai = i.

             For example, D( {1,2,3} ) = 3 ,D( {1,3,2} ) = 1 (only ‘1’ is at 1), D({3,1,2}) = 0 ….

             Now we want to calculate the number of permutation that satisfy D( {A1,A2...An } ) = K.

               For example, if n = 3 and k = 3, then of course there is only one permutation {1,2,3} that satisfy D( {1,2,3}) = 3. But if n = 3 and k = 0, then there are two permutations {3,1,2} and {2,3,1} satisfy D( {3,2,1} ) = D( {2,3,1} ) = 0;

        But when n is very large, it’s hard to calculate by brute force algorithm. Optimal is one required here.

             Because the answer may be very large, so just output the remainder of the answer after divided by m.

       

      Input

      In the first line there is an integer T, indicates the number of test cases. (T <= 500)

      In each case, the first line contains three integers n,k and m. (0 <= k<= n <=10^9, 1 <= m <= 10^5, n != 0)

       

      Output

      Output “Case d: “first where d is the case number counted from one. Then output the remainder of the answer after divided by m.

      Example

      Input:
      3
      3 0 7
      3 3 3
      331105236 82934100 3711


       Output:
      Case 1: 2
      Case 2: 1
      Case 3: 2622

      Added by:aekdycoin
      Date:2010-12-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:2010 ACM-ICPC Multi-University Training Contest









      SPOJ Problem Set (classical)

      8093. Sevenk Love Oimaster

      Problem code: JZPGYZ

       

          Oimaster and sevenk love each other.

          But recently,sevenk heard that a girl named ChuYuXun was dating with oimaster.
      As a woman's nature, sevenk felt angry and began to check oimaster's online talk with ChuYuXun.
          Oimaster talked with ChuYuXun n times, and each online talk actually is a string.
      Sevenk asks q questions like this,
          "how many strings in oimaster's online talk contain this string as their substrings?"

      Input

      There are two integers in the first line, 
      the number of strings n and the number of questions q.
      And n lines follow, each of them is a string describing oimaster's online talk. 
      And q lines follow, each of them is a question.
      n<=10000, q<=60000 
      the total length of n strings<=100000, 
      the total length of q question strings<=360000

      Output
      For each question, output the answer in one line.
      Example
      Input:
      3 3
      hi,I'mChuYuXun..YouaresohandsomethatIfallinlovewithyou
      butIlovesevenk..you'dbettergoaway
      55555555555
      ChuYuXun
      you
      55555555
      Output:
      1
      2
      1

      Added by:Tom Chen
      Date:2010-12-18
      Time limit:1s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8096. Queue

      Problem code: SPQUEUE


      On some special occasion Nadia’s company provide very special lunch for all employees of the company. Before the food is served all of the employees must stand in a queue in front of the food counter. The company applied a rule for standing in the queue. For instance if Abul is the supervisor of Babul and Abul stands in kth position from the front of the queue, then Babul cannot stand at any position in between 1 and k-1 from front of the queue. The company has N employees and each of them has one supervisor except one who doesn’t have any supervisor.

      You need to calculate in how many ways the queue can be created. You can safely assume that in at least one way the queue can be created.

      Input

      The first line is the number of test cases.

      Each test case:

      -         The first line contains 2 integers M and N.

      -         Line 2..N: consist of one integer is supervisor of i-employees.

      Output

      For each test case: the result of this problem module M in one line.

      Example

      Input:
      1
      2 2
      1
      Output:

      1

      Constraints:
      - Number of test cases <= 10 for small data, N <= 100000
      - Number of test cases = 1 for large data, N <= 500000
      - 1 <= M <= 1000000000
      - Time Limit for all tests: 2s

      Added by:HNUE
      Date:2010-12-20
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Based on ACM Kuala Lumpur









      SPOJ Problem Set (classical)

      8097. Islands

      Problem code: IOIISL08

      You are visiting a park which has N islands. From each island i, exactly one bridge was constructed. The length of that bridge is denoted by Li. The total number of bridges in the island is N. Each bridge can be traversed in both directions. Also, for each pair of island, there is a unique ferry that travels back and forth between them.


      Since you like walking better than riding ferries, you want to maximize the sum of the lengths of the bridges you cross subject to the constraints below :

      • You can start a visit on an island of your choice.
      • You may not visit any island more than once.
      • At any time you may move from your current island S to any island D which you have not visited before. You can go from S to D either by walking, in which case the length of the bridge you take will be added to the total length or by ferry if the islands are not connected by any bridge (when checking for connectivity you should include those islands which have been previously visited by you).

      Note that you do not have to visit all the islands, and it may be impossible to cross al the bridges.

      Given N bridges along with their lengths, your task is to find out the maximum distance you can walk by following the rules above.

      Constraints :

      2 <= N <= 100000

      1 <= Li <= 1000000

      Input

      The first line of the input contains N, the number of islands. Islands are numbered 1 to N inclusive. Then follow N lines. The ith of these lines contains two integers Ii and Li, which are the island the ith island connects to and the length of the bridge respectively. You may assume that each bridge has two different islands as its endpoints.

      Output

      You must write a single line which is the maximum possible distance that you can walk.

      Example

      Input :

      7

      3 8

      7 2

      4 2

      1 4

      1 9

      3 4

      2 3

      Output :

      24

      Explanation of the example :

      Start at 5.

      Walk to 1.

      Walk to 3.

      Walk to 6.

      Ferry to 7.

      Walk to 2.

      Hence total distance you walked is 9 + 8 + 4 + 3 = 24.

      Note : The final answer fits within 64 bit integer.


      Added by:Paranoid Android
      Date:2010-12-20
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:International Olympiad in Informatics 2008









      SPOJ Problem Set (classical)

      8099. Crash´s number table

      Problem code: TABLE

      In today's math lesson, Little Crash has just learnt Least Common Multiple (LCM). For two positive integers a and b, LCM(a, b) means the minimum positive integer which can be divisible by a and b.

      After coming home, Crash is still thinking about what he learnt in the math lesson. Then he draw a table filled numbers in order to research LCM. The table has N rows and M columns. The number in the ith row and jth column is LCM(i, j).

      A table of 4*5 is just like this:

      1 2 3 4 5
      2 2 6 4 10
      3 6 3 12 15
      4 4 12 4 20

      Now Little Crash wants to know the sum of all the numbers in the table. You just need to output the sum modulo 20101009.

      Input

      Only two positive integers stand for N and M. (N, M <= 107)

      Output

      A positive integer which means the sum modulo 20101009.

      Example

      Input:
      4 5

      Output:
      122

      Added by:jiazhipeng
      Date:2010-12-20
      Time limit:0.100s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 C99 strict JAVA PAS fpc PAS gpc
      Resource:Modified from task energy of NOI 2010









      SPOJ Problem Set (classical)

      8100. Shifting Lights

      Problem code: SHLIGHTS

      Recently I made a new device. It contains a set of lightbulbs, each having two parts. The left part glows blue and the right part glows green. One cannot guess which parts of the bulbs will be  glowing when the device is powered on. Consider any two adjacent bulbs at time t. If the left bulb is glowing green and the right bulb is glowing blue they swap their states to blue and green respectively at time t + 1. But now I am wondering, if I power it on when will the bulbs stop swapping. Can you help me with this ?

      Input

      The first line of the input contains t, the number of testcases. Each of the next t lines contains a single string containing characters 'B' and 'G' representing the bulbs when switched on i.e. at time t = 0. Here 'B' is for blue and 'G' is for green. The length of the string will be less than 100000.

      Output

      For each test output one line giving the time after which swapping stops.

      Example

      Input :

      2

      GBGBBB

      BGBBGGGBBBGBGB

      Output :

      4

      8


      Added by:Paranoid Android
      Date:2010-12-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8104. Friendly Knights

      Problem code: KFRIENDS

      horse

      Gurram land is the city of Knights and is shaped exactly like a chess board. Some of the cells in this city contains Knights. Due to scarcity of grass ( Global Warming ! ), there has been fights between every pair of neighboring Knights. Knight A is a neighbor of Knight B, if A can reach B in exactly one step ( see notes for clarity ) .

      To spread peace in the Gurram land, the United Nations has organized a 'Friendship Mela' and wants to distribute friendship neck straps to the Knights. Each pair of neighboring Knights then exchange Neck Strap of same color and wear it around their neck, to promote friendship :). To make it more colorful, the UN also wants each Knight to have distinct colored neck straps around its neck. The UN is ready to produce any number of straps of a particular color, but can you help them to find out the minimum number of colors to be used.

      Notes: A Knight in cell (x,y) can move in one step to any of the cells (x+2,y+1) , (x+2,y-1) , (x+1,y+2) , (x+1,y-2) , (x-2,y+1) , (x-2,y-1) , (x-1,y+2) , (x-1,y-2) i.e., the normal rule in standard chess.

      Input

      First line contains T ( around 10 ), the number of test cases. Each test case starts with an integer N ( 0 <= N <= 10000 ) the number of Knights in the city. Each of the next N lines contains two integers X Y the row and the column number of a Knight ( 1 <= X,Y <= 100 ). No two Knights are on a same cell.

      Output

      For each test case, print the minimum number of colors needed, in a separate line.

      Example

      Input:
      2
      3
      1 1
      2 3
      3 2
      4
      1 1
      2 3
      2 1
      1 3
      Output:
      2
      1

      Case 1 : (1,1) & (2,3) can exchange a Red strap , (1,1) & (3,2) can exchange a Green Strap
      Case 2 : (1,1) & (2,3) can exchange a Red strap , (2,1) & (1,3) can exchange a Red Strap

      Added by:Anil Kishore
      Date:2010-12-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK NODEJS PYTH 3.2.3 n SED
      Resource:Own problem. Used in Jan'2011 IIIT-Hyderabad Internal Contest.









      SPOJ Problem Set (classical)

      8105. Dot Product Maximization

      Problem code: DPMAX

      Given two vectors, a = ( xa, ya ), b = ( xb, yb ), their dot product is defined as follows:
      dp( a, b ) = xa*xb + ya*yb.

      Given N vectors in the plane, find a pair for each of them (among those given in the input) such that the dot product of the vector and its pair is maximal. You may pair a vector with itself too.

      Input

      The first line of input contains a single integer N ( 1 <= N <= 200000 ).
      Each of the next N lines contain a pair of real numbers, xi and yi (0 <= |xi|, |yi| <= 100000), representing the i-th vector. xi and yi will be rounded to 3 decimal places.

      Output

      Output N lines, i-th one containing the maximal dot product for the i-th vector from the input rounded to 3 decimal places.

      Example

      Input: 

      4
      0.000 1.000
      0.000 2.000
      1.000 1.000
      0.000 0.000

      Output:
       
      2.000
      4.000
      2.000
      0.000

      Explanation: Pair the first vector with the second, the second with itself, third with itself or with the second, and the last one with any of them.


      Added by:Gustav Matula
      Date:2010-12-23
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8106. Normalized Form

      Problem code: ACPC10C

      As you most probably know, any boolean expression can be expressed in either a disjunctive normal form or a conjunctive normal form. In a disjunctive normal form, a boolean expression is written as a disjunct (logical or) of one-or more sub-expressions where each of these sub-expressions is written in a conjunctive normal form. Similarly, an expression written in a conjunctive normal form is a conjunct (logical and) of sub-expressions each written in a disjunctive normal form.

      a


      An AND/OR tree is a tree-like graphical-representation of boolean ex- pressions written as either conjunctive- or disjunctive-normal form. Since the sub-expressions of a normalized form alternate in being either disjunctive or conjunctive forms, you’d expect the sub-trees on an AND/OR tree to alternate in being AND- or OR- trees depending on the sub-tree’s depth-level. The example upwards illustrates this observation for the boolean expression (A (B C)) (D E) where the trees in the 1st (top-most) and 3rd levels are AND-trees.
      Write a program that evaluates a given and/or tree.

      Input

      Your program will be tested on one or more test cases. Each test case is specified on exactly one line (which is no longer than 32,000 characters) of the form:
            ( E1 E2 . . . En )
      where n > 0 and Ei is either T for true, F for false, or a sub-expression using the same format.
      The trees at the deepest level are AND-trees. The last test case is followed by a dummy line made of ().

      Output

      For each test case, print the following line:
      k. E
      Where k is the test case number (starting at one,) and E is either true or false depending on the value of the expression in that test case.

      Example

      Input:
      ((F(TF))(TF))
      (TFT)
      ((TFT)T)
      ()

      Output:
      1. false
      2. false
      3. true

      Added by:Omar ElAzazy
      Date:2010-12-27
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACPC 2010









      SPOJ Problem Set (classical)

      8108. POLYU

      Problem code: POLYU

      In the country of Giantarum, the king of Giantarum is AC.AC and his billions of hougong like to eat giantarum very much. The shape of giantarum is special! It could be regard as a triangle. There are N giantarums in the Cartesian coordinates, they may cover each other. AC wants to know the total area that is covered by giantarums.

      Input

      In the first line there is an integer T, indicates the number of test cases.(T<=100)

      In each case, the first line contains an integer N (N <= 100), indicates the number of the giantarum. The follow N line, every line contains six floating numbers x0, y0, x1, y2, x2, y2, indicates the coordinate of the three vertices of the giantarum. (all |xi| <= 10^4 and |yi| <= 10^4)

      Output

      For every test case, output one line. First output “Case idx: ”, here idx is the case number start from 1.Then output the area, rounded to 3 digits after the decimal point.

      Example

      Input:
      2
      1
      0 0 1 0 1 1
      2
      0 0 1 0 1 1
      0 0 0 1 1 1


      Output:
      Case 1: 0.500
      Case 2: 1.000


      Added by:aekdycoin
      Date:2011-01-01
      Time limit:1s-26s
      Source limit:7000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:AekdyCoin









      SPOJ Problem Set (classical)

      8119. CIRU2

      Problem code: CIRUT


      You are given N different circles , while some region may be covered more than once.

      If one region is covered by K times, then it was called a "K- Region".

      So, you are expected to output the area of all the regions! (K from 1 to N)

       

      Input

      The first line is one integer n indicates the number of the circles. (1 <= n <= 1000)

      Then follows n lines every line has three integers

      Xi Yi Ri

      indicates the coordinate of the center of the circle, and the radius. (|Xi|. |Yi|  <= 1000, 0 < Ri <= 1000)

       

      Output

      Output N lines, the i-th line output

      [i] = area_of_i_region

      here the area must round to  3 digits after decimal point.

       

      Example

      Input:
      3
      0 0 1
      1 0 1
      1 1 1

      Output: [1] = 4.699
      [2] = 1.699
      [3] = 0.443

      Added by:aekdycoin
      Date:2011-01-03
      Time limit:1s-4s
      Source limit:80000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:AekdyCoin









      SPOJ Problem Set (classical)

      8129. Sky Lift

      Problem code: SKY

      We can represent a grid of skyscrapers by an NxN matrix of their positive heights. A skyscraper is made out of square blocks, and you may travel through them using a special elevator that can move as any other, but also sideways (four possible directions on a fixed floor). They may move anywhere as long as they don't exit the skyscrapers. In other words, if the elevator is inside a skyscraper, it may move to the neighboring skyscraper only if its height is greater or equal to the current level the elevator is at.

      Moving sideways (in one of the 4 directions, that is, N, E, S, W...) is done for free when using this elevator, but moving one floor up or down costs exactly one unit.

      Given the positions of two skyscrapers, find the cost of moving from the top block of the first to the top block of the second using the described elevator.

      Input

      The first line of input contains a single integer N ( 1 <= N <= 1000 ). The next line contains four integers, xa, ya, xb, yb, (between 1 and N), representing the positions of the two skyscrapers.

      The next line contains three integers: A, B and C (1 <= A, B, C <= 109).

      Generate the height of the skyscraper at coordinates (i, j) using the formula hij = (((i-1)*N+j-1)*A + B) mod C (indicies are 1-based).

      Output

      To the first and only line of input output the solution.

      Example

      Input: 
      3
      1 1 3 3
      5 5 7

      Output:
      2

      Added by:Gustav Matula
      Date:2011-01-03
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8132. Street Trees

      Problem code: STREETR

      A group of trees is planted along a straight line.

      KOI is planning to plant more trees so that the distance between two adjacent trees is equal for all trees.

      For simplicity, each tree can only be planted on an integer coordinate.

      For example, if 4 trees were originally planted on coordinates (1,3,7,13), and if KOI plants 3 more trees on coordinates (5,9,11), then the distance between two adjacent trees will equal for all trees.

      Your task is to calculate the minimal number of trees that KOI can plant so that the distance between two adjacent trees will equal for all trees.

      Input

      The first line is an integer N (3<=N<=100,000), which denotes the number of already planted trees.

      The next N lines will have an integer X (1<=X<=1,000,000,000), which denotes the coordinate of each tree. 

      You can safely assume that the value of X will be unique. 

      Output

      Output the minimal number of trees that must be planted.

      Example

      Input:
      4
      1
      3
      7
      13
      Output:
      3
      Input:
      4
      2
      6
      12
      18
      Output:
      5

      Added by:Joon Young Seo
      Date:2011-01-05
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:2010 KOI High School Division









      SPOJ Problem Set (classical)

      8139. Chairs

      Problem code: CHAIR

      N chairs are placed in a circle.

      There will be K attendants to a very important meeting.

      However, the attendants do not like each other, so they do not want to sit beside each other in the meeting.

      As the host of this important meeting, you want to find out how many ways there are to choose K chairs such that none of them are adjacent to each other. 

      Input

      The first line of the input is an integer N (4<=N<=1000), which denotes the number of chairs.

      The next line is an integer K (1<=K<=N), which denotes the number of attendants to the meeting.

      Output

      Output the total number of ways to choose K chairs from N chairs such that none of the chairs are adjacent.

      Since the answer can get very large, output the answer modulo 1,000,000,003.

      Example

      Input:
      4
      2
      Output:
      2
      

      Added by:Joon Young Seo
      Date:2011-01-06
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Based on a problem in 2010 KOI High School & Middle School Division









      SPOJ Problem Set (classical)

      8177. Beautiful numbers EXTREME

      Problem code: JZPEXT

      We call one integer beautiful, if and only if it is divisible by each of its non-zero digits. Given an interval [l, r], calculate how many beautiful numbers n satisfy l<=n<=r.

      Input

      Then t lines follow, each line two numbers l, r, representing the query interval [l, r]

      First line, the number of test cases, t.

      Then t lines follow, each line two numbers l, r, representing the query interval [l, r].

      1<=t<=2.5*10^4

      1<=l<=r<=10^18

      Output

      t lines. The t-th line is the answer to the t-th query.

      Example

      Input:
      1
      1 100
      Output:
      33
      

      Added by:sevenkplus
      Date:2011-01-17
      Time limit:1s
      Source limit:1024B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8184. Bureaucracy

      Problem code: BUREAU

       

      Many centuries later lawyers discovered that there were only two types of laws in the kingdom:
      ² direct law, that states a new norm;
      ² canceling law, that cancels one of the previous laws.
      The law is considered active if and only if there is no active law that cancels it.
      You are to write program that ¯nds out which laws are still active.

      Long ago, in a kingdom far, far away the king decided to keep a record of all laws of his kingdom. From that moment whenever a new law was passed, a corresponding record was added to the law archive.

      Many centuries later lawyers discovered that there were only two types of laws in the kingdom:

      • direct law, that states a new norm;
      • canceling law, that cancels one of the previous laws.

      The law is considered active if and only if there is no active law that cancels it.

      You are to write program that finds out which laws are still active.

       

      Input

      The first line of the input contains T, the number of test cases. T test cases follow.

      The first line of each test case contains an integer number n (1 <= n <= 100000) - the number of passed laws.

      The following n lines describe one law each. Each description has one of the following formats:

      • "declare", meaning that a direct law was passed.
      • "cancel i", where i is the number of law being cancelled by this one.

      The laws are numbered from one.

       

      Output

      For each test case your output must contain a line with the number of active laws. The following line must contain numbers of these laws listed in increasing order.

       

      Example

      Input:
      1
      5
      declare
      cancel 1
      declare
      cancel 2
      cancel 3
      
      Output:
      3
      1 4 5

      Added by:Fidel Schaposnik
      Date:2011-01-19
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC 2009, NEERC, Northern Subregional Contest









      SPOJ Problem Set (classical)

      8189. Circles On A Screen

      Problem code: CIRCSCR

      Yesterday Andrew wrote a program that draws n white circles on a black screen. The screen is monochrome and it has a resolution w x h pixels. Pixels are numbered from upper left corner (0, 0) to bottom right one (w-1, h-1).

      A circle with the center at pixel (xc, yc) and the radius r consists of the pixels with coordinates (x, y) such that (xc-x)2 + (yc-y)2 <= r2 . If the circle does not fit on the screen, it is truncated. If some pixel belongs to two or more circles, it is white.

      Example

      The resulting picture was very nice, so Andrew decided to copy it to his wall. He has white wallpaper and he can only draw some parts of wall into black. Now he wants to know the amount of paint he needs.

      He copies the picture exactly pixel-to-pixel, so you should write a program that calculates the number of black pixels left on a screen after drawing n circles.

       

      Input

      In the first line of input file there is an integer T, the number of test cases. T test cases follow.

      Each test case begins with a line where there are three integers: w, h, and n (1 <= w, h <= 20.000; 1 <= n <= 100). Each of the following n lines contains descriptions of the circles. In i+1-th line there are three integers: xi, yi, ri (0 <= xi < w; 0 <= yi < h; 0 <= ri <= 40 000). They denote a circle with the center at pixel (xi, yi) and radius ri.

       

      Output

      For each test case you should output exactly one number - the number of black pixels left on the screen.

       

      Example

      Input:
      2
      5 3 2
      1 1 1
      3 1 1
      12 9 2
      3 3 2
      7 5 4
      
      Output:
      6
      51

      Note: The picture corresponds to the second test case of the example.


      Added by:Fidel Schaposnik
      Date:2011-01-20
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC 2009, NEERC, Northern Subregional Contest









      SPOJ Problem Set (classical)

      8217. XOR Maximization

      Problem code: XMAX

      Given a set of integers S = { a1, a2, a3, ... a|S| }, we define a function X on S as follows:
      X( S ) = a1 ^ a2 ^ a3 ^ ... ^ a|S|.
      (^ stands for bitwise 'XOR' or 'exclusive or')

      Given a set of N integers, compute the maximum of the X-function over all the subsets of the given starting set.

      Input

      The first line of input contains a single integer N, 1 <= N <= 105.
      Each of the next N lines contain an integer ai, 1 <= ai <= 1018.

      Output

      To the first line of output print the solution.

      Example

      Input:

      3
      1
      2
      4
      Output:

      7

      Added by:Gustav Matula
      Date:2011-01-26
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem, similar problem reported from CPSPC though...









      SPOJ Problem Set (classical)

      8222. Substrings

      Problem code: NSUBSTR

      You are given a string S which consists of 250000 lowercase latin letters at most. We define F(x) as the maximal number of times that some string with length x appears in S. For example for string 'ababa' F(3) will be 2 because there is a string 'aba' that occurs twice. Your task is to output F(i) for every i so that 1<=i<=|S|.

      Input

      String S consists of at most 250000 lowercase latin letters.

      Output

      Output |S| lines. On the i-th line output F(i).

      Example

      Input:
      ababa

      Output:
      3
      2
      2
      1
      1

      Added by:Tooru Ichii
      Date:2011-01-27
      Time limit:1s-2s
      Source limit:44444B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Immagination









      SPOJ Problem Set ()

      8238. N-Factorful

      Problem code: NFACTOR

      A number is called n-factorful if it has exactly n distinct prime factors. Given positive integers ab, and n, your task is to find the number of integers between a and b, inclusive, that are n-factorful. We consider 1 to be 0-factorful.

      Input

      Your input will consist of a single integer T followed by a newline and T test cases. Each test cases consists of a single line containing integers ab, and n as described above.

       

      T > 10000
      1 ≤ a ≤ b ≤ 106
      0 ≤ n ≤ 10

      Output

      Output for each test case one line containing the number of n-factorful integers in [ab].

      Example

      Input:
      
      
      5
      1 3 1
      1 10 2
      1 10 3
      1 100 3
      1 1000 0
      Output:
      
      2
      2
      0
      8
      1

      Added by:gogo40
      Date:2011-01-30
      Time limit:10s-20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:Facebook Hacker Cup 2011 Round 1C









      SPOJ Problem Set (classical)

      8263. Big Pyramid

      Problem code: EMILABC

      Archeologists have discovered an ancient manuscript describing a big pyramid. The pyramid is built of cubical stone blocks as shown in the picture. There are N horisontal levels in the pyramid. The topmost level consists of a single block, and the base level is a square of 2*N-1×2*N-1 blocks. The archeologists learned from the manuscript the size of a stone block and the orientation the pyramid. However, they do not know the size and the exact location of the pyramid.

      There are many hills in the land where the pyramid is believed to be located. The archeologists think that one of the hills is actually the pyramid covered with sand. To check that hypothesis, they produced an elevation map of the land. The land was divided into a grid of H×W cells. The size of a cell is the same as the size of a stone block face. For each cell they measured its height and calculated how many stone blocks can be underneath the surface of the cell.

      Now the archeologists give you the elevation map and ask to compute the largest possible pyramid size, assuming that the pyramid base sides are parallel to the grid lines.


      Input

      The first line of the input contains two integers H and W (0<H,W≤200). Each of the subsequent H lines contains W integers. Each integer is non-negative and less than 201.

      Output

      One interger - the number of levels in the larget possible pyramid.

      Input:

      5 6
      0 0 0 0 0 0
      0 1 0 0 0 0
      0 0 1 1 1 1
      0 0 1 1 2 1
      0 0 1 1 1 1

      Output:

       2


      Added by:Azat Taryhchiyev
      Date:2011-02-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8 C99 strict JAR JAVA NODEJS PAS fpc PAS gpc PYTH 3.2.3 n
      Resource:International Sebat Institutions









      SPOJ Problem Set (classical)

      8265. Zero Count

      Problem code: ZEROCNT

      Write down N integers 1, 2, ..., N in binary system on a paper, one per line, ignore all leading 0s:

      1

      10

      11

      100

      101

      110

      111

      ...

      Now on each line, consider all groups of consecutive 0s, index these group from 1. We will color all zeros in the 1st, (K+1)th, (2K+1)th, ... group, for K is a given integer.

      For example: if a number in binary is: 10100011100110000, and K = 2. We have 4 groups of consecutive 0s, and we will color all zeros in the 1st and the 3rd group. So we will color 1 + 2 = 3 zeros in this line.

      Given N and K. Compute total number of 0s we will color in the paper. (The paper is big enough to contain all numbers :D)

      Input

      Several lines, each line contains 2 integers: N and K separated by a single space. (1 < N < 231, K > 0)

      Output

      For each line in the input, print exactly 1 number on a single line which is the result of the corresponding test case.

      Example

      Input:
      4 1
      56 2
      Output:
      3
      92

      Added by:Race with time
      Date:2011-02-05
      Time limit:1s
      Source limit:700B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:VOJ









      SPOJ Problem Set (classical)

      8277. Number of Prime Strings

      Problem code: PSTR

      A string is called a "prime string" if it can't be written as concatenation of more than one same strings. For example, the following strings are not prime strings: AAA, ABABAB, CFGFGCFGFG, while CFGFGC, ABABA are prime strings.
      Calculate the number of prime string of length N (1<=N<=1000000), and only contains first K (1<=K<=26) letters from English alphabet. Note that some of these K letters need not appear in that string.

      Input

      Multiple test cases. The number of them (about 10000) is given in the very first line.
      Each test case contains one line with two integers - K and N, seperated by a single space.

      Output

      For each test case, output the required number modulo 1000000007 in a single line.

      Example

      Input:
      1
      2 3
      Output:
      6
      Explanation
      The prime strings of length 3 which only contain character 'A' and 'B' are: AAB,ABA,ABB,BAA,BAB,BBA.

      Constraints

      1 <= N <= 1000000 1 <= K <= 26
      Total number of test cases is around 10000.


      Added by:Kunal Jain
      Date:2011-02-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeCraft 11









      SPOJ Problem Set (classical)

      8281. Combination Of Integers

      Problem code: INTCOMB

      You will be given n positive integers a_1, a_2, ..., a_n. We say that a nonnegative integer combination of these numbers is of the form a_1*b_1 + a_2*b_2 + ... + a_n*b_n where each of b_1, b_2, ..., b_n is a nonnegative integer. You are to determine how many positive integers cannot be expressed as a nonnegative integer combination of a_1, a_2, ..., a_n.

      Input

      The first line contains a single integer denoting the number of test cases (about 30). Each test case consists of a single line. The first integer on the line is n, between 1 and 30, which indicates the number of integers a_1, a_2, ..., a_n. Then n integers follow each between 1 and 100,000. The i'th such integer is a_i. All integers on this line are separated by a space.

      Output

      For each test case you are to output a single line. If there are only a finite number of positive integers that cannot be expressed as a nonnegative integer combination of a_1, a_2, ..., a_n, then you are to output this number. Otherwise, simply output the text "Infinite" (without quotes).

      Example

      Input:
      3
      2 2 4
      2 4 5
      3 11 12 13
      Output: Infinite
      6
      30
      Explanation
      Sample Test 2 :
      You cannot express 1,2,3,6,7 and 11 using only the integers 4 and 5.

      Constraints

      1 <= n <= 30
      1 <= a_i <= 100000


      Added by:Kunal Jain
      Date:2011-02-07
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeCraft 11









      SPOJ Problem Set (classical)

      8282. Distance

      Problem code: DIST

      You are given the coordinates of N cities (xi,yi). Each city also has a popularity value, pi. You have to place a new city (x,y) such that the sum of distances of this new point from all the other given points is minimized.
      Distance of the new point from a given city i is given by :
      d = |xi - x| ^ pi + | yi - y | ^ pi

      Input

      There are multiple test cases.
      First line contains the number of testcases.
      Each testcases starts with the number N, the number of points.
      This is followed by the descriptions of each in the format
      xi yi pi
      The input consists of only integers

      Output

      For each testcase, output the minimum distance obtained, with exactly 3 digits after the decimal point.

      Example

      Input:
      1
      3
      1 2 0
      4 5 1
      2 4 2
      Output: 4.500

      Constraints

      No. of testcases <= 10
      N <= 10^5
      |xi,yi| <= 1000
      0 <= pi <= 3


      Added by:Kunal Jain
      Date:2011-02-07
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeCraft 11









      SPOJ Problem Set (classical)

      8283. Non-Decreasing Numbers

      Problem code: NONDEC

      A Non-Decreasing number is a number whose ith digit from the left it greater than or equal to the (i-1)th digit from the left.
      You are given four integers A, B, C and D. X is any integer b/w A and B, inclusive, and Y is any integer b/w C and D, inclusive. You must output the number of numbers formed by the concatenation of X and Y which are Non-Decreasing, i.e. if we treat "X" and "Y" as STRINGS, then "Z" = "X" + "Y" must represent a Non-Decreasing number.
      Since this number can be very large, give your answer modulo 98765431.
      If the same number "Z" can be formed in various ways, it must be counted every time. See example for clarification.

      Input

      The first line of the input contains t, the number of test cases.
      This is followed by t lines containing 4 positive integers each, which are the values of A, B, C, D.

      Output

      You must output t lines. Each line contains the answers for the quadruple (A, B, C, D) in the order they appear in input.

      Example

      Input:
      1
      1 11 1 11 Output: 56

      Explanation
      Note that the number "111" is counted twice. Once as "11" + "1" and again as "1" + "11".

      Constraints

      A, B, C, D are all positive integers having <= 1000 digits
      A <= B; C <= D;
      Number of test cases = t <= 1000


      Added by:Kunal Jain
      Date:2011-02-07
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeCraft 11









      SPOJ Problem Set (classical)

      8284. Weighted Sum

      Problem code: WEIGHT

      You are given N integers, A[1] to A[N]. You have to assign weights to these integers such that their weighted sum is maximized. The weights should satisfy the following conditions :

      1. Each weight should be an positive integer.
      2. W[1] = 1
      3. W[i] should be in the range [2, W[i-1] + 1] for i > 1

      Weighted sum is defined as S = A[1] * W[1] + A[2] * W[2] + ... + A[N] * W[N]

      Input

      There are multiple test cases.
      First line contains the number of test cases
      Each test case consists of a single line containing N.
      This is followed by N lines, each containing A[i]

      Output

      For each test case, output one line - the maximum weighted sum.

      Example

      Input:
      1
      4
      1
      2
      3
      -4
      Output: 6
      Explanation
      The weights are 1,2,3,2

      Constraints

      N <= 10^6
      | A[i] | <= 10^6
      Total number of test cases is around 10.


      Added by:Kunal Jain
      Date:2011-02-07
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeCraft 11









      SPOJ Problem Set (classical)

      8285. Rectangles in a Matrix

      Problem code: RECTMAT

      In a matrix with n rows and m columns, (i,j) is the cell in i-th row and j-th column(0<=i<n,0<=j<m). A rectangle (r0,r1,c0,c1) in a matrix is the set of cells (i,j) where r0 <= i < r1 and c0 <= j < c1. (0<=r0 < r1 <= n, 0 <= c0 <c1 <= m). Two rectangles are called independent if the intersection of their cell set is empty.
      Given n,m,k, find the number of ways to choose k independent rectangles from a nxm matrix. The order of these k rectangles doesn't matter, see sample for further clarification.

      Input


      One line contains three integers n,m,k(1<=n,m<=1000, 1<=k<=6).

      Output

      For each test case, output the number of ways, modulo 10^9+7.

      Example

      Input:
      2 2 4
      10 10 1
      Output:
      1
      3025
      Explanation
      First case: You have to find the number of ways of choosing 4 independent rectangles from a 2x2 matrix.
      The only way to do this is to choose each cell as a separate rectangle.

      Constraints

      (1<=n,m<=1000, 1<=k<=6).
      Total number of test cases is around 150. Not all the test cases are included.


      Added by:Kunal Jain
      Date:2011-02-07
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeCraft 11









      SPOJ Problem Set (classical)

      8286. Perfect Matching

      Problem code: MATCH

      You are given a bipartite graph with N(1<=N<=300) nodes on each side. Determine whether the number of perfect matching is odd or even.

      Input

      First line is an integer T(1<=T<=20) means the number of test cases. The following are T parts. Each part begin with an integer N(1<=N<=300) means the number of nodes on both sides. It followed with N lines, each line contains a 0/1 string. If the j(1<=j<=N)th character of the i(1<=i<=N)th line is 1, it means the i th node on left have an edge to the j th node on right. See the sample for details.

      Output

      T lines, each contain "Odd" or "Even", which means the parity of the number of the perfect matching. See the sample for details.

      Example

      Input:
      2
      1
      1
      4
      1100
      1100
      0011
      0011
      Output: Odd
      Even

      Constraints

      1 <=N <= 300
      1 <=T <= 20


      Added by:Kunal Jain
      Date:2011-02-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeCraft 11









      SPOJ Problem Set (classical)

      8288. Fast Food Restaurant

      Problem code: FASTFOOD

      Hong Kil Dong wants to open a new fast food restaurant to make some money. The picture below describes the city where he wants to open his restaurant. The nodes are the possible locations that he can set up his new restuarant, and the edges are the length of the road connecting the two locations. You can assume that maximum five roads intersect at a single node, and that it is possible to reach all nodes from any chosen node.

      There are three apartments (these three are the only places people live in) in this city, denoted A, B, and C, as shown in the picture.

      Graph

      Suppose he wants to open his new restuarant in location (node) 1. The shortest distances from location 1 to A, B, and C are 8, 16, and 9 respectively. These values are each larger than the shortest distances from location 4 to A, B, and C, which are 6, 7, and 3. Since people usually prefer using closer restuarants, it is better to open his restaurant in location 4.

      Consider location 6. The shortest distances from location 6 to A, B, and C are 5, 3, and 5. Therefore, location 6 is better than location 1. However, when comparing with location 4, it is better regarding A and B, but worse when considering C.

      Therefore, Hong Kil Dong came up with a criteria to determine whether a given location is good or bad.

      Consider location p, and let the shortest distances from location p to A, B, and C be a, b, and c, respectively.        

      Consider another location q, and let the shortest distances from location q to A, B, and C be x, y, z, respectively.

      If a>x, b>y and c>z, we say that location p is a bad location. If there is no location q that satisfies this, we say that location p is a good location.

      Hong Kil Dong has chosen some candidate locations. Given the description of the city and a number of queries, determine whether each candidate location is good or bad.

      Note that it is possible to open the restaurant in any of the locations, even in  A, B, and C.

      Input

      The first line of the input is an integer N (1<=N<=100,000), denoting the number of locations.  All the locations are numbered from 1-N.

      The second line of the input is three integers A, B, and C, denoting the location of each apartment. A, B, and C are all distinct and are between 1 and N, inclusive.

      The third line of the input is M, denoting the number of roads in this city.

      The next M lines give the description of each road and consist of integer X, Y, and Z (1<=Z<=10,000). X and Y are the two endpoints of this road, and Z is the length of this road. No two same roads appear in the input.

      The next line is an integer T (1<=T<=10,000), denoting the number of queries.

      The next T lines each consist of an integer Q (1<=Q<=N), which denote the location number. 

      Output

      For each query, determine whether location Q is a good location or a bad location. If it is bad, output "NO" (quotes for clarity) and "YES" if it is good.

      Example

      Input:
      9
      2 5 9
      15
      1 2 8
      1 3 5
      2 4 6
      2 5 8
      2 6 5
      3 4 6
      3 9 4
      4 6 4
      4 9 3
      5 6 3
      5 7 4
      6 7 2
      6 9 5
      7 8 7
      8 9 6
      2
      1
      2
      Output: NO
      YES

      Added by:Joon Young Seo
      Date:2011-02-10
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:2010 KOI Final Stage Middle School & High School Division









      SPOJ Problem Set (main)

      8316. Win gold medal

      Problem code: WINGOLD

      In a game there are infinite number of levels. In order to go to the next level,a player has to clear all the preceding levels. A player cant go further,if he fails to clear the level. Each player has a probability p of clearing the level (which is independent of the other players and the level number). For example, if p =1/2 there is a probability 2^(-n-1) that a particular game will have exactly n levels cleared.A player will get Gold medal if he clears the maximum number of levels. If the maximum number of levels reached is common between two or more players, then no one wins the gold medal.What is the probability that a Gold medal is given to any player?

      Input

      T number of test cases each case follow
      p n m . probability of clearing level for each player, number of player, number of levels in game

      Output

      T line each probability that gold medal is given round off to 4 significant digits

      limit:

      1<=T<10000
      1<=n<1000
      1<=m<100
      0<=p<=1.0

      Example

      Input:
      6
      0.43 3 2
      0.5 3 4
      0.2 3 4
      0.1 4 5
      0.9 3 3
      1.0 4 4
      Output: 0.4490
      0.6244
      0.4184
      0.3014
      0.0275
      0.0000

      Added by:pankaj
      Date:2011-02-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8
      Resource:own, DOPE 2011









      SPOJ Problem Set (classical)

      8317. Red Balls

      Problem code: SIGNGAME


      After the previous game ,each ball is either red or green in color. Dope tells you that he is changing the color of all balls in the range i to j (both inclusive),that is red balls to green and green balls to red.And then he asks you to tell the total extra mass of red balls over green balls for some range between i to j (inclusively). As you like red balls,you will try to maximize the total mass of red balls mass over the green balls. So He allows you to choose any range inside the range i, j inclusively which gives the maximum extra mass of red balls over the green balls .When you choose a range, you have to take all the green and red balls that belong to the range.

      Convention:
      (+) positive mass represents red ball mass
      (-) negative mass represents green ball mass

      Input

      T number of test cases
      next T test cases follow each contains:
      N number of balls
      next line contains N mass of ball ( positive or negative)
      next line Q number of operation and query next Q lines contain
      c a b
      c =0 change the color of balls in range a, b inclusively
      c =1 print the maximum extra mass of red bass over green in the range a,b inclusively

      Output

      each line for print query

      limit:
      1<=T<10
      1<=N<100000
      1<=Q<100000
      0<=a<=b<N
      c = 0 or 1
      abs(individual mass )<1000

      Example

      Input:
      1
      5
      2 -3 4 5 -2
      4
      0 0 2
      1 0 2
      1 1 3
      0 1 1

      Output:
      3
      5

      [you have to choose a range, if all balls are green in the range you have to print (-)ve answer]


      Added by:pankaj
      Date:2011-02-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own, DOPE 2011









      SPOJ Problem Set (classical)

      8318. color the balls

      Problem code: PLAYSIGN


      You and Dope are visiting DAKSH. Suddenly Dope found some balls having some mass on it and all balls are white in color. They found an interesting thing of the balls that they can change color to either red or green on clicking the switch on it.Dope is in a funny mood and wants to play a game with you. He tells you that each player will switch the balls to either red or green color alternatively and only white ball can be chosen to change the color.After changing the color of all balls you need to pay an amount equal to the absolute difference between mass of the red balls and green balls. Dopen would try to maximize the pay and obviously you want to give him as less as possible. Dope invites you to play first. If you and Dope play optimally, what is the amount you have to pay to Dope?

      Input

      T number of test cases. Each case consists of two lines. first line N number of white balls. Next line contains a b c use to generate N mass using
      mass = (a*i+b)%c; for 1<=i<=N

      Output

      single line for each case the amount you need to pay

      limit:
      1<=T<1000
      1<=N<10000

      1<=a,c<1000
      0<=b<1000

      Example

      Input:
      2
      3
      1 0 10
      4
      2 1 10
      Output:
      2
      10

      explanation:
      case1: 3 mass = 1 2 3; output = 2
      case2: 4 mass=3 5 7 9;output=10

      Added by:pankaj
      Date:2011-02-13
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own, DOPE 2011









      SPOJ Problem Set (classical)

      8319. GLJIVE

      Problem code: GLJIVE

      In front of Super Mario there are 10 mushrooms, arranged in a row. A certain amount of points is
      awarded for picking each of the mushrooms. Super Mario must pick mushrooms in order they appear,
      but is not required to pick them all – his goal is to score a number of points as close as possible to
      100.
      In case there exist two such numbers which are equally close to 100 (e.g. 98 and 102), Mario will pick
      the greater one (in this case 102).
      Help Super Mario and tell him how many points he will score.

      Input

      Input consists of 10 lines, each of which contains one positive integer less than or equal to 100,
      denoting the scores awarded for picking each mushroom, in the order that Mario can pick them in.

      Output

      The first and only line of output must contain the required number of points.

      Example

      Input:
      

      10

      20

      30

      40

      50

      60

      70

      80

      90

      100

      Output:

      100


      Added by:akaki
      Date:2011-02-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:coci









      SPOJ Problem Set (classical)

      8320. Spreadsheet scrolling

      Problem code: SCROLL

      Sruthi is looking at a spreadsheet containing N rows. Only K rows of the spreadsheet are visible at a time (If the top row is i, the bottom row will be i+K-1). In the beginning, rows 1..K are visible. Sruthi needs to read certain values from rows r1,r2...rM in that order. It is possible to scroll the spreadsheet so that the rows j..j+K-1 can be viewed instead of the current i..i+K-1. This operation counts as one scroll and its scroll length is defined as |j-i|

      Find the minimum number of scrolls required so that Sruthi can read of all the M values in the given order. As there may be more than one way to do this, also find the minimum total scroll length required to do the reading in so many scrolls.

      Input

      The first line of the input contains the integer T (<=20), the number of test cases to follow.

      The description of each test case begins with a line containing 3 integers N(<=10^8), K(<=10^8) and M(<=50000) as defined in the problem. Following this are M lines giving the row numbers from which values have to be read sequentially.

      Output

      Output two space separated integers in a line per test case : The minimum number of scrolls required and the minimum scroll length required for the minimum number of scrolls.

      Example

      Input:
      2
      20 10 2
      10
      20
      20 10 2
      10
      7
      
      Output:
      1 10
      0 0
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8321. Chocolate distribution

      Problem code: CHOCDIST

      In Dystopia, chocolates are being distributed to children waiting in a queue. The distribution proceeds as follows. Each chocolate bar is rectangular in shape with integer edge lengths. If the chocolate bar is a square, it is given away completely to the first child in the queue. Otherwise the largest possible square piece of chocolate is broken off from the chocolate bar and given to the first child. After a child receives his share of chocolate, he leaves the queue. The remaining portion of the chocolate bar is dealt with in the same fashion and the whole or a portion of it is given to the next child in the queue.

      For example, if we start with a 5x3 chocolate bar, the first child in the queue receives a 3x3 chocolate bar, leaving a 2x3 bar. The second child gets a 2x2 bar while the third and fourth children get 1x1 bars. Thus four children have been fed using the 5x3 bar.

      The Dystopian government has got a carton of chocolate bars to be distributed to children in the country. To make sure that maximum inequality is achieved while distributing chocolates, the chocolate bars in the carton are all of different sizes. For every i such that M<=i<=N and every j such that P<=j<=Q (where M,N,P,Q are integers) there is exactly one chocolate bar of length i and breadth j in the carton. Here a bar of length i and breadth j is considered to be different from a bar of length j and breadth i.

      Given the values of M,N,P,Q find the number of children that can be fed with the chocolate in the carton.

      Input

      The first line of the input contains the number of test cases, T (<=1000)

      Following this are T lines, each describing a test case with four integers M,N,P,Q separated by spaces (1<=M<=N<=100000000, 1<=P<=Q<=1000)

      Output

      Output T lines, each containing an integer : The number of children that can be fed using the chocolate in the carton

      Example

      Input:
      2
      1 2 1 2
      3 4 4 5
      
      Output:
      6
      14
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8323. Triangle equality

      Problem code: TRIEQUAL


      Consider three distinct points A,B,C on a plane. The sum of straight line distances from A to B and B to C is always greater than or equal to the straight line distance from A to C. Equality holds only when ABC is a degenerate triangle. This is the famous triangle inequality

      In this case, distance between points is measured by the Euclidean metric. ie, the distance between points (x1,y1) and (x2,y2) is given by sqrt((x1-x2)2+(y1-y2)2). However, this is not the only metric possible. Another common metric used is the Manhattan metric where the distance between the pair of points is given by |x1-x2|+|y1-y2|

      You are given N distinct points on a plane where distances are measured using the Manhattan metric. Find the number of ordered triplets of distinct points (A,B,C) such that the sum of distances from A to B and B to C is equal to the distance from A to C.

      Input

      The first line of input contains an integer T (<=10), the number of test cases to follow.

      Following this are the descriptions of T test cases. Each test case description begins with an integer N (<=50000), the number of points. Following this are N lines, each giving the x and y coordinates of a point (0<=xi,yi<=108) separated by a space.

      Output

      Output T lines, each containing the number of ordered triplets of distinct points in every test case with the given property

      Example

      Input:
      2
      3
      0 0
      1 1
      2 2
      3
      0 0
      1 2
      2 1
      
      Output:
      2
      0
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8324. Military patrol

      Problem code: MILPATR


      Dystopia consists of N cities. There are one-way roads connecting some pairs of cities. The dysfunctional state has recently seen a lot of protests to overthrow the tyrannical ruler and the government plans to use military patrol vehicles to make sure that the protests are suppressed. Every patrol vehicle is assigned a sequence of cities. If a patrol vehicle is assigned the cities c1,c2,...ck then it starts from the city c1 and takes the direct one-way road to c2, from there it takes the one-way road to c3 and so on. Finally the vehicle takes the one way road from ck to c1. This routine is repeated everyday to keep the protestors perpetually under fear.

      Now note that:

      • Every city has to appear in exactly one vehicle's patrol sequence exactly once
      • Every patrol vehicle has to move - so it has to be assigned more than one city

       

      The government does not have any limit on the number of patrol vehicles it can use. However, they want to make sure that the least possible amount of money is spent on the patrol mission and hence they want to minimise the total distance travelled by the patrol vehicles.

      Given the road network of Dystopia, find the minimum total distance the patrol vehicles need to move so that all the cities can be patrolled. If it is impossible to organise a nationwide patrol with the given constraints, report the same.

      Input

      First line of the contains T, the number of test cases (T<=10)

      This is followed by the descriptions of the T testcases. The first line of the description contains two integers N and R, the number of cities and one way roads respectively (N<=200,R<=10000). The cities are numbered 1,2,3,...N This is followed by R lines, each representing a one way road by 3 integers N1, N2 and D : the start city, the end city and the length of the road respectively ( N1!=N2, 1<=D<=1000000). You are assured that there is no more than one one way road from any N1 to N2

      Output

      For each test case output one line. If the patrol can be done, output the minimum total distance that the patrol vehicles have to travel. Otherwise output Impossible

      Example

      Input:
      2
      3 3
      1 2 1
      2 3 1
      1 3 1
      4 6
      1 2 2
      2 3 2
      3 4 2
      4 1 2
      1 4 1
      3 2 1
      
      Output:
      Impossible
      6
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8325. Partitioning the plane

      Problem code: PARTPLNE

      You are given the coordinates of 4*K+5 points on a plane such that no three of them are collinear. You need to select five points from these : a central point O and four arm points A,B,C,D such that:

      • Rays from the centre to the arm points divide the plane into four regions containing an equal number of points
      • None of the four central angles is a reflex angle
      • Sum of absolute values of the cotangents of the central angles is as low as possible

       

      If it is possible to choose points satisfying this condition, output the lowest possible value for the sum of absolute values of the cotangents of the central angles. Otherwise report that it is not possible.

      Input

      The first line of input contains T(<=4), the number of test cases. Following this are the descriptions of the T test cases.

      The first line in the description of each test case gives K(<=100). Following this are 4*K+5 lines giving the x and y coordinates of each point separated by a space (0<=x,y<=106)

      Output

      For each test case output in a different line the minimum sum of absolute values of the cotangents of the central angles, with six digits after the decimal point. If the division cannot be done in the manner explained, print Impossible

      Example

      Input:
      2
      0
      0 0
      0 1
      1 1
      1 0
      2 3
      0
      0 0
      2 0
      0 1
      2 1
      1 2

      Output:
      4.500000
      Impossible

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8326. Leaky containers

      Problem code: LEAKCONT

      The acid manufacturing company has a special room to store leaky acid containers. The container holders in the room, which have the capacity to hold one leaky container each, are arranged in a rectangular grid of R rows and C columns such that the columns are in the North-South direction while the rows are in the East-West direction. Currently there are N leaky containers in some of the holders and M more have just arrived and need to be placed in the holders.

      The company has realised that the containers being produced these days are exceptionally leaky. So much so that the acid that is leaking is corroding the holders completely.

      Every acid container leaks either in the North-South direction or the East-West direction. Containers can be rotated by 90 degrees and thus a container that is leaking in the East-West direction can be made to leak North-South and vice versa. Given enough time, a leaky container can corrode the holder completely and start corroding the two adjacent holders in the leak direction and this process can go on.

      The company employee has to make a decision fast. He needs to rotate some of the existing containers and place the new containers in proper holders and directions such that the total number of holders that will be corroded is minimised.

      Find out the minimum number of holders that will be corroded after proper placement of the new containers and proper orientation of all containers.

      Input

      The first line of the input contains the number of test cases T (<=10).

      For each test case, the first line has four numbers R, C, N and M (1<=R,C<=100, 1<=M,N<=20, M+N<=R*C). This is followed by N lines, each giving the location and leak direction of an existing container by 3 integers r (row number), c (column number) and d (1 if leakage is N-S, 0 if E-W). Numbering of rows and columns begins with 1.

      Output

      For each test case, output on a different line the smallest number of holders that will get corroded after rotating the existing containers and placing the newly arrived containers.

      Example

      Input:
      2
      4 6 4 4
      1 2 0
      2 4 0
      3 2 1
      3 5 1
      50 50 5 10
      1 35 1
      17 44 0
      17 46 1
      42 35 1
      42 46 0
      
      Output:
      12
      148
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8327. Progressive progressions

      Problem code: PROGPROG


      An arithmetic progression is a sequence of numbers a1, a2,... an such that ai+1-ai is equal for all 0≤i<n. This difference is called the common difference of the arithmetic progression.

      Now consider a sequence of arithmetic progressions A1 = (a1,1, a1,2,... a1,n1), A2 = (a2,1, a2,2,... a2,n2),... Ak = (ak,1, ak,2,... ak,nk)

      A progressive progression is such a sequence with the additional properties that:

      • ai,ni = ai+1,1 for 1 ≤ i < k
      • ci, the common difference of Ai, is a positive factor of ai,1 for 1 ≤ i ≤ k
      • ci<ci+1 for 1 ≤ i < k
      • ni >1 for 1 ≤ i ≤ k
      • k ≥ 1

       

      Find the number of progressive progressions such that a1,1=1 and ak,nk = N. As this number can be quite large, output it modulo 100000007.

      Input

      The first line of input contains T (≤ 100), the number of testcases. This is followed by the description of the testcases. The description of each testcase consists of a single integer N (1 < N ≤ 1000000).

      Output

      For each testcase, output modulo 100000007 the number of progressive progressions such that a1,1=1 and ak,nk = N

      Example

      Input:
      2
      5
      10
      
      Output:
      1
      6
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8328. Move the books

      Problem code: MOVEBOOK

      Sheldon and Lenard are a pair of nerds playing an unimaginatively named game, "Move the books". The game board is an infinitely long strip of cells numbered 1,2,3.... from left to right. On certain cells, their favourite physics books have been placed. A player's move consists of taking any one of the books and moving it to any cell which lies to its left. But there is a constraint that you are not allowed to make your book jump over a cell that contains a book already (ie, You cannot move a book from cell j to cell i < j if there is a cell k which contains one or more books such that i < k < j). However, you can place a book into a cell even if it contains one or more books already. But books that are placed in a cell are stacked in the order in which they arrive and hence only the topmost book (the last arrived one) can be moved from there. The players make moves alternately, and the person unable to move any book loses.

      They have been playing the game for a long time. Sheldon makes the first move in all the games and wins most of the time. Lenard is fed up and wants to make the first move. However, Sheldon doesn't yield and this leads to an argument. This is the final agreement they have come up with:

      • They start with N books placed in different cells. The arrangement is computer generated and hence there is no player role in this step
      • Lenard picks two natural numbers a & c while Sheldon picks a natural number b. Both are unaware of the number(s) the other person has chosen while choosing their own number(s). Three more books are now added to the set : a cells to the right of the rightmost current book, b cells to the right of this book and c cells to the right of the latter book.
      • They start the game with the same rules as earlier, with Sheldon making the first move.

       

      Now Lenard feels that there might be certain pairs (a,c) such that independent of which number Sheldon chooses, Lenard is assured to win the game. Given the initial configuration of the board find all such pairs, sort them lexicographically [(a1,c1) < (a2,c2) iff a1 < a2 or (a1=a2 and c1 < c2)] and output the Kth such pair. If there are less than K pairs with this property, output Impossible

      Input

      The first line of the Input contains T (≤50), the number of test cases. Following this are the descriptions of the T test cases

      The first line in the description of each test case contains two space separated integers N (≤1000) and K (≤108). Following these are N lines, each containing the location of a book. The book positions are given in increasing order and will each fit in a 32 bit signed integer.

      Output

      For each test case output the Kth lexicographically smallest pair of integers that will assure Lenard a win. The two integers should be separated by a space and pairs for each test case should be output on a new line. If for any test case there are less than K pairs of integers that assure Lenard a win, on the line for that test case output Impossible

      Example

      Input:
      1
      1 1
      1
      
      Output:
      1 1
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8329. Road trip

      Problem code: ROADTRIP

      Phileas Fogg and Passepartout are now going on a road trip in their brand new car. They start at location A0 and need to go to AN. Their car has a capacity to hold only C units of fuel and can travel unit distance on unit amount of fuel. They start by filling some amount of fuel from the filling station at A0. On the way, there are several filling stations A1, A2,... AN-1. The cost of fuel is not the same at all filling stations. Find the minimum amount that they have to spend on fuel to make the journey. Note that it is assured that the journey can be completed with the car of the given capacity.

      Input

      The first line of input contains T (≤10), the number of test cases. Following this are the descriptions of the testcases

      The first line in the description of each test case contains two space integers N (≤50000) and C (≤108). This is followed by N lines, each containing an integer. The integer on the ith line is the distance from A0 to Ai and is ≤ 108. The distances are in increasing order. This is followed by N more lines, each containing an integer. The integer on the ith line is the cost of one unit of fuel at the filling station Ai-1 and is ≤ 108.

      Output

      Output one integer per test case, the minimum total amount that needs to be spent on fuel to complete the journey

      Example

      Input:
      2
      5 10
      10
      20
      30
      40
      50
      1
      2
      1
      2
      1
      5 15
      10
      20
      30
      40
      50
      1
      2
      1
      2
      1
      
      Output:
      70
      60
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8330. Giant fountain

      Problem code: GNTFNTN

      The Dystopian government has installed a giant fountain in front of the parliament building. The fountain consists of N levels stacked one on top of the other and is situated on top of a large tank of infinite capacity. The levels of the fountain are numbered 1 to N from top to bottom. The top l1 levels are identical with capacity c1, the next l2 levels identical with capacity c2,... the final lK levels with capacity cK. Here l1 + l2 + ... lK = N.

      When water is added to level i beyond its capacity, the excess water overflows to level i+1. Water overflowing from level N is collected in the tank. Water is added to the levels in the following fashion. First, w1 amount of water is added to each level i such that s1 ≤ i ≤ e1. Then w2 amount of water is added to each s2 ≤ i ≤ e2... Finally wM amount is added to sM ≤ i ≤ eM. Note that water might be added to the same level multiple times in this fashion. You have to find out the amount of water that has overflowed to the tank at the bottom, and the total number of levels of the fountain that are completely filled

      Input

      The first line of the input contains T (≤10), the number of test cases. Following this are the descriptions of the test cases.

      The first line of the description of a test case contains space separated integers N (≤2x108), K (≤2000) and M (≤104). Following this are K lines, each containing a space separated pair of integers. These are the (li,ci) pair as explained in the problem statement. Here l1 + l2 + ... lK = N and ci ≤ 108. This is followed by M lines, each containing a space separated triplet of integers. These are (si,ei,wi) as explained in the problem statement. 1 ≤ si ≤ ei ≤ N and wi ≤ 106

      Output

      For each test case output a space separated pair of integers : The total amount of water that has overflowed to the tank and the number of levels of the fountain that are completely filled.

      Example

      Input:
      1
      10 2 1
      5 6
      5 3
      3 9 5
      
      Output:
      5 5
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8331. Sister cities

      Problem code: SSTRCITS


      Unlike Dystopia, the neighbouring nation of Utopia believes in economic development. To improve the economy of the nation, the Utopian government has decided to select some pairs of cities as sister cities and take steps to improve trade relations between each pair.

      There are N cities in Utopia, numbered 1 to N. There are two-way roads connecting some pairs of cities. The total number of roads in Utopia is R. Now the road network in Utopia has been created efficiently so that there is no road that is redundant. That is, there is exactly one way to travel between any pair of cities without using the same road twice. Now when a pair of cities is chosen as sister cities, the government wants to make sure that there is a direct road between them. Also, a given city cannot have more than one sister.

      Given the road network of Utopia, find the number of ways of selecting K pairs of sister cities under these constraints. As the answer can be quite large, output it modulo 100000007.

      For example, assume that there are 6 cities in Utopia. There are direct roads between the following pairs of cities : (1,2), (2,3), (2,4), (4,5), (4,6). Notice that there is exactly one way to travel between any pair of cities. If the government wants to select two pairs of sister cities, it can do it in four ways : {(1,2),(4,5)}, {(3,2),(4,5)}, {(1,2),(4,6)}, {(3,2),(4,6)}

      Input

      First line of the input contains T (≤10), the number of test cases. This is followed by the description of the test cases.

      The description of each test case begins with a line containing 3 space separated integers N (<400), R (<10000) and K (<400). Following these are R lines, each representing a road in Utopia. The line will contain two different space separated integers N1 and N2 implying that there is a two way road between N1 and N2. You are assured that the road network has the property as described in the problem statement.

      Output

      For each test case, output modulo 100000007 the number of ways of selecting K pairs of sister cities satisfying the conditions in the problem statement.

      Example

      Input:
      2
      3 2 1
      1 2
      2 3
      6 5 2
      1 2
      2 3
      2 4
      4 5
      4 6
      
      Output:
      2
      4
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8332. Ski slopes

      Problem code: SKISLOPE


      A skier wants to ski down from the top of a mountain to its base. There are several possible routes, using different slopes enroute, and passing through some flat areas. The effort expended in skiing down a slope depends upon the length of the slope and the speed of skiing. For each slope, there is a maximum advisable speed. The skier wants to use a toute that minimizrs the average effort spent per unit distance traveled (i.e. the total effort expended divided by the total distance traveled).

      The flat regions on the mountain are numbered 1 to N from top to bottom. The skier begins at level 1 and needs to reach level N. You are given the numbers of the flat regions each slope connects. Note that on a slope, one can only ski downwards. For each slope, you are also given the length of the slope and the maximum advisable speed for it. The effort expended in skiing down a particular slope is given by the following formula:

      e = d*(70-s) if s ≤ 60, and e = d*(s-50) if s > 60

      where e is the effort required, d is the distance traveled and s is the speed of travel.

      You have to determine the minimum average effort per unit distance that the skier has to expend in order to reach the mountain base, while staying within the maximum advisable speed at every slope.

      Input

      The first line of input gives the number of test cases T(≤20). This is followed by the descriptions of the test cases

      For each test case, the first line of input gives the number of flats, N (N ≤ 1000), and the number of slopes, R (R ≤ 20000), connecting them respectively. Each of the next R lines describes a slope by giving: the numbers of the flats at the top and the bottom of the slope, the maximum advisable speed for the slope (≤ 100), and the length of the slope (≤ 1000) respectively.

      Output

      For each test case, output a single number (with four places after the decimal point, rounded up) that gives the minimum average effort per unit distance that needs to be expended to ski down from the mountain top to the base. The output for each test case should be on a separate line.

      Example

      Input:
      2
      4 5
      1 4 30 60
      1 2 50 40
      1 3 60 20
      2 4 60 50
      3 4 50 50
      3 3
      1 2 50 40
      1 3 40 20
      2 3 20 30
      
      Output:
      14.4445
      30.0000
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8333. Place-name game

      Problem code: PLCNMGME


      Place-name game is a favourite pastime among the few children that go to school in Dystopia. The game is played as follows : One player says the name of a city and the next player has to say the name of a city that begins with the last letter of the said city. The game then goes on.

      Dystopian cities recently went through a massive renaming. Now each city has a name that begins with a consonant and ends with a consonant.

      Anaximander is a student with a very poor knowledge of geography. Hence he fares very poorly in the game. He has recently come up with a new idea. He would just remember the name of 21 Dystopian cities. He wants to choose the 21 cities such that there is exactly one city name starting with each consonant and exactly one city name ending with each. This would give him a good advantage in the game, whether he is playing first or second.

      Given the names of the N cities in Dystopia, find out the number of ways Anaximander can select 21 city names out of the lot satisfying the properties. As this number can be very large, output it modulo 100000007.

      Input

      The first line of the input contains N (≤1000), the number of cities. This is followed by N lines, each containing the name of a city in Dystopia. Each city name will begin and end with a consonant, and will contain at least 2 and at most 10 letters.

      Output

      Output modulo 100000007 the number of ways Anaximander can choose 21 city names out of the N with the intended properties.

      Example

      Input:
      23
      BBBB
      CCCC
      DDDD
      FFFF
      GGGG
      HHHH
      JJJJ
      KKKK
      LLLL
      MMMM
      NNNN
      PPPP
      QQQQ
      RRRR
      SSSS
      TTTT
      VVVV
      WWWW
      XXXX
      YYYY
      ZZZZ
      BAAC
      CAAB
      
      Output:
      2
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8334. Enumeration of rationals

      Problem code: ENUMRTNL

      It is well known that rational numbers form a countable set. Hence the set of rational numbers in the open interval (0,1) also form a countable set.

      Here we enumerate the rationals in (0,1) in the following fashion. First, every rational is expressed in the lowest terms : ie, as p/q where p and q are positive integers with no common factor other than one. Then we sort the fractions in the ascending order of p+q. In case of a tie, the smaller fraction comes first.

      The first few terms in this enumeration are 1/2, 1/3, 1/4, 2/3, 1/5, 1/6, 2/5...

      Given a natural number N, find the numerator and denominator of the Nth term in the enumeration.

      Input

      The first line of the input contains T (≤1000), the number of test cases. This is followed by T lines, each containing an integer N(≤1011).

      Output

      For each value of N, output separated by space the numerator and denominator (in lowest terms) of the Nth fraction in the enumeration

      Example

      Input:
      2
      3
      6

      Output:
      1 4
      1 6

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set (classical)

      8335. Counting the teams

      Problem code: CNTTEAMS


      The teacher in the Dystopian School for Politics and other Dirty Games (DSPDG) is training students in group activities. She feels that to really understand group behavior, students need to practice working in groups of different sizes. This is how she groups the students:

      There are N students in the class, with roll numbers from 1 to N(2≤N≤1012). The teacher generates using her laptop a random permutation of the roll numbers. The student with the roll number equal to the ith number in the permutation is assigned as a "target" to the student with roll number as i (Note that "targetship" is not mutual. If 1 is the target for 2, 2 need not be the target for 1). If any student is assigned himself as the target, the teacher generates another permutation till no student is assigned himself.

      The N students stand far from each other. Now student 1 goes and joins his target. After this, student 2 (and any student who is with him) joins 2's target. At the ith step, student i and anyone who is already with him joins i's target. In case i's target is already with him, nothing is done.

      By following this procedure, when all students have joined their targets, the class gets split into some groups. For example, assume that there are 6 students in the class and the permutation that has been generated is {2,4,5,6,3,1}. First, 1 goes and joins 2. Then 1 and 2 join 4. Then 3 joins 5. Then 1, 2 and 4 join 6. 5 is already with 3 and hence does not move. Similarly 6 is already with 1 and does not move. In the end, we have 2 teams : {1,2,4,6} and {3,5}

      Given N, find out the expectation value of the number of teams that will be formed when the teacher groups the class in this fashion.

      Input

      First line of the input contains T(≤100), the number of test cases. Following this are T lines, each containing an integer N(2≤N≤1012).

      Output

      For each N, output the expectation value of the number of groups formed. Output 6 digits after the decimal point while printing the expectation value

      Example

      Input:
      2
      3
      4
      
      Output:
      1.000000
      1.333333
      

      Added by:Raziman T V
      Date:2011-02-13
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOPC2011









      SPOJ Problem Set ()

      8349. BRODOVI

      Problem code: BRODOVI

      Mirko lives in a small town with a harbour: once in a blue moon a ship passes by. However, to this day
      Mirko remembers the day when all the ships who had ever visited the harbour showed up. He
      denoted this day by index 1.
      Many days have passed since, but Mirko noted each day when at least one ship visited the harbour,
      naming these days entertaining.
      Additionally, Mirko has noticed that each ship visits the harbour periodically, at regular intervals. For
      instance, an interval of length 3 implies that some ship visited the harbour on days 1, 4, 7, 10 etc.
      Given Mirko’s list of entertaining days (including today which is considered to be an entertaining day as
      well), compute the minimum possible number of ships visiting his harbour.
      Notes: All entertaining days appear on Mirko’s list. It is guaranteed that the given data is consistent - in
      other words, a solution will always exist.

      Input

      The first line of input contains an integer N (2 ≤ N ≤ 5000), the number of entertaining days.
      The following N lines contain indices of entertaining days, one per line, in ascending order. The first
      and the last indices, representing the day from which Mirko started monitoring harbour traffic and
      today, respectively, will always appear on the list. The first index will always be 1, and the last one
      (index of today) will be less than 109.

      Output

      The first and only line of output must contain the required minimum number of ships.

      Example

      Input:
      5
      1
      7
      10
      13
      19
      Output:
      2

      Added by:akaki
      Date:2011-02-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:coci









      SPOJ Problem Set (classical)

      8351. KOSARK

      Problem code: MIDO

       

      Slavko has started to follow the NBA league. The game duration is exactly 48 minutes. When a game 
      ends, the statistics are shown. Slavko has written down whenever a team scored. He is curious about 
      how long each team was in the lead.  
      INPUT 
      The first line of input contains one integer N (1 ≤ N ≤ 100). The following N lines describe events 
      when a team scored. 
      Each description consists of a team that scored, which is either  1 or  2, and a timestamp in format 
      MM:SS (minutes:seconds), the time when a team scored. Minutes and seconds are zero padded and 
      from ranges [00, 47] and [00, 59] (inclusive). The given timestamps are unique. 
      OUTPUT 
      The first line of output must contain the duration that the first team was in the lead. 
      The second line of output must contain the duration that the second team was in the lead. 
      All durations should be in MM:SS format, with leading zeros

       

      Slavko has started to follow the NBA league. The game duration is exactly 48 minutes. When a game 

      ends, the statistics are shown. Slavko has written down whenever a team scored. He is curious about 

      how long each team was in the lead.  

      INPUT 

      The first line of input contains one integer N (1 ≤ N ≤ 100). The following N lines describe events 

      when a team scored. 

      Each description consists of a team that scored, which is either  1 or  2, and a timestamp in format 

      MM:SS (minutes:seconds), the time when a team scored. Minutes and seconds are zero padded and 

      from ranges [00, 47] and [00, 59] (inclusive). The given timestamps are unique. 

      OUTPUT 

      The first line of output must contain the duration that the first team was in the lead. 

      The second line of output must contain the duration that the second team was in the lead. 

      All durations should be in MM:SS format, with leading zeros.

      SAMPLE TESTS

       

      input 

      1 01:10 

      2 21:10 

      2 31:30 

      output 

      20:00 

      16:30 

       

       

       


      Added by:Kawmia Institutes
      Date:2011-02-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI









      SPOJ Problem Set ()

      8363. COSTLY CHESS

      Problem code: CCHESS

      In the country of Rome, Chess is a royal game. For evey move the players had to give some bucks to the Emperor Jurg. The LGMs or Little Green Men, are very good player of chess. But as the chess is a expensive game, thats why it is royal, they asked you to help them find the minimum bucks which they had to pay for moving their Knight from one position to another. Any number of steps can be used to reach the destination.

      Constraints:

      The chess has a dimension of 8X8, and the index of left bottom cell (0, 0).

      Knight move only in a standard way, i.e. 2 row and 1 col or 1 row and 2 col.

      If in a step Knight move from (a, b) to (c, d), then LGM had to pay a*c + b*d bucks to Emperor Jurg.

      0 ≤ a, b, c, d ≤ 7

      Input

      There are 100-150 test cases. Each test case is composed of four space separeated integers.The first two numbers, a, b, are the starting position of the Knight and the next two, c, d, are the destination of the Knight. Read upto End Of File.

      Output

      For each test case, print the minimum amount of bucks they had to pay in separate line. If its impossible to reach the destination then print -1.

      Example

      Input:
      2 5 5 2
      4 7 3 2
      1 2 3 4

      Output:
      42
      78
      18


      Explanation for test case #1:
      2 5 5 2

      For moving Knight from (2, 5) to (5, 2) in minimum cost, one of the path is (2, 5) -> (3, 3) ->(5, 2)
      Bucks paid:
      (2, 5) = 0
      (2, 5) -> (3, 3) = 0 + (2*3 + 5*3) = 21
      (3, 3) -> (5, 2) = 21 + (3*5 + 3*2) = 42


      To infinity and beyond...

      Added by:`
      Date:2011-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IIITM Local Contest









      SPOJ Problem Set (classical)

      8371. TRIANGULAR PRISM

      Problem code: PRISMSA

      In a far away nation, all the liquid substance are stored in a can of shape of a triangular prism. According to belief, this will bring security to their children. As they are very resource conservative people, unlike the earth natives, they want to use as less as possible amount of the raw material to be used for producing the can, which directly depends on the surface area of the can. Mr. Buzz Light Year, of Star Command, is provided with the responsiblity to find the minimal suface area required to prodce a can of a given volume.

      Notes

      - Consider the material the can is made of to be infinitely thin.

      - The base of the prism is equilateral triangle.

      - Some formuls:

        a: triangle side's length.

        h: height of the prism.

        Volume, V =  (a2 * sin(60°) * h)/2

        Surface Area, S = a2*sin(60°) + 3*a*h

       - If not provided by a library, use the alue of 2*acos(0) for PI(π).

       - Reminder

          If your result is within 10-2 of the expected result, your solution will be evaluated as correct.

          If your result is between (1-10-2)*expected and (1+10-2)*expected, it will be evaluated as correct.

       

      Prism

       

      Constriants:

       - Volume will be between 1 and 100000, inclusive.

       - Volume will always be a integer.

      Input

      Input begins with a integer t, number of test cases. Then follows t lines, each one containing an integer, V, given volume.

      Output

      For each volume, print the minimum surface area required to produce the can in separate line.

      Example

      Input:
      5
      10
      5
      100
      245
      5421

      Output:
      30.3872837089
      19.1427891970
      141.0452767471
      256.3318686611
      2020.2796324002

      Explanation for test case 1: Volume = 10
      a = 3.41995
      h = 1.97451
      Minimum Surface Area = 30.3872837089

      Added by:`
      Date:2011-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IIITM Local Contest









      SPOJ Problem Set (classical)

      8372. Triple Sums

      Problem code: TSUM

      You're given a sequence s of N distinct integers.
      Consider all the possible sums of three integers from the sequence at three different indicies.
      For each obtainable sum output the number of different triples of indicies that generate it.

      Constraints:

      N <= 40000, |si| <= 20000

      Input

      The first line of input contains a single integer N.
      Each of the next N lines contain an element of s.

      Output

      Print the solution for each possible sum in the following format:
      sum_value : number_of_triples

      Smaller sum values should be printed first.

      Example

      Input:

      5
      -1
      2
      3
      0
      5
      Output:
      1 : 1
      2 : 1
      4 : 2
      5 : 1
      6 : 1
      7 : 2
      8 : 1
      10 : 1

      Explanation:
      4 can be obtained using triples ( 0, 1, 2 ) and ( 0, 3, 4 ).
      7 can be obtained using triples ( 0, 2, 4 ) and ( 1, 3, 4 ).

      Note: a triple is considered the same as any of its permutations.


      Added by:Gustav Matula
      Date:2011-02-18
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem, used for a contest on codechef









      SPOJ Problem Set (classical)

      8374. PARKET

      Problem code: PARKET1

       

      Ivica has set up a new parquet flooring in his room. The room is L decimeters long and W decimeters 
      wide. 
      The blocks are of quadratic shape and each has an area of one quadratic decimeter. Once Ivica had set 
      up the flooring, which consists of brown.colored blocks, he decided to paint the blocks on the edge
      of the room red. 
      The picture below illustrates the scenario from the test case #2 – outer blocks are red, while the 
      remaining two inner blocks are brown: 
      Marica has come to visit Ivica. While Ivica was serving her cookies, she counted the number of blocks 
      of each color. When she returned home, she recalled of the two numbers and wished to calculate the 
      dimensions of Ivica’s room. Help her! 
      INPUT 
      The first and only line of input contains two integers separated by a space,  R (the number of red 
      blocks) and B (the number of brown blocks). The following constraints will apply: 8 ≤ R ≤ 5000, 1 ≤ 
      B ≤ 2 000 000. 
      OUTPUT 
      The first and only line of output must contain the dimensions of the room, L and W, respectively. If 
      the numbers differ, output the greater one first. The test data will ensure that a unique solution always 
      exists

       

      Ivica has set up a new parquet flooring in his room. The room is L decimeters long and W decimeters wide. 

      The blocks are of quadratic shape and each has an area of one quadratic decimeter. Once Ivica had set up the flooring, which consists of brown.colored blocks, he decided to paint the blocks on the edge of the room red. 

      The picture below illustrates the scenario from the test case #2 – outer blocks are red, while the remaining two inner blocks are brown: 

      picture for problem

      Marica has come to visit Ivica. While Ivica was serving her cookies, she counted the number of blocks of each color. When she returned home, she recalled of the two numbers and wished to calculate the dimensions of Ivica’s room. Help her! 

      INPUT 

      The first and only line of input contains two integers separated by a space,  R (the number of red 

      blocks) and B (the number of brown blocks). The following constraints will apply: 8 ≤ R ≤ 5000, 1 ≤ B ≤ 2 000000. 

      OUTPUT 

      The first and only line of output must contain the dimensions of the room, L and W, respectively. If 

      the numbers differ, output the greater one first. The test data will ensure that a unique solution always 

      exists.

       

      input 

      8 1  

      output 

      3 3

       

       

      input 

      10 2 

      output 

      4  3

       

       

       

       


      Added by:Kawmia Institutes
      Date:2011-02-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI









      SPOJ Problem Set (classical)

      8391. The Ball

      Problem code: BALL

      In a coordinate plane, there are N horizontal conveyor belts, each moving either leftwards or rightwards. When the ball falls on a belt, the belt drags it in direction it's moving. When the ball reaches the end of the belt, it falls vertically downwards. For example, if the belt is moving rightwards and it ends in the unit square with x-coordinate 12, the ball will fall from the belt on the x-coordinate 13, and continue falling on the same x-coordinate until it falls on another belt or reaches the ground (the height of 0).

      Frane drops a ball many times (from the height that is greater than any of the belt heights), from various x-coordinates, and your task is: for each ball Frane drops, determine the direction of each belt such that this ball falls on as many belts as possible.

      This picture reprezents the first test example:  

      Input

      In the first line of input, there is an integer N (the number of conveyor belts, 1 ≤ N ≤ 100000).

      In each of the next N lines, there are integers X1, X2, Y (X1 ≤ X2, 0 < X1, X2, Y < 109) reprezenting the belt. Imagine the belt as a segment of which the bounding unit squares are (X1, Y) and (X2, Y). The belt's thickness is zero and it lies on the bottom of the given unit squares. The belts will not touch or overlap each other.

      In the next line, there is an integer Q (the number of falling balls, 1 ≤ Q ≤ 100000).

      In the next Q lines there is an integer less than 109, reprezenting the x-coordinate of the unit square Frane drops the ball from.

      Output

      For each of the Q queries, output the greatest possible number of the conveyor belts visited by the ball.

      Example

      Input:
      
      3
      1 4 3
      5 7 2
      2 4 1
      4
      1
      4
      5
      6
      Output:
      3
      3
      2
      2
      Input:
      3
      5 20 20
      15 30 15
      10 14 11
      3
      5
      30
      516546
      Output:
      3
      2
      0

      Added by:Adrian Satja Kurdija
      Date:2011-02-21
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Frane Kurtoviæ









      SPOJ Problem Set (classical)

      8392. Youtube

      Problem code: YOUTUBE


      N students are bored in computer class so they watch funny video clips on YouTube.

      The site contains K popular clips, numbered 1 through N. When a video clip is watched, a list of similar video clips is displayed on the side.

      Every student picks a video clip from the main page and starts watching it. After exactly one minute every student gets bored of his or her video clip, so he opens the first video clip from the list of similar clips on the side (even if he already watched that clip).

      Write a program that determines for each student which video clip he will be watching during the M-th minute of the class.

      Input

      The first line contains three integers N, K and M (1 ≤ N, K ≤ 100 000) (1 < M ≤ 1 000 000 000), the numbers of students, video clips and minutes.

      The second line contains N integers, each between 1 and K, the indices of video clips the students start watching.

      The third line contains K integers, each between 1 and K, the index of the first similar clip for each video clip.

      Output

      Output N integers, the indices of video clips that students will be watching during the M-th minute.

      Example

      Input:
      4 5 2
      1 2 4 3
      5 5 1 2 3
      Output:
      5 5 2 1


      Input:

      2 6 5
      1 6
      2 3 4 1 4 5

      Output:

      1 2

      Added by:Stjepan Glavina
      Date:2011-02-21
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Croatian Nationals 2009









      SPOJ Problem Set (classical)

      8406. Temple Queues

      Problem code: TEMPLEQ

      main-destinations-tirupati

      The Tirumala temple is the most visited place of worship in the world. As the number of pilgrims who visit the temple each day is very high, the head of the temple should keep monitoring the queue system. Today is another lovely day and he has started his work. There are N queues at the entrance of the temple and some of them are already filled with pilgrims. Each queue has a metal door at the beginning, which leads to the temple. When the door is opened, it allows only one pilgrim to get through it and it gets closed immediately after that.

      New pilgrims are rushing in to the queues and the head needs to monitor the current sizes of the queues and decide which doors to be opened. At any time, he wants to know how many queues currently have at least X pilgrims. He also decides an integer Y and wants to open the doors of all the queues having at least Y pilgrims at that time. You are the controller of the queue system and are following his instructions. Respond quickly and win yourself a big laddu (sweet) from him :) .


      Read the input section for rest of the details.

      Input

      The first line contains two integers N and Q. N - The number of queues [ 1 <= N <= 100,000 ], Q - The number of queries [ 0 <= Q <= 500,000 ] . The second line contains N integers, which are the initial sizes of the queues. ith integer ( 1-based ) is the initial size of queue i [ 0 <= initial size <= 100,000,000 ]

      Each of the next Q lines is one of the following

      1 A [ One pilgrim enters the queue# A ( 1 <= A <= N ) ]

      2 X [ Find the number of queues having atleast X pilgrims currently ( 0 <= X <= 1,000,000,000 ) ]

      3 Y [ Open the doors of all the queues having atleast Y pilgrims ( 1 <= Y <= 1,000,000,000 ), and thus allowing only one pilgrim to enter the temple from each of them ]

      Output

      For each query of type "2 X" , print the answer in a new line.

      Example

      Input:
      5 6
      20 30 10 50 40
      2 31
      1 2
      2 31
      3 11
      2 20
      2 50

      Output:
      2
      3
      3
      0

      Note : Ideal time limit should be 2s. It has been increased to 7s, to let Java solutions pass, as the i/o is huge.

      * There are multiple test sets, and the judge shows the sum of the time taken over all test sets of your submission, if Accepted.

      Added by:Anil Kishore
      Date:2011-02-25
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeMutants 2011 , DA-IICT, India









      SPOJ Problem Set (classical)

      8407. Candies and Milestones

      Problem code: CANDYSTN

      Little Pratya loves collecting candies and she also likes playing games :).

      Today Pratya is travelling in bus and she has a bag full of N candies. She looks outside the window and notices milestones with numbers written on them. She decides to play a game. She wants to select some initial non-zero number of candies from the bag and call it her collection of candies. When she sees a milestone on the way, she will add or remove some candies from her collection as following.

      Let the previous milestone number be a1 and the current milestone number be a2.

      pratya1

      a2 > a1 : Pratya adds ( a2 - a1 ) candies to her collection (thus, her bag of candies loses them). If the bag doesn't contain at least ( a2 - a1 ) candies, she starts crying.

      a2 < a1 : Pratya removes ( a1 - a2 ) candies from her collection (thus, her bag of candies gains them). If her collection doesn't contain more than ( a1 - a2 ) candies, she starts crying.

      a1 = a2 : Pratya is bored to see the same number again and so she eats one of the candies from her collection.

      Moreover, Pratya always wants her candy collection to have at least one candy, otherwise she starts crying. Given the numbers written on all the milestones in order, find the minimum number of candies Pratya should select in the beginning so that she doesn't have to cry at all. If it is not possible , print -1. Note that no change to the collection happens when she sees the first milestone.

       

      Input

      The first line contain the number of test cases T. Each test case has two lines. The first line specifies N and M. N is the number of candies in the bag and M is the total number of milestones. Second line contains M integers, the numbers written on the milestones, in the order Pratya sees them.

      ^ is used for power.

      T <= 150

      1 <= N <= 10^7

      2 <= M <= 10^4

      Each milestone number will be between [-10^6,10^6].

      Output

      For each test case output the minimum number of candies that should be selected from the bag or -1 if its not possible

      Example

      Input:
      3
      10 5
      1 5 1 -1 -2
      2 5
      1 5 1 -1 -2
      100 3
      1 2 3

      Output:
      4
      -1
      1

      Note : Large input, prefer using scanf / printf  to  cin / cout
      * There are multiple test sets, and the judge shows the sum of the time taken over all test sets of your submission, if Accepted.


      Added by:Anil Kishore
      Date:2011-02-25
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeMutants 2011 , DA-IICT, India









      SPOJ Problem Set (classical)

      8408. Min Max 01 Path

      Problem code: MNMXPATH

      I have been asked to set a problem by spoj, what do I do now ? Lets see the standard stuff in most of the programming contests and make one problem out of it. Hmm... many problems are having Binary digits, Grids, Paths, Coins, Maximize or Minimize something, so let me mix them all now in to one problem, the one problem to rule them all ;)

      Lets have a grid of size N x M having N rows and M columns, and put gold coins in it. How many in each cell ? , lets involve binary here. I'll give you two binary strings A[1...N] and B[1...M]. Cell (i,j) (1-based indexing) Row-i and Column-j in the grid contains A[i] * B[j] gold coins. From a cell (i,j), you can move to any of the 4 adjacent cells (i-1,j), (i+1,j), (i,j-1), (i,j+1) in one step. I want a path of minimum length from top-left cell (1,1) to bottom-right cell (N,M), and the value of this path = number of gold coins it covers. Find the maximum value of such a path. Not every one wants to become a Raja, also find the minimum value of such a path.

      Input

      First line contains T [ number of test cases, around 10 ]. T cases follow, each having 2 lines, "N A" and "M B" (quotes for clarity only). [ 1 <= N,M <= 100,000 and each character in A, B is either 0 or 1 ]

      Output

      For each test case, print the maximum value of a path followed by the minimum value of a path, in the same line, separated by a single space. Output of each case should be in a separate line.

      Example

      Input:
      2
      4 1001
      3 110
      5 01111
      3 110

      Output:
      3 1
      5 0

      Explanation:
      Case 1 : A Maximum path in bold
      110
      000
      000
      110

      Case 1 : A Minimum path in bold
      110
      000
      000
      110


      Added by:Anil Kishore
      Date:2011-02-25
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeMutants 2011 , DA-IICT, India









      SPOJ Problem Set (classical)

      8409. Favorite Sub Hair

      Problem code: FAVSUBS

      Little Princess Rapunzel is blessed with long (really looong!) hair, which is golden colored and has healing power. After the end of a long happy story, she marries her lover Flynn. They decide to lead a normal life by getting rid of the mysterious hair, which when cut loses its power and turns brown. There are many colorful beads on her hair in order. Rapunzel has some K favorite colors B[1...K]

      To remember good old stories, she wants to keep a part of her hair after its cut. A favorite sub hair is that continuous part of the hair, which has each of her favorite color beads at least once.

      For the purpose of this problem, we represent a color as an integer and Hair as an array A[1...N], which has exactly N colored beads in the given order. Could you please tell her the total number of ways she can cut her favorite sub hair (sub-array). Two sub-arrays are different, if their starting or ending index in A differ.

      Input

      First line contains T [ number of test cases, around 10 ]. Each test case is preceded by a blank line, including the 1st case. [ -2,000,000 <= A[i], B[j] ( colors ) <= 2,000,000 ]
      Each test case has 4 lines, as described below.
      N [ 1 <= N <= 100,000 ]
      < Array A : N integers, separated by spaces >
      K [ 1 <= K <= 1,000 ]
      < Array B : K integers, separated by spaces, her favorite colors, without repetition >

      Output

      For each test case, output the number of different sub-arrays, which has her favorite color appearing at least once, in a separate line.

      Example

      Input:
      3
      
      4
      1 2 3 1
      2
      1 2
      
      6
      10 20 30 40 50 60
      1
      20
      
      5
      1 2 3 4 5
      2
      2 6
      
      Output:
      4
      10
      0
      
      Explanation:
      Case 1 : Favorite sub-arrays in bold [ 1 2 3 1 ], [ 1 2 3 1 ] , [ 1 2 3 1 ], [ 1 2 3 1 ]
      


      Note: Large input, prefer using scanf / printf to cin / cout

      There are multiple test sets, and the judge shows the sum of the time taken over all test sets of your submission, if Accepted.


      Added by:Anil Kishore
      Date:2011-02-25
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeMutants 2011 , DA-IICT, India









      SPOJ Problem Set (classical)

      8410. Snaky Numbers

      Problem code: SNAKYNUM

      Sanky is a school kid and is very fond of numbers. His teacher gave his class a home work, asking each of them to invent a new series of numbers, with a large collection of numbers in them. His friend Evan has already invented one, which starts from 0 and picks every alternate number : {0, 2, 4 ,...} and he named them 'Evan' numbers :). Sanky is not happy because he couldn't invent that first and thinks picking every alternate number starting from 1 : {1, 3, 5, ... } would not be very odd ;).

      After refreshing at home, he comes up with a new series of numbers in which the digits alternate between increasing and decreasing when compared with the digit before it, in a zig-zag fashion. To make it clear, if the number is abcde, either a < b > c < d > e or a > b < c > d < e. He cleverly named them 'Snaky Numbers' :). Eg: 8, 90, 243516 and 31524 are Snaky while 44, 123 and 4235 are not. He is now wondering if his Snaky series is large enough. Particularly, he wants to know how many 'Snaky Numbers' are there of length at most N. Count only non-negative integers, without leading zeros.

      The answer may get very big and not fit in Sanky's book, so please just tell him the ( answer modulo M )

      Input

      First line contains T [ number of test cases, around 50 ]. Each of the next T lines contains two integers N M.

      1 <= N <= 1,000,000,000

      2 <= M <= 1,000,000,007

      Output

      For each test case, output ( Number of Snaky numbers of length at most N ) % M, in a separate line

      Example

      Input:
      3
      1 101
      2 107
      3 1001

      Output:
      10
      91
      616

       Hint: You may have to use the mod operator wisely !


      * There are multiple test sets, and the judge shows the sum of the time taken over all test sets of your submission, if Accepted.


      Added by:Anil Kishore
      Date:2011-02-25
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeMutants 2011 , DA-IICT, India









      SPOJ Problem Set (classical)

      8418. Revenge of the squares

      Problem code: SQUA_REV

      Given a number calculate the product N of their digits bigger than zero. The output is the number R of different (!) presentations of N in the form A*A+B*B with A and B being positive integers including zero.

      Input

      Twenty tests with one positive integer < 10^20.

      Output

      Print the illustrated above number R for each test.

      Example

      Input:
      5
      7
      78185824586267361855 Output: 1
      0
      3

      Added by:HWK
      Date:2011-02-25
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8419. Traversing Grid

      Problem code: BTCODE_A

      Given 2 points in 2 dimensional space (xs,ys) and (xd,yd), your task is to find whether (xd,yd) can be reached from (xs,ys) by making a sequence of zero or more operations.
      From a given point (x, y), the operations possible are:
      a) Move to point (y, x)
      b) Move to point (x, -y)
      c) Move to point (x+y, y)
      d) Move to point (2*x, y)

      Input

      The first line of input contains T, the number of test cases. T lines follow, one for each test case. For each test case, the input contains one line denoting the 4 integers xs, ys, xd, yd

      Output

      Output T lines, one for each test case. For each test case, output "YES" if (xd,yd) is reachable from (xs,ys) and "NO" otherwise. (quotes for clarity)

      Example

      Input:
      1
      1 1 2 2
      
      Output:
      YES
      
      Constraints:
      T <= 25
      -10^10 <= xs, ys, xd, yd <= 10^10
      Note that, although the input values are constrained by the above inequality, the coordinates of the points
      at the intermediate steps need not be.
      
      

      Explanation:

      Test case 1: We can move in the following manner: (1,1) -> (2,1), using the operation (x,y) -> (2*x,y). Then, move from (2,1) -> (1,2), using the operation (x,y) -> (y,x). Finally use the operation (x,y) -> (2*x,y) to move from (1,2) -> (2,2).


      Added by:suhash
      Date:2011-02-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8420. Finding Minimum

      Problem code: BTCODE_B


      You are given 'n' integers k1, k2, ...., kn and an integer 'x', which satisfy the equation x1k1 * x2k2 * ..... * xnkn = x. You are also given values a1, a2, ...., an and y1, y2, ...., yn. Your task is to find the least positive value 'v', that can be taken by the expression: a1*x1y1 + a2*x2y2 + ... + an*xnyn. Note that x1, x2, x3, ..... xn are some variables (not necessarily integers), which can only take positive values.

      Input

      The first line of input contains a single integer 't', denoting the number of test cases.
      The first line of each testcase contains two space separated integers 'n' and 'x'.
      Next line contains 'n' integers k1, k2, ..., kn.
      Next line contains 'n' integers a1, a2, ..., an.
      Next line contains 'n' integers y1, y2, ..., yn.

      Output

      For each testcase output the least positive value 'v' that can be taken by the expression. To avoid floating point errors, round it off to the nearest integer.

      For example, 12.6 is rounded off to 13, and 12.4 is rounded off to 12. To avoid ambiguity, there will be no test case for which the fractional part of the answer equals 0.5.

      Example

      Input:
      2
      1 4
      2
      3
      3
      2 6
      1 1
      1 1
      1 1
      
      Output:
      24
      5
      
      Constraints:
      t <= 25
      1 <= n <= 20
      1 <= x <= 1000000
      1 <= ki, ai, yi <=20
      xi > 0
      
      

      Explanation:

      Test case 1: x12 = 4. Therefore, x1 = 2 and 3*x13 = 24.
      Test case 2: x1*x2 = 6. Minimum value of x1 + x2 is 2*sqrt(6) = 4.89897. x1 = sqrt(6) and x2 = sqrt(6) gives this solution. Answer is 4.89897, which when rounded off to the nearest integer equals 5.


      Added by:suhash
      Date:2011-02-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8421. Fun With Inequalities

      Problem code: BTCODE_C


      You are given 'n' inequalities. Each inequality is of one of the following 4 types:
      Type 1: x > v
      Type 2: x < v
      Type 3: x = v
      Type 4: x != v

      where 'x' is a variable which can only take non-negative integral values.

      Your task is to find the maximum number of inequalities which are satisfied for some value of 'x'. You are also required to find the minimum value of 'x' for which the maximum number of inequalities are satisfied.

      Input

      The first line of input contains a single integer 'n', denoting the total number of inequalities.
      Each of the next 'n' lines contain 2 space separated integers ti and vi. ti denotes the type of inequality and vi denotes the value on the right hand side of the inequality.

      Output

      Output two space separated integers, the first integer denoting the maximum number of inequalities which are satisfied for some value of 'x', and the second integer denoting the minimum value of 'x' for which the maximum number of inequalities are satisfied.

      Example

      Input:
      4
      1 10
      2 9
      3 7
      4 4
      
      Output:
      3 7
      
      Constraints:
      1 <= n <= 100000
      1 <= ti <= 4
      1 <= vi <= 10^18
      
      

      Explanation:

      The given inequalities are: 1) x > 10, 2) x < 9, 3) x = 7, 4) x != 4. For x=7, the inequalities 2), 3) and 4) are satisfied.


      Added by:suhash
      Date:2011-02-26
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8422. Maximum Profit

      Problem code: BTCODE_D


      Chakra is a young and dynamic entrepreneur, who is developing rapidly as a successful hotelier. He owns the Quickbyte chain of restaurants, 'M' of which are fully functional now. He divides each day into 'N' time slots. For each time slot 'j', in every restaurant 'i', there are Aij waiters and Bij customers. Being a quality conscious person, he wants each waiter to handle atmost one customer in a given time slot. Since he is really busy, in a day each restaurant is open only during one of the time slots. Since the hunger and demand for food varies during the day, the price which the customer is willing to pay varies, and is given by Cij for a restaurant 'i' during a time slot 'j'.

      Given the values of Aij, Bij and Cij, find the maximum profit which Chakra can make in a day.

      Input

      The first line of input contains an integer 't', denoting the number of test cases.
      For each testcase, the first line contains 2 space separated integers 'M' and 'N'.
      Each of the next 'M' lines contains 'N' integers. The jth integer on the ith line denotes the value of Aij
      Each of the next 'M' lines contains 'N' integers. The jth integer on the ith line denotes the value of Bij
      Each of the next 'M' lines contains 'N' integers. The jth integer on the ith line denotes the value of Cij

      Output

      For each test case output one value, denoting the maximum profit which Chakra can make in a day.

      More than one restaurant can be open during a given time slot.

      Example

      Input:
      1
      2 3
      1 2 3
      3 2 1
      3 2 1
      1 2 3
      4 5 2
      3 1 6
      
      Output:
      16
      
      Constraints:
      t <= 50
      1 <= M,N <= 100
      1 <= Aij, Bij <= 5000
      0 <= Cij <= 10^9
      
      

      Explanation:

      Test case 1: By opening the first restaurant at time slot 2 and second restaurant at time slot 3, Chakra makes a profit = 2*5 + 1*6 = 16. Note that although there are 3 customers for the second restaurant at time slot 3, since there is only 1 waiter, only 1 customer can be served.


      Added by:suhash
      Date:2011-02-26
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8423. Recover Polynomials

      Problem code: BTCODE_E


      Venkatesh is an expert in mathematics, and loves playing around with polynomials during his free time. His favourite mathematical equation is pretty obviously: f(x) = an*xn + an-1*xn-1 + ..... + a1*x + a0. His friend Suhash loves posing challenges to Venkatesh. Once they were discussing a particular problem at Snacky, which goes as follows:

      Suhash would choose an integer 'n' as the degree of the polynomial and give Venkatesh the value of the polynomial at 'n+1' equally spaced points, i.e he gives Venkatesh integers 'n', 'x0', 'd' and g0, g1, g2, ..., gn such that: f(x0) = g0, f(x0+d) = g1, f(x0+2*d) = g2, ......f(x0+n*d) = gn. Now, Venkatesh is required to find the polynomial. Since he hates floating point values, he decides to find the polynomial in coefficient form, modulo a prime number. Can you help Venkatesh find the polynomial?

      Input

      The first line of input contains an integer 't', denoting the number of test cases.
      For each test case, the first line contains 3 space separated integers 'n', 'x0', 'd'. The next line contains 'n+1' space separated integers g0, g1, g2, .....gn.

      Output

      For each test case output 'n+1' integers, denoting the coefficients of the polynomial a0, a1, a2,...... an. All the coefficients that are printed should be non-negative and should be less than 1000000007.

      You are required to find coefficients of the polynomial a0, a1, a2,...... an, which satisfy the equations: f(x0)%1000000007 = g0, f(x0+d)%1000000007 = g1, ....... f(x0+n*d)%1000000007 = gn. It is guarenteed that there is a unique solution for every test case.

      Example

      Input:
      1
      3 1 1
      10 26 58 112
      
      Output:
      4 3 2 1
      
      Constraints:
      t <= 25
      1 <= n <= 1000
      0 <= x0 <= 100000
      0 < d  <= 10000
      0 <= gi <= 10^9
      
      

      Explanation:

      Test case 1: It can be seen that the polynomial f(x) = x3 + 2*x2 + 3*x + 4 satisfies the above input.


      Added by:suhash
      Date:2011-02-26
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8424. Life Game

      Problem code: BTCODE_F


      Gobo and Muku were really bored of working and decided to play a game on their respective laptops - the game of life. It is a one player game which consists of an M*N rectangular grid. Each cell of the grid contains exactly one magical potion. The potion at the jth column of the ith row of the grid increases the player's current health by Vij.(This value can be negative, in which case the player's health decreases). At any point of time, the health of a player can be negative too (i.e. He does not die). From a cell(i,j), the player can move to cells (i+1,j-1) or (i+1,j) or (i+1,j+1), as long as these cells exist in the grid. Initially, the player has a health of 0. He can start from any column on the first row (1,j). If he chooses to enter a cell, then he is forced to drink the potion in that cell. The game is completed when any column of the last row is reached. There are 2 modes in which the game can be played: the "min" mode and the "max" mode. In "max" mode, the aim is to finish the game with maximum health Hmax satisfying the condition A <= Hmax <= B. Similarly, in "min" mode the aim is finish the game with minimum health Hmin, satisfying the conditions A <= Hmin <= B. Now, Gobo decides to play the game in "max" mode on his laptop, and Muku decides to play the game in "min" mode on his laptop. Can you help Gobo and Muku finish with maximum and minimum health respectively, satisfying the above conditions?

      Input

      The first line of input contains an integer 't', denoting the number of test cases.
      For each test case, the first line contains 2 space separated integers 'M' and 'N'. The next line contains 2 space separated integers 'A' and 'B'. Each of the next 'M' lines contain 'N' integers. The jth integer on the ith line denotes the value Vij.

      Output

      Output 2 space separated integers Hmin and Hmax, the minimum and maximum health with which Gobo and Muku can finish the game. Hmax and Hmin should satisfy A <= Hmax, Hmin <= B. If it is not possible to achieve such a health, output "NO" (quotes for clarity).

      Gobo and Muku start playing on 2 different instances of the same game independently. i.e the values of A,B and initial values of Vij are same for both grids.

      Example

      Input:
      2
      3 3
      5 10
      2 5 10
      -1 -10 3
      -3  6 -2
      2 3
      8 11
      2 5 10
      -1 -10 2
      
      Output:
      6 10
      NO NO
      
      Constraints:
      t <= 10
      1 <= M,N <= 25
      -1000 <= A <= B < 1000
      -25 <= Vij <= 25
      
      

      Explanation:

      Test case 1: Take the path (1,2) -> (2,1) -> (3,2), to get a value 5-1+6=10. Take the path (1,2) -> (2,3) -> (3,3), to get a value 5+3-2=6.
      Test case 2: There is no valid path which satisfies the above conditions.


      Added by:suhash
      Date:2011-02-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8425. Coloring Trees

      Problem code: BTCODE_G


      Nivash and Bhoopathi play a game of memory, which goes as follows: There is a tree containing 'N' nodes, all of which are initially uncoloured. In the game, Nivash has 2 moves:

      1) Command: Color a particular node with a given color.
      2) Query: Ask Bhoopathi if the path from node 'a' to node 'b' (both inclusive), is monochromatic or not.(i.e Whether all nodes on the path have the same color).

      Nivash can do these steps in any order he wishes and he colors each node atmost once. Whenever Nivash puts forth a 'Query' at Bhoopathi, Bhoopathi has to recollect the colouring of the tree and reply either "YES" or "NO". Can your help Bhoopathi answer these queries?

      Input

      The first line of input contains an integer 'N', denoting the number of nodes in the tree. The next 'N-1' lines contain 2 space separated integers 'u' and 'v', denoting an edge between vertex 'u' and vertex 'v'.
      The next line contains an integer 'Q', denoting the number of inputs (commands and queries) which Nivash wants to give. The next 'Q' lines contain 3 space separated integers 'x', 'a', 'b'. If 'x' is 1, it denotes a command to color node 'a' with a color 'b'. If 'x' is 2, it denotes a query and Bhoopathi should answer if the path from node 'a' to node 'b' (both inclusive), is monochromatic or not.

      All vertices of the tree are 0 based.

      Output

      For each query, output "YES" or "NO" (quotes for clarity), denoting whether the path from node 'a' to node 'b' (both inclusive), is monochromatic or not.

      Output "NO", even if all nodes on the path from node 'a' to node 'b' (both inclusive) are uncolored.

      Example

      Input:
      3
      0 1
      1 2
      7
      1 0 11
      2 0 1
      2 0 2
      1 2 12
      1 1 11
      2 0 1
      2 0 2
      
      Output:
      NO
      NO
      YES
      NO
      
      Constraints:
      1 <= N <= 100000 
      1 <= Q <= 200000
      1 <= color value <= 30.
      
      

      Explanation:

      Initially node '0' is colored with color '11', so path between node '0' and node '1' is not monochromatic. Hence, the answer is "NO". The same explanation holds for the path between node '0' and node '2'. Then node '2' is colored with color '12' and node '1' with color '11'. Now, all nodes on the path between node '0' and node '1' are colored with only one color ('11'), so the answer is "YES". The path between node '0' and node '2' has 2 colors ('11' and '12'), hence the answer is "NO".


      Added by:suhash
      Date:2011-02-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8426. Trie Expectation

      Problem code: BTCODE_H

      What is the expected number of nodes in a trie when 'N' words, each of length 'L' are inserted into it. The words are made up only of 0's and 1's. The words may be repeated and all possible permutations of words are equally likely. Initially the trie consists of only one node (root node).

      Input

      The first line of input contains an integer 't', denoting the number of test cases. Each of the next 't' lines contain 2 space separated integers 'N' and 'L'.

      Output

      For each test case, output one floating point value denoting the expected number of nodes in the trie. Output the values rounded off to 2 decimal places. Always print 2 digits after the decimal point.

      To know more about tries visit here.

      Example

      Input:
      2
      1 3
      2 2
      
      Output:
      4.00
      4.25
      
      Constraints:
      t <= 25
      1 <= N <= 300
      1 <= L <= 300
      
      

      Explanation:

      Test case 1: There are 8 possible words of length 3. Which ever word is inserted into the trie, we get only 4 nodes.


      Added by:suhash
      Date:2011-02-26
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8427. Permutation Game

      Problem code: BTCODE_I


      Harsha is given 9 integers a1, a2, a3, .... a9. This denotes that he is given a1 1's, a2 2's,......a9 9's. Let 'x' = (a1 + a2 + ...a9). Now, Harsha makes all possible 'x' digit numbers by using these given digits. Let S be the set of all such numbers which he makes. Now he constructs a directed graph containing |S| nodes, in which each node denotes a unique number from the set. For all numbers u,v belonging to S, there is a directed edge from node 'u' to node 'v in the graph iff u>v. It is easy to note that we obtain a directed acyclic graph. Whats more, the edges of the graph are weighted. The weight of an edge joining node 'u' and node 'v' is equal to u+v. Now, Deepak decides to test Harsha's memory and gives him 'Q' queries. Each query consists of two numbers 'u', 'v' (u>v, both belonging to the set S). For each query Harsha must provide the following answers:

      1) How many distinct paths are there from node 'u' to node 'v' in the graph.
      2) For each distinct path 'i' from node 'u' to node 'v', let Si denote the sum of weights of all edges on this path. Calculate the value of sum(Si), for every distinct path 'i' from node 'u' to node 'v'.

      Input

      The first line of input contains 9 integers a1, a2, ....a9. The second line contains a single integer 'Q', denoting the number of queries. Each of the next 'Q' lines contain 2 numbers 'u' and 'v'.

      Output

      For each query, output 2 space separted integers denoting the number of distinct paths and sum of weights of all paths respectively. Since the output can be large, output these quantities modulo 1000000007.

      Two paths (v1, v2, .... vm) and (u1, u2, .... un) are distinct if:
      1) m != n
      2) m = n, there exists some index 'k' (1 <= k <= m) such that vk != uk

      Example

      Input:
      2 0 1 0 0 0 0 0 0
      1
      311 113
      
      Output:
      2 1110
      
      Constraints:
      1 <= (a1  + a2 + .... a9) <= 500
      1 <= Q <= 20
      ai >= 0
      
      

      Explanation:

      Test case 1: The set S for the above problem is {311, 113, 131}. The edges of the graph are 311->131, 311->113, 131->113. There are 2 distinct paths from 311 to 113, namely (311->131->113) and (311->113). The sum of weights of edges on path-1 = (311+131)+(131+113) = 686. For path-2, the sum of weights of edges = (311+113) = 424. Therefore, answer = 686 + 424 = 1110.


      Added by:suhash
      Date:2011-02-26
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8428. Grid Tiling

      Problem code: BTCODE_J


      Vikas is the chief interior designer incharge of the Taj Palace, Mumbai. He wants to make an impressive and colourful pattern in the courtyard. Importing exotic tiles has become very difficult after the Mumbai terror attacks, and therefore Vikas has only 4 kinds of tiles to choose from:

      A     B     C    D
      ==    ==    ==   ==
      XX    X     X    X
      XX    X     XX
      
      

      Any rotation of above tiles is also permitted.

      Each tile is available in 'k' different colors, and there's an infinite supply of all tiles. The courtyard has dimensions 2 * 'n'. Vikas wants to tile the courtyard in such a way that no two adjacent tiles have the same color. Two tiles are considered adjacent if they share a common side. Two tilings are considered different if:

      1) The arrangement of tiles is different.
      2) There is atleast 1 position (1*1 square) which has different colors in the two arrangements.

      Can you help Vikas find the number of different ways in which he can tile the courtyard, subject to the above conditions?

      Input

      The first line of input contains a single integer 't', denoting the number of test cases.
      Each of the next 't' lines contains 2 space separated integers 'n' and 'k'.

      Output

      For each test case output one integer, denoting the number of different ways in which the courtyard can be tiled.

      Two tiles are considered adjacent if they share an edge. Two tiles which just share a common point are not considered adjacent.

      Since the answers can be large, print all the quantities modulo 1000000007.

      Example

      Input:
      2
      1 1
      1 2
      
      Output:
      1
      4
      
      Constraints:
      t <= 1000
      1 <= n <= 10^9
      1 <= k <= 1000
      
      

      Explanation:

      Test case 1: There is only 1 way to tile the courtyard, by using a 2*1 tile.
      Test case 2: Let '1' and '2' be the available colors. The grid can be tiled in 4 ways - 1) place one 2*1 tile of color '1', 2) place one 2*1 tile of color '2', 3) Place two 1*1 tiles (color '1' above and color '2' below), 4) Place two 1*1 tiles (color '2' above and color '1' below)


      Added by:suhash
      Date:2011-02-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8429. Array Sorting

      Problem code: BTCODE_K

      Sumit specialises in sorting algorithms, and Abhishek decides to test Sumit's coding skills. An array of 'n' numbers a[0], a[1], a[2], ..., a[n-1] is given. Abhishek gives a sequence of inputs of the form "v i j". Each input is either a query or an update (query if 'v' is 0, update otherwise).

      For any input of the form "0 i j" ,Sumit's output should be as follows:
      If the subarray a[i], a[i+1], ... a[j] is unsorted, output 0.
      If the subarray a[i], a[i+1], ... a[j] is sorted in non-descending order, output 1.
      If the subarray a[i], a[i+1], ... a[j] is sorted in non-ascending order, output 2.
      If the subarray a[i], a[i+1], ... a[j] is sorted in both non-ascending and non-descending order (i.e, if all the elements in the range are equal), output 3.

      Any other input "v i j" (v!=0) should be treated as an update, as follows:
      For each element in the subarray a[i], a[i+1], ... a[j], Sumit has to replace the element a[k] with v-a[k].

      Sumit is really tired and does not want to write a program. Can you write a program for Sumit, which responds to Abhishek's instructions?

      Input

      The first line of input contains 2 space separated integers 'n' and 'q'. The second line contains 'n' integers a[0], a[1], ....., a[n-1]. Each of the next 'q' lines contain 3 integers 'v', 'i', 'j'.

      Output

      For each query, output a single integer 0, 1, 2 or 3, denoting the answer.

      Example

      Input:
      4 5
      3 -2 -5 1
      1 1 3
      0 0 3
      0 0 2
      0 2 3
      0 0 1
      
      Output:
      0
      1
      2
      3
      
      Constraints:
      1 <= n <= 100000
      1 <= q <= 100000
      -5000 <= a[i] <= 5000
      -5000 <= v <= 5000
      
      

      Explanation
      Initial array is {3, -2, -5, 1}. After first update, the array will be {3, 3, 6, 0}. Now, from indices '0' to '3', it is unsorted. From indices '0' to '2', it is sorted in non-descending order. From indices '2' to '3', it is sorted in non-ascending order. Between indices '0' and '1', the values are equal.


      Added by:suhash
      Date:2011-02-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2011, NIT Trichy, India









      SPOJ Problem Set (classical)

      8433. Revenge of the squares (variation)

      Problem code: SQUAREV1

      Given a number N calculate the number R of different presentations of N in the form A*A+B*B with A and B being positive integers including zero. 1*1+2*2 and 2*2+1*1 are not different presentations. So for input 5 the output is 1.

      Input

      Fifty tests with one positive integer < 10^9.

      Output

      Print the illustrated above number R for each test.

      Example

      Input:
      5
      7
      986244509 Output: 1
      0
      2

      Added by:HWK
      Date:2011-02-28
      Time limit:6s
      Source limit:300B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8434. Kolica

      Problem code: KOLICA

      A number of shopping carts filled with explosives are floating in a coordinate system, in one of the four main directions (up, down, left or right). All carts are moving at a speed of one unit per second.

      Movement is continuous; for example, in one third of a second, a cart travels one third of a unit.

      When two or more carts collide (are at the same place at the same time), there is an explosion and all carts taking part in the collision explode and cease to exist.

      Write a program that, given the starting points and directions of all carts, determines which carts never explode.

      Input

      The first line of input contains an integer N (2 ≤ N ≤ 500), the number of carts.

      Each of the following N lines contains two integers and a string. Each pair of integers describes the starting coordinates of one cart (between 0 and 100 000 000, inclusive), and the string describes the direcction in which the cart is moving ("gore" for up, "dolje" for down, "lijevo" for left, or "desno" for right).

      No two carts will start at the same coordinates.

      Output

      Output the indices of all carts which never explode, sorted in ascending order, one index per line. The first cart in the input is labeled 1, the second is labeled 2 etc. If no carts survive, output "nema".

      Example

      Input:
      4
      5 5 dolje
      5 6 lijevo
      5 7 desno
      5 8 gore Output: 1
      2
      3
      4


      Input:

      5
      3 3 dolje
      1 1 desno
      5 1 lijevo
      100000 500000 desno
      900000 500000 lijevo

      Output:
      nema


      Input:
      3
      10 0 gore
      0 10 desno
      15 5 lijevo
      Output:
      2

      Added by:Stjepan Glavina
      Date:2011-02-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Croatian Nationals 2007









      SPOJ Problem Set (classical)

      8442. Problem 3

      Problem code: NOVICE43

       

      When I first learned backtracking I made a program to find all the permutations of the English alphabets in lexicographically increasing. Filled with elation I showed the program to Rohil. Rohil being someone who likes to do stuff off the league was not impressed and gave me the following variation of the problem help me to solve the problem:
      You have to find the number of permutations of length N(1<=N<=12) such that at whenever an alphabet say($) appears in the permutation all the alphabets smaller than $ should have appeared before it at least once. An alphabet is smaller than another if it appears before the other in the English alphabet. ‘a’ being the smallest and ‘z’ being the largest. For example when N=2 then aa,ab are the only valid permutations and ba,bb is invalid since in ba all the alphabets smaller than b have not appeared at least once before it. See example for further clarification.

      When I first learned backtracking I made a program to find all the permutations of the English alphabets in lexicographically increasing. Filled with elation I showed the program to Rohil. Rohil being someone who likes to do stuff off the league was not impressed and gave me the following variation of the problem help me to solve the problem: 

      You have to find the number of permutations of length N(1<=N<=11) such that at whenever an alphabet (say 'c' ) appears in the permutation all the alphabets smaller than 'c' should have appeared before it at least once. An alphabet is smaller than another if it appears before the other in the English alphabet. ‘a’ being the smallest and ‘z’ being the largest. For example when N=2 then aa,ab are the only valid permutations and ba,bb is invalid since in ba all the alphabets smaller than b have not appeared at least once before it. See example for further clarification.

      Input

      Line 1: T(no. of test cases)

      Line 2: n1

      Line 3: n2

      Output

      Line 1: no. of such permutations of length n1

      ……

      …..

      Example

      Input:
      2
      2
      3
      
      Output:
      2
      5
      Explanation for N=3, the possible permutations are:
      abc
      aba
      abb
      aab
      aaa

      Added by:Mahesh Chandra Sharma
      Date:2011-03-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NSIT Noivce contest #4









      SPOJ Problem Set (classical)

      8449. Plotting functions (variation)

      Problem code: PLOT1

      Given a function y=f(x) in RPN-notation plot it with stars (*) and then (!) its derivation with crosses (+) for 0<=x<=20 with Δx=1 in a diagram with 21*21 points (0<=x,y<=20). Empty fields are marked with dots (.). For plotting the real number y should be rounded to integer (-0.5 -> -1, -0.4 -> 0, 0.4 -> 0, 0.5 -> 1). The function and its derivation are continuous between 0 and 20.
      The function definition uses only the following characters: 0123456789x.+-*/^
      '^' means 'power of'. Items are separated by space.

      Input

      In the first line the number N of functions, then N lines with one function.

      Output

      The plot of each function and its derivation in 21 lines.

      Example

      Input:
      1
      x 1 - Output: .....................
      ....................*
      ...................*.
      ..................*..
      .................*...
      ................*....
      ...............*.....
      ..............*......
      .............*.......
      ............*........
      ...........*.........
      ..........*..........
      .........*...........
      ........*............
      .......*.............
      ......*..............
      .....*...............
      ....*................
      ...*.................
      +++++++++++++++++++++
      .*...................

      Added by:HWK
      Date:2011-03-02
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8456. PRIMITIVEROOTS

      Problem code: PROBLEM4


      Problem 4:   PRIMITIVEROOTS

       

      Introduction to Primitive Roots:

      a primitive root modulo n is any number g with the property that any number coprime to n is congruent to a power of g modulo n.

       

      The number 3 is a primitive root modulo 7. because

       

       

       

      Problem Statement:

      Given a number n as input you’ve to find the (product all the primitive roots of n) % n if n is prime.

       

      Input:

      The first line consists of t the number of test cases followed by t lines. Each line consists of a prime number n.

       

      Output:

      For each test case print  the test case number followed by ‘:’ followed by (product of all primitive roots of n) % n. If it is not a prime then print “NOTPRIME”

       

      Input Specifications

      1<=t<=100

      10000>=n>=3

      Example

      Sample Input

      3

      6

      7

      9

      Sample Output

      1:NOTPRIME

      2:1

      3:NOTPRIME

       

      Description for test case #2:

      The primitive roots of 7 are 3 and 5. The product % 7 = 15%7  =1


      Added by:cegprakash
      Date:2011-03-04
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Edited question from Kurukshetra 2011









      SPOJ Problem Set (classical)

      8461. Adventure in Moving

      Problem code: AVDM

      To help you move from Waterloo to the big city, you are considering renting a moving truck. Gas prices being so high these days, you want to know how much the gas for such a beast will set you back.

      The truck consumes a full litre of gas for each kilometre it travels. It has a 200 litre gas tank. When you rent the truck in Waterloo, the tank is half full. When you return it in the big city, the tank must be at least half full, or you'll get gouged even more for gas by the rental company. You would like to spend as little as possible on gas, but you don't want to run out along the way.

      Input

      Input is all integers. The first integer is the distance in kilometres from Waterloo to the big city, at most 10000. Next comes a set of up to 100 gas station specifications, describing all the gas stations along your route, in non-decreasing order by distance. Each specification consists of the distance in kilometres of the gas station from Waterloo, and the price of a litre of gas at the gas station, in tenths of a cent, at most 2000.

      Output

      Output is the minimum amount of money that you can spend on gas to get you from Waterloo to the big city. If it is not possible to get from Waterloo to the big city subject to the constraints above, print "Impossible".

      Example

      Input:
      500
      100 999
      150 888
      200 777
      300 999
      400 1009
      450 1019
      500 1399
      Output:
      450550

      Added by:[Retired] Fendy Kosnatha
      Date:2011-03-05
      Time limit:0.125s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UVa









      SPOJ Problem Set (classical)

      8462. Barn Allocation

      Problem code: BARN

      Farmer John recently opened up a new barn and is now accepting stall
      allocation requests from the cows since some of the stalls have a
      better view of the pastures.
      
      The barn comprises N (1 <= N <= 100,000) stalls conveniently numbered
      1..N; stall i has capacity C_i cows (1 <= C_i <= 100,000). Cow i
      may request a contiguous interval of stalls (A_i, B_i) in which to
      roam (1 <= A_i <= N; A_i <= B_i <= N), i.e., the cow would like to
      wander among all the stalls in the range A_i..B_i (and the stalls
      must always have the capacity for her to wander).
      
      Given M (1 <= M <= 100,000) stall requests, determine the maximum
      number of them that can be satisfied without exceeding stall
      capacities.
      
      Consider both a barn with 5 stalls that have the capacities shown
      and a set cow requests:
      
      Stall id:    1   2   3   4   5
                 +---+---+---+---+---+
      Capacity:  | 1 | 3 | 2 | 1 | 3 |  
                 +---+---+---+---+---+
      Cow 1       XXXXXXXXXXX             (1, 3)
      Cow 2           XXXXXXXXXXXXXXX     (2, 5)
      Cow 3           XXXXXXX             (2, 3)
      Cow 4                   XXXXXXX     (4, 5)
      
      FJ can't satisfy all four cows, since there are too many requests
      for stalls 3 and 4.
      
      Noting that Cow 2 requests an interval that includes stalls 3 and
      4, we test the hypothesis that cows 1, 3, and 4 can have their
      requested stalls. No capacity is exceeded, so the answer for this
      set of data is 3 -- three cows (1, 3, and 4) can have their requests
      satisfied.

      Input

      * Line 1: Two space-separated integers: N and M
      
      * Lines 2..N+1: Line i+1 contains a single integer: C_i
      
      * Lines N+2..N+M+1: Line i+N+1 contains two integers: A_i and B_i

      Output

      * Line 1: The maximum number of requests that can be satisfied

      Example

      Input:
      
      5 4
      1
      3
      2
      1
      3
      1 3
      2 5
      2 3
      4 5
      Output:
      3

      Added by:[Retired] Fendy Kosnatha
      Date:2011-03-05
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:USACO Gold Division









      SPOJ Problem Set (classical)

      8467. GRADE POINT AVERAGE

      Problem code: GPA1

      Problem 1: GRADEPOINTAVERAGE

      Problem Statement:

      Every student of a college has to write 3 internal assessments and 1 final exam on each semester for all the 6 subjects.  Each internal assessment mark is out of 20 and the final exam mark is out of 100. The best two of three assessment marks is chosen and those marks are considered to be out off 45. The final exam mark is considered to be out off 50. The rest 5 marks is allotted based on the percentage of attendance of the student.

      Attendance mark allotment

      Below 51% attendance – 5 marks

      Below 61% attendance – 4 marks

      Below 71% attendance – 3 marks

      Below 81% attendance – 2 marks

      Below 91% attendance – 1 mark

      else –No mark for those sincere students

      Some students even bunk the assessments. If he bunks then instead of the mark ‘ab’ symbol is used which denotes “absent”. But no one bunks the final exam.

      No attendance is taken during exam days

      For each subject there’ll be some credit allotted by the department based on the importance of the subject.

       

      Total marks in a particular subject = best two out of three assessments(45%)

                                                          + attendance mark(5%) +Final exam mark(50%)

       

      Points out off 10:

      %Total mark in a subject                                                       Points

      >=91                                                                                      10

      >=81                                                                                      9

      >=71                                                                                      8

      >=61                                                                                      7

      >50                                                                                        6

      ==50                                                                                      5

      <50                                                                                        0   

      If the student scores 0 point in any of the subjects then he’s declared as FAILED else he’s declared as PASSED

      Mr.Chintumani, a professor of Computer Science department of the college designed a software program to calculate the GRADEPOINTAVERAGE(GPA) of the student and to determine whether the student is “PASSED” or “FAILED"

      GPA=  sum of (credit*points) for all the subjects / total number of credits of all the subjects

       

      Input:

      The first line consists of an integer n, the number of students in the class. Then n test cases follows, in each test case the first line consists of 6 integers a,b,c,d,e and f, the credits of the 6 subjects. Then for the next 6 lines, each line(each subject) consists of 5 numbers(the first three numbers are the assessment marks out off 20, the fourth is the final exam mark and the fifth is the percentage of attendance).

       

      Output:

      Assume you are Prof. Chintumani and print the result and GPA(rounded to two decimal places) per line for each student in the format as given in the example output.

       

      Example:

      Sample Input:

      1

      1 1 1 2 2 3

      19 18 20 70 70

      17.33 15 16.66 66 70.66

      ab ab ab 0 100

      ab ab 10 78 78

      17 18.33 19.5 64 87

      14 8 ab 60 45

      Sample Output:

      FAILED, 6.30

       

      Explanation of  the testcase:

      There is only 1 student

      In the Subject 0, he got 19,18 and 20 as internal marks, considering best two of three his internals score is 43.875/45.

      His final exam score is 35/50

      His attendance mark is 3

      So the total marks he got in that subject is 81.875 which leads to 9 points.

      Similarly he gets

      Subject 1:  74.2387 --> 8 points

      Subject 2:  0 --> 0 points

      Subject 3:  52.25 --> 6 points

      Subject 4:  75.5588 --> 8 points

      Subject 5: 59.75 --> 6 points

       

      Gpa= (9*1 + 8*1 + 0*1 + 6*2 + 8*2 + 6*3 ) / (1+1+1+2+2+3) = 6.30

      Since he got 0 points in atleast one of the subjects he is FAILED

      The output format is “RESULT,<space>gpa” without double quotes.


      Added by:cegprakash
      Date:2011-03-06
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8478. Ancient Pocket Calculator

      Problem code: POCALC1

      Adam likes pocket calculators, especially the early ones. As one of his favorite calculators is about 40 years old, he is not sure how long he will be able to use it. So he had the ingenious idea to develop a simulator that behaves exactly like his calculator. This simulator must be able to read a sequence of keystrokes from the calculator's keypad, process the appropriate calculations and print the calculator's output. As Adam needs only basic arithmetic, the following keys will be sufficient: digits 0 to 9, decimal point, operators +, -, x and : (for division), the equal sign for calculating and displaying a result and the [C] key for reseting the calculator and clearing the display, i.e. the display is set to "0.". Calculations are done from left to right without any operator precedence.

      Calculator Display

      You may call Adam's calculator a headstrong comtemporary, because of its special behaviour:
      There is no invalid sequence of keystrokes. You can press arbitrary keys one after another, the calculator always knows how to handle it. If more than one operator key (including [=]) is pressed directly after another, only the last of these operators will be processed - all previous ones (in that continuous sequence) are ignored.
      If more than 8 digit keys are pressed for the input of a single number, only the first 8 digits will be processed - all following digits are ignored. If the actual display value is zero, the typing of the zero key will have no effect, it's just ignored like successive keystrokes of the same operator. If a floating point value is typed in, a leading zero directly before the decimal point may be left out, but will be displayed just the same. If the decimal point key is pressed within a number that already has a decimal point typed in or if the input of a number (as a sequence of digit keys) is terminated by a decimal point, that has no effect.

      Input

      Input starts with a positive integer t (t<1000) in a single line, the number of testcases. Then t lines follow, each line giving the description of an arbitrary sequence of keystrokes on the calculator's keypad. Every key is enclosed by square brackets, all keystrokes are separated by a single space. The number of keystrokes per sequence is less than 500 and every sequence will be terminated by [=].

      Output

      For each sequence of keystrokes print the result the calculator will show on the display after the complete sequence of keystrokes has been processed. The size of the display is 8 digits plus an optional "-"-sign in front of the leftmost digit and a decimal point that will always appear, even if the result is an integer value. If a value has more than 8 decimal digits, it has to be rounded to fit into 8 digits. As the calculator's display is filled from right to left, the output has to be adjusted to the right.
      If the absolute value of a number rounded to an integer needs more than 8 digits, scientific notation is used. Same case, if the absolute value of a number is larger than 10-100, but rounding to 8 digits would result in displaying zeros only. If the absolute value is not larger than 10-100, it results to zero.
      In scientific notation a number is expressed as a product of a decimal part and a power of 10. The decimal part has always exactly one non-zero digit before the decimal point, an optional "-" sign in front of the leftmost digit and upto 4 digits after the decimal point, rounded if necessary. If the exponent is negative, a "-" follows, otherwise a space. Then follow two digits representing the exponent; a leading zero is shown in the exponent, if necessary.

      Notice that there are two cases, where the calculator will display "Error." instead of showing a result. If a (final or interim) result has a rounded absolute value of at least 10100 or if you divide by zero. After an error has occured, all following keystrokes are ignored unless [C] is pressed.

      For more clarity of the calculator's behaviour and the required input and output format please look at the examples below.

      Example

      Input:
      12
      [3] [+] [4] [x] [5] [=]
      [1] [:] [6] [=]
      [4] [.] [8] [-] [x] [+] [-] [+] [x] [-] [.] [=]
      [4] [.] [8] [-] [x] [+] [-] [+] [x] [.] [=]
      [+] [+] [+] [+] [+] [+] [1] [=] [=] [=]
      [9] [8] [C] [-] [7] [6] [5] [4] [3] [2] [1] [0] [1] [2] [3] [4] [=]
      [1] [=] [2] [=] [3] [=]
      [5] [:] [9] [8] [7] [8] [9] [8] [9] [8] [7] [8] [8] [:] [4] [5] [6] [7] [8] [9] [=]
      [-] [9] [9] [9] [9] [9] [9] [9] [9] [-] [-] [-] [-] [8] [8] [8] [8] [8] [8] [=]
      [2] [.] [3] [.] [4] [.] [5] [=]
      [0] [0] [0] [0] [0] [=]
      [.] [:] [.] [=]
       
      Output:
             35.
       0.1666667
             4.8
              0.
              1.
      -76543210.
              3.
        1.108-13
      -1.0089 08
           2.345
              0.
          Error.
      

      Added by:numerix
      Date:2011-03-06
      Time limit:2s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8491. Messy Phone List

      Problem code: PHONMESS

      Adam has a lot of friends and therefore he stored a lot of phone numbers in his phone database. As his telephone doesn't belong to the latest generation, its database is somewhat simple. In fact, all entries are stored line by line, exactly in the way Adam once typed them in, no matter what format he used. Unfortunately he changed the format from time to time, unable or too lazy to remember how he did it the last time. So, after years have passed (Adam likes his phone and doesn't want to replace it by a modern one), his phone number list has become really messed up and he wants to do some clean up. Your task is to write a program that will do that clean up for him.

      Every entry consists of three parts: telefon number, first name and last name of one of Adam's friends. The order of these parts may vary. An entry may start with the phone number, following the name or vice versa, phone number and name always separated by exactly one space. The order of the two parts of the name may also vary. Either it is first name before last name, separated by a space, or it is last name before first name, separated by a comma.
      A phone number may contain an optional leading area code, separated by a "-" or a "/" from the local code. If an area code is missing, the area code of Adam's hometown is assumed. Area code and local code both consist of at least three and at most ten digits. There may be additional optional spaces in between for better readability. For the final list the phone numbers have to be normalized. A normalized phone number consists of the area code and the local code, separated by "-" without any spaces.
      A name consists of any letters of the English alphabet. Capital letters and small letters may be mixed, as Adam didn't pay attention to that when he typed in the entries. First name and last name each are at least one and at most 20 characters long. For the final list all names have to be normalized. A normalized name consists of only small letters, except the first one being a capital letter. All following explanations refer to normalized numbers and names.

      If two different persons have the same phone number, that will be considered as being an error - none of these entries must appear in the final list. If two entries are equal, they must appear only once in the final list. If a person is listed with different phone numbers, this person has changed phone numbers over the years and will only appear with the latest of the listed numbers, that does not have to be removed because of the reason stated above.

      Input

      Input starts with a positive integer t (t<50) in a single line, then t testcases follow. Every testcase starts with one line containing a positive integer n (n<1000), the number of phone list entries, and - separated by a space - the area code of Adam's hometown. Then n lines follow, each line representing one entry in the phone list.

      Output

      For each testcase first print the number k of entries in the final list in a single line. Then k lines must follow, the cleaned up phone list. Each line is a single entry that has to look exactly like this: [first name] [last name]: [phone number]. Square brackets only for clarity. The list has to be sorted in alphabetical order according to last names (primary key) and - if necessary - first names (secondary key).

      Example

      Input:
      2
      10 0608
      Sastre,Carlos 030/64 736 666
      Voigt,Jens 07401-4498
      A Winokurow 0289-334405
      Jan ULLRICH 089-77 98 00 9
      089/779 8009 Ullrich,Jan
      LANCE Armstrong 0608 / 220 4 768 86
      Jan Ullrich 089/7798 005
      02 89 / 33 44 05 Contador,A
      ArmStrong,Lance 220476886
      Ullrich,JaN 0289 / 334405
      5 012
      Becker,Franz 1200344
      Becker,Boris 034/50005
      Boris Becker 012 / 50 005
      5000 5 Boris Becker
      Franz Beckenbauer 332323
       
      Output:
      4
      Lance Armstrong: 0608-220476886
      Carlos Sastre: 030-64736666
      Jan Ullrich: 089-7798005
      Jens Voigt: 07401-4498
      3
      Franz Beckenbauer: 012-332323
      Boris Becker: 012-50005
      Franz Becker: 012-1200344
      

      Added by:numerix
      Date:2011-03-07
      Time limit:1s-3s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8495. Maximum Subset of Array

      Problem code: MAXSUB

       

      Given an array find the sum of the maximum non-empty subset of the array and also give the count of the subset. A subset of an array is a list obtained by striking off some numbers.
      A non-empty subset implies a subset with at least 1 element in it.

       

      Given an array find the sum of the maximum non-empty subset of the array and also give the count of the subset. A subset of an array is a list obtained by striking off some (possibly none) numbers.

      A non-empty subset implies a subset with at least 1 element in it.

       

       

      Input

      First line contains an integer T which is the number of integers. Following this T-cases exist.

      Each case starts with a line containing an integer n which is the number of elements in the array.

      The next line contains n-integers which contain the value of this subset.

       

      T <= 20

      n <= 50,000

      Each element in the array <= 1000,000,000

      Output

      For each test case output the value of the maximum subset and the count of the subsets modulo 1000,000,009

      Example

      Input:
      2
      5
      1 -1 1 -1 1
      6
      -200 -100 -100 -400 -232 -450
      
      Output:
      3 1
      -100 2
      

      Added by:.:: Pratik ::.
      Date:2011-03-07
      Time limit:2s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8496. No Squares Numbers

      Problem code: NOSQ


       

      A square free number is defined as a number which is not divisible by any square number.
      For example,
      13, 15, 210 are square free numbers, where as 25 (divisible by 5*5), 108 (divisible by 6*6), 18 (divisible by 3*3) are not square free numbers.
      However number 1 is not considered to be a square and is a squarefree number.
      Now you must find how many numbers from number a to b, are square free and also have a digit d inside it.
      For example for in the range 10 to 40 te squarefree numbers having digit 3 are
      13, 23, 30, 31, 33, 34, 35, 37, 38, 39

       

      A square free number is defined as a number which is not divisible by any square number.

      For example,

      13, 15, 210 are square free numbers, where as 25 (divisible by 5*5), 108 (divisible by 6*6), 18 (divisible by 3*3) are not square free numbers.

      However number 1 is not considered to be a square and is a squarefree number.

      Now you must find how many numbers from number a to b, are square free and also have a digit d inside it.

      For example for in the range 10 to 40 te squarefree numbers having digit 3 are

      13, 23, 30, 31, 33, 34, 35, 37, 38, 39

       

       

      Input

      The first line contains an integer T, which is the number of test-cases

      Then follow T lines, each containing 3 integers a, b and d.

      1 <= T <= 20,000

      1 <= a <= b <= 100,000

      0 <= d <= 9

      Output

      Print one integer which is the required number as described in the problem statement.

      Example

      Input:
      3
      10 40 3
      1 100 4
      1 100000 7
      
      Output:
      10
      9
      26318
      

      Added by:.:: Pratik ::.
      Date:2011-03-07
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8505. Nacci Fear

      Problem code: NACCI

      We all know about the classical fibonaaci series, Fibonacci series is F(n)=F(n-1)+F(n-2). For this question we call it a 2-Nacci series as a new element is calculated as the sum of the last 2 terms of the series. For fibonaaci we assume F(0)=0 and F(1)=1. We define as new series N-Nacci where F(n) is the sum of the last n terms and here we assume that F(0)=0, F(1)=1,F(2)=2... F(n-1)=(n-1). Your task is to calculate the last K digits of the Lth term of the N-Nacci series(no leading zeros needed).

       

      Constraints

       

      2<=N<=30

      K<=8

      L<=1000000000

       

       

      Input

      The first line of the input denotes the number of test cases t(atmost 10). Each line denotes a test case consisting of N,K,L.

      Output

      For each test case print the last K digits of the Lth term of the N-Nacci series.

      Example

      Input:
      4
      2 1 5
      3 6 12
      4 1 10
      4 2 10
      
      Output:
      5
      778
      6
      16
      

      Added by:Saransh Bansal
      Date:2011-03-09
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      8507. Party Switching

      Problem code: PSWITCH


       

      Seraph is a smart boy who, one day at the time of his birthday he was wearing a lot of lights for the event. The number of lights is installed for as many as N, which are numbered 1 through N. lights are connected to a controller that has 4 buttons. Each button functions as follows:

      1. if this button is pressed, then all light will change the state from OFF to ON or from ON to OFF

      2. if this button is pressed, then the odd-numbered light will change its state

      3. if this button is pressed, then the even-numbered light will change its state

      4. if this button is pressed, all lights are numbered 3K +1 will change its state

      In the controller, there are counter C that count number of button will be pressed. when the initial state, the state of all the lights are ON and the counter C is set to 0. After that you will be given information of light at the end of the show, and you have to count how many kinds of configuration according to the information provided.

       

       

      Seraph is a smart boy who, one day at the time of his birthday he was wearing a lot of lights for the event. The number of lights is installed for as many as N, which are numbered 1 through N. lights are connected to a controller that has 4 buttons. Each button functions as follows:
      1. if this button is pressed, then all light will change the state from OFF to ON or from ON to OFF
      2. if this button is pressed, then the odd-numbered light will change its state
      3. if this button is pressed, then the even-numbered light will change its state
      4. if this button is pressed, all lights are numbered 3K +1 will change its state

      In the controller, there are counter C that count number of button will be pressed. when the initial state, the state of all the lights are ON and the counter C is set to 0. After that you will be given information of light at the end of the show, and you have to count how many kinds of configuration according to the info

      rmation ahdadhprovided.

      Input

      The first line containing N (10 <= N <= 100) that indicates number of lamps. The second line is C (1 <= C <= 1000) that indicate the final value of counte. The third line is lists the number of ON lights at the end of the show, each number separated by a space and the end of the line given the value -1. The fourth line is lists the number of OFF light at the end of the show, each number separated by a space and the end of the line given the value -1.

      Output

      configurations are possible at the end of the event. There should be no repetitive configuration and output must be in lexicographical. If there is no configuration, print "Impossible".

      Example

      Input:
      10
      1
      -1
      7 -1
      
      Output:
      0000000000
      0101010101
      0110110110
      
      Explanation :
      There is 10 lamps in that event and you have to pressed the button once, and at the end of event, lamp number 7 must be OFF.
      0 mean that lamp is OFF, 1 mean that lamp is ON 

      Added by:[Retired] Fendy Kosnatha
      Date:2011-03-10
      Time limit:0.050s-0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOI 1998









      SPOJ Problem Set (classical)

      8542. Modern Pocket Calculator

      Problem code: POCALC2


      Adam likes pocket calculators, not only the early ones, but also the modern ones with a two line LCD-display and mathematically correct operator precedence. The upper (input-)line shows the expression you typed in, the (output-)line below shows the result immediately after the [=] key has been pressed. Given the calculator's input-line, the program's task is to produce its output-line. Using the calculator's [S-D] key, the display switches between fractional and decimal representation of the result, so output must contain both representations.

      Display left Display right

      Input

      Input starts with a positive integer t (t<1000) in a single line, then t testcases follow. Every testcase consists of either three lines or a single line, representing the expression in the calculator's input-line, followed by a blank line. An expression contains n numbers (0 < n < 10) with exactly one operator (+, -, x, :) between any two numbers and exactly one space to separate number and operator. There will be no invalid expression and no undefined operation.
      A number is given as a decimal, a fraction or a mixed number and will be non-negative. If a number is positive, its decimal value is between 10-9 and 109, numerator and denominator are also non-negative and not larger than 109 each, given decimals have at most 9 digits overall. These constraints also hold for all calculations, if done properly. The length of the fraction bar depends on the maximum length of the numerator or the denominator respectively. If lengths of numerator and denominator are different, the shorter one will be centered based on the fraction bar. If centering isn't possible, it is set one digit to the right.

      Output

      For each testcase print the result the calculator will display in its output-line: first fractional, then decimal, both representations separated by " [S-D] ". If a result is negative, the negative sign has to be printed directly (i.e. no space) in front of the integer part or the fraction bar.
      The fractional representation has to be printed in lowest terms either as a proper fraction or mixed number. If the number has an integer representation, that has to be printed instead. Numerator and denominator have to be placed as described in the input section.
      After " [S-D] " the exact(!) decimal represenation has to be printed. As the screenshot shows, the calculator is even able to display a repeating decimal in its decimal representation using a vinculum, so that's what the program has to do as well, using underscores in the line above. You can assume that no decimal expansion is longer than 100 digits (it's a calculator with XXL-display).

      The number of lines for every output depends on the result. It may be three lines (if fractions appear) or a single line (if result is an integer). Print a blank line after every testcase except the last one. Be careful not to print any trailing spaces.

      For more clarity of input and output format please look at the examples below.

      Example

      Input:
      5
      9 50
      2-- + 0.26 x --
      11 15

      4 9
      5.88 - -- : -
      18 5

      3 - 5.125

      9 + 14

      1
      --- x 0.5
      100


      Output:
      113 __
      3--- [S-D] 3.684
      165

      1532 _________
      5---- [S-D] 5.75654320987
      2025

      1
      -2- [S-D] -2.125
      8

      23 [S-D] 23

      1
      --- [S-D] 0.005
      200

      Added by:numerix
      Date:2011-03-12
      Time limit:1s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8545. Subset sum

      Problem code: MAIN72

       

      you are given an array of N integers. Now you want to find the sum of all those integers which can be expressed as the sum of at least one subset of the given array.

      You are given an array of N integers. Now you want to find the sum of all those integers which can be expressed as the sum of at least one subset of the given array.

      Input

      First line contains T the number of test case. then T test cases follow,first line of each test case contains N (1<=N<=100) the number of integers, next line contains N integers, each of them is between 0 and 1000 (inclusive).  

      Output

      For each test case print the answer in a new line.

      Example

      Input:
      2
      2
      0 1
      3
      2 3 2
      
      Output:
      1
      21

      Added by:Mahesh Chandra Sharma
      Date:2011-03-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for NSIT-IIITA main contest #7









      SPOJ Problem Set (classical)

      8546. Manoj and Pankaj

      Problem code: MAIN73

       

      Manoj and Pankaj play the following game on a N*M grid, Each cell of which is either empty or contain a stone.
      Each player in his his turn must take one the two moves described below:-
      1. He can shift an stone to its adjacent right cell, if that cell is empty
      2. or he can remove a stone completely from the grid.
      Player who take the last turn will wins the game. It is also given that both the players will play optimally and Manoj always take the first turn.
      You have to find who will win the game. 

      Manoj and Pankaj play the following game on a N*M grid, Each cell of which is either empty or contain a stone.

      Each player in his his turn must take one the two moves described below:-

      1. He can shift an stone to its adjacent right cell, if that cell is empty

      2. He can remove a stone completely from the grid.

      1st player who is unable to take a move looses the game . It is also given that both the players will play optimally and Manoj always take the first turn.

      You have to find who will win the game. 

      Input

      First line of each test case contains two integers N and M. (1<=N,M<=200) Each of next N lines contains an string, jth character on of ith string is '*' if there is an stone otherise it is '.' (empty). Input ends when N, M = 0,0. which is not to be processed.

      Output

      For each test case print 'Manoj' if Manoj wins, print 'Pankaj' otherwise.

      Example

      Input:
      
      2 2
      .*
      .*
      
      2 2
      .*
      *.
      0 0
      Output:
      Pankaj
      Manoj

      Added by:Mahesh Chandra Sharma
      Date:2011-03-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for NSIT-IIITA main contest #7









      SPOJ Problem Set (classical)

      8547. Euclids algorithm revisited

      Problem code: MAIN74

       

      Consider the famous euclid algoithm to calculate the GCD of two integers (a, b):
      int gcd(int a, int b){
         while(b!=0){
             int temp = a
        a = b
        b = temp % b
         }
         return a;
      }
      for input (7, 3) the 'while' loop will run 2 times as follows: (7, 3)  => (3, 1) =>  (l, 0)
      Now given an integer N you have to find the smallest possible sum of two non-negative integers a, b (a>=b) such that
      the while loop in the euclid algorithm for (a, b) will run exactly N times.

      Consider the famous euclid algoithm to calculate the GCD of two integers (a, b):

      int gcd(int a, int b){

         while(b!=0){

             int temp = a

        a = b

        b = temp % b

         }

         return a;

      }

      for input (7, 3) the 'while' loop will run 2 times as follows: (7, 3)  => (3, 1) =>  (l, 0)

      Now given an integer N you have to find the smallest possible sum of two non-negative integers a, b (a>=b) such that the while loop in the above mentioned function for (a, b) will run exactly N times.

      Input

      First line of input contains T (1<=T<=50) the number of test cases. Each of the following T lines contains an integer N (0<=N<=10^18).

      Output

      For each test case print the required answer modulo 1000000007 in a seperate line.

      Example

      Input:
      1
      1
      
      Output:
       2
      Explaination: (1,1) is the required pair.

      Added by:Mahesh Chandra Sharma
      Date:2011-03-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for NSIT-IIITA main contest #7









      SPOJ Problem Set ()

      8549. BST again

      Problem code: MAIN75

       

      N nodes are labled with integers from 1 to N. Now these N nodes are inserted in a empty binary search tree. But the constraint is that
      we have to build this tree such that height of the tree is exactly equal to H. Your tast is to find how many distict binary search trees exists 
      of these nodes such that their height is exactly equal to H ?

      N nodes are labled with integers from 1 to N. Now these N nodes are inserted in a empty binary search tree. But the constraint is that we have to build this tree such that height of tree is exactly equal to H. Your tast is to find how many distict binary search trees exists of these nodes such that their height is exactly equal to H ?

      Two BSTs are considered to be different if there exist a node whose parent is different in both trees.

      Input

      Input First line contains 1<=T<=10 the number of test cases. Follwomg T lines contains 2 integers each. N and H. 1<=N<=500, 0<=H<=500.

      Output

      For each test case print the required answer modulo 1000000007.

      Example

      Input:
      1
      2 1
      Output:
      2

      Added by:Mahesh Chandra Sharma
      Date:2011-03-13
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for NSIT-IIITA main contest #7









      SPOJ Problem Set (classical)

      8550. Longest Square Factor

      Problem code: LSQF

      Given a string x, the string obtained by concatenating x to itself is sometimes called the square of x.

      Given a string s, output the longest string x such that its square is a substring of s. If you find more than one solution, output the lexicographically smallest.

      Input

      The first and only line of input contains a string s (consisting only of lowercase letters of the english alphabet). The length of s is less than or equal to 105.

      Output

      To the first line of output print the length of the string x.
      To the second line print the string x.

      Such a string will always exist in the test data.

      Example

      Input:
      abcabc

      Output:
      3
      abc

      Added by:Gustav Matula
      Date:2011-03-13
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8551. Colours A, B, C, D

      Problem code: ABCD


      Consider a table with 2 rows and 2N columns (a total of 4N cells). Each cell of the first row is coloured by one of the colours A, B, C, D such that there are no two adjacent cells of the same colour. You have to colour the second row using colours A, B, C, D such that:

      • There are exactly N cells of each colour (A, B, C and D) in the table.

      • There are no two adjacent cells of the same colour. (Adjacent cells share a vertical or a horizontal side.)

      It is guaranteed that the solution, not necessarily unique, will always exist.

      Input

      [a natural number N ≤ 50000]

      [a string of 2N letters from the set {A, B, C, D}, representing the first row of the table]

      Output

      [a string of 2N letters from the set {A, B, C, D}, representing the second row of the table]

      Example

      Input

      1

      CB

      Output

      AD

       

      Input

      2

      ABAD 

      Output

      BCDC


      Added by:Adrian Satja Kurdija
      Date:2011-03-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:originated from a mathematical problem









      SPOJ Problem Set (classical)

      8558. Linear Equation Solver

      Problem code: LINQSOLV

      Given a system of linear equations, print the solution of that system.

      Input

      Input starts with a positive integer t<100 in a single line, then t testcases follow. Every testcase represents a linear system and starts with one line containing a positive integer n<21, the number of equations and also the number of variables of that system. Then n equations follow, each one in a single line.
      An equation is written in schoolbook notation, i.e. variables noted by single small letters (english alphabet), no multiplication sign, factor 1 left out, no spaces in between. A variable or a value may occur zero or more times in an equation. All coefficients are integers with an absolute value less than 100, a single line won't be longer than 100 characters and will always contain a valid linear equation.

      The following equations are considered to be valid:
      a+b-c+b-2c-a=1       -x+5-9=-4x+y-8       c-c+t+1=0       y=z

      The following equations are considered to be invalid:
      4*a+b=6       6+-2x=99       c-c+t-t=0       4+9 = h

      Output

      For each testcase print all variables of the linear system in alphabetical order together with the associated value as an integer or a fraction in lowest terms respectively. Print a blank line between testcases. For exact notation see example below. All (interim) results will fit into 64-bit, if algorithm is implemented properly. You can assume that all linear systems have an unique solution.

      Example

      Input:
      2
      2
      a+b=5
      b-a=1
      3
      5u-5z+4=0
      8k-3z=-2
      9k-u=u
       
      Output:
      a=2
      b=3
      
      k=-4/55
      u=-18/55
      z=26/55
      

      Added by:numerix
      Date:2011-03-14
      Time limit:2s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8574. Four in a row

      Problem code: FOUROW

      Four in a row

      You probably know the popular two-players game "Four in a row". Each player gets 21 chips of the same color at the beginning. Then the two players take turns in putting a chip into one of seven slots (each one six cells in height), trying to get at least four of their chips "in a row", i.e. horizontally, vertically or diagonally.
      Given a series of moves, your task is to first check, if this is a valid game. A game is invalid, if one or more moves are made after a player has already won the game or if more than six chips are put into a single slot. If a game is valid, check if the game is over. A game is over, if one of the players got at least four chips "in a row" with his last move (i.e. he is the winner of the game) or if all slots are filled. If a game is over, check if there is a winner and if so, who it is. If there is a winner, then print the final state of the game.
      The picture shows the final state of a game, won by the first player (yellow chips).

      Input

      Input starts with a positive integer t<100 in a single line, then t testcases follow. Every testcase starts with "Game #n: ", where n is the number of the game, numbered from 1 to t. Then the description of a game follows, given as a series of digits 1 to 7 indicating the number of the slot (as noted in the picture), in which the player puts his chip. The players are taking turns and the number of moves (i.e. the number of chips put into the slots) will be at most 42.

      Output

      For each testcase print exactly one of the following five lines, where n has to be replaced by the game's number:
      Game #n is invalid.
      Game #n is over. There is no winner.
      Game #n is over. The first player won.
      Game #n is over. The second player won.
      Game #n is not over, yet.

      If there is a winner, you also have to print a snapshot of the game's final state. A game's state consists of at most six lines representing the (horizontal) rows of the game's grid plus a leading and a trailing line containing seven hyphens. Every line has a length of exactly seven characters. Use "x" for the chips of the first player, "o" for those of the second player, whitespaces for all cells without a chip. If a (horizontal) row contains only whitespaces, it must not be printed.

      To make it easier to find the winning row in the grid, all chips that belong to the winning row(s) have to be marked either by "X" (instead of "x", if the first player has won) or by "O" (instead of "o", if the second player has won). Be aware that there can be more than four chips in a winning row and more than one winning row!

      Example

      Input:
      2
      Game #1: 2143563445575
      Game #2: 123456
      
      Output:
      Game #1 is over. The first player won.
      -------
          X  
         Xx  
        Xoo  
      oXoxxoo
      -------
      Game #2 is not over, yet.
      
      

      Added by:numerix
      Date:2011-03-17
      Time limit:1s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8578. Reverse the Sequence

      Problem code: REVSEQ


      This is a very ad-hoc problem. Consider a sequence (N, N-1, ..., 2, 1). You have to reverse it, that is, make it become (1, 2, ..., N-1, N). And how do you do this? By making operations of the following kind.

      Writing three natural numbers A, B, C such that 1 ≤ A ≤ B < C ≤ N means that you are swapping the block (block = consecutive subsequence) of elements occupying positions A...B with the block of elements occupying positions B+1..C. Of course, the order of elements in a particular block does not change.

      This means that you can pick any two adjacent blocks (each of an arbitrary length) and swap them. The problem can easily be solved in N-1 operations, but to make it more difficult, you must think of a faster way.

      Input

      A natural number 1 < N < 100.

      Output

      Output at most 50 operations, one per line. Each opearations is represented by three numbers as described above.

      Example

      Input:
      5
      
      Output:
      2 3 5
      1 2 4
      2 3 5
      Explanation of the sample output: (5 4 3 2 1) --> (5 2 1 4 3) --> (1 4 5 2 3) --> (1 2 3 4 5)

      Added by:Adrian Satja Kurdija
      Date:2011-03-18
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:originated from a mathematical problem









      SPOJ Problem Set (classical)

      8583. Garden

      Problem code: NPOWM

      Vasja is a very beautiful country garden, which is a rectangular box the size of n × m, divided by n · m square cells. One day, Bob remembered that he needed to pave the path between k cells with important buildings - for that he can fill in some of the concrete cells of the garden.

      About every cell of the garden known number of aij, which means the number of flowers growing in the cell with coordinates (i, j). When pouring concrete all the flowers that grow in the cell dies.

      Bob wants to pour concrete, some cells so that the following conditions:

          
      * K all the important cells have to be filled with concrete
          
      * Each of the major cell to any other cells there was an important way of concrete poured, the cells under the condition that neighboring cells are considered as having a common side
          
      * Total number of dead plants should be minimal

      Since Wasi quite a large garden, it asks you to help him.

      Input

      The first line of input data are given three integers n, m and k (1 ≤ n, m ≤ 100, n · m ≤ 200, 1 ≤ k ≤ min (n · m, 7) - the size of the garden and the number of important cells. Next the n rows of m numbers are given in each of aij (1 ≤ aij ≤ 1000) - the number of colors in the cells. Then the k rows are the coordinates of the critical cells in the form «xy» (without quotation marks) (1 ≤ x ≤ n, 1 ≤ y ≤ m). numbers are located on the same line, separated by spaces. It is guaranteed that all k important cells have different coordinates.

      Output

      In the first line of the output single integer - the minimum number of deaths in the construction of plants. Then output n lines of m characters each - the plan of the garden, where the symbol «X» (a capital letter X) is flooded with concrete cell, and the symbol "." (Point) - is not flooded. If several solutions, any output.

      Input

      3 3 2
      1 2 3
      1 2 3
      1 2 3
      1 2
      3 3
      Output
      9
      .X.
      .X.
      .XX

      Added by:Azat Taryhchiyev
      Date:2011-03-19
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://codeforces.ru/contest/152/problem/E









      SPOJ Problem Set (classical)

      8586. Factorial factorisation

      Problem code: PRIME

      Factorial n! of an integer number n ≥ 0 is defined recursively as follows:

      0! = 1
      n! = n * (n - 1)!

      While playing with factorials chEEtah noticed that some of them can be represented as a product of other factorials, e.g. 6! = 3! * 5! = 720. Such factorisation helps chEEtah to simplify a certain class of equations he is working on during his research.

      So he needs a program that finds a compact factorisation of a given factorial or determines that it is impossible if that is the case. If there are more than one factorisation the program has to find such that contains the minimum number of terms. For example, 10! can be factorised in two different ways: 10! = 6! * 7! = 3! * 5! * 7!. The first factorisation contains only two terms and should be preferred to the second one. If there are several factorisations with the same minimum number of terms then any optimal solution is acceptable.

      Input

      Input contains the only integer 2 ≤ n ≤ 1000 which factorial n! should be factorised.

      Output

      Output should contain the optimal factorisation in the format shown in the samples. The factorisation terms should go in non-decreasing order. If no factorisation can be found print No solution.

      Example

      Input:
      9

      Output:
      9! = 2! * 3! * 3! * 7!



      Added by:Azat Taryhchiyev
      Date:2011-03-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8 JAR JAVA NODEJS PAS fpc PAS gpc PIKE PYTH 3.2.3 n
      Resource:olymp.krsu.edu.kg









      SPOJ Problem Set (classical)

      8591. Prime Permutations

      Problem code: PRIMPERM

      Given two positive integers n and m, we call m a prime permutation of n, if m is prime and can be obtained by zero or more permutations of the digits of n. Permutations with leading zeros are invalid.

      Input

      Input starts with a positive integer t<104 in a single line, then t lines follow.
      Each of the t lines contains one positive integer n<107.

      Output

      For every n print the number of distinct prime permutations of n in a single line.

      Example

      Input:
      2
      13
      110
      
      Output:
      2
      1
      

      Hint:If your solution times out, you may try the tutorial version with a weaker time limit.


      Added by:numerix
      Date:2011-03-20
      Time limit:2s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8594. Tails all the way

      Problem code: TAILS

      John and James planned to play a game with coins. John has 20 coins and he places it on the table in a random manner(i.e either with heads(1) or tails(0) facing up). John asked james to convert all heads into tails in minimum number of flips with the condition that if a coin is flipped the coins present to the right and left of the chosen coin should also be flipped.

      Input

      A single line with 20 space-separated integers

      Output

      The minimum number of coin flips necessary to convert all heads into tails (i.e., to 0). For the inputs given, it will always be possible to find some combination of flips that will manipulate the coins to 20 tails.

      Example

      Input:
      0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0

      Output: 3

      Hint
      Explanation of the sample:
       
      Flip coins 4, 9, and 11 to make them all tails:
      0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 [initial state]
      0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 [after flipping coin 4]
      0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 [after flipping coin 9]
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [after flipping coin 11]

      Added by:Infinity
      Date:2011-03-21
      Time limit:1s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:AWK BF C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA JS NODEJS PAS fpc PAS gpc PERL PERL 6 PHP PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n RUBY SCALA SED TCL
      Resource:Own









      SPOJ Problem Set (classical)

      8596. Wood, Axe and Grass

      Problem code: WAGE

      Danny has created a new civilization on a 2D grid. At the outset each grid location may be occupied by one of three life forms: Woods, Axe, or Grass. Each day, differing life forms occupying horizontally or vertically adjacent grid locations wage war. In each war, Woods always defeat Axe, Axe always defeat Grass, and Grass always defeat Woods. At the end of the day, the winner expands its territory to include the loser's grid position. The loser vacates the position.Determine the territory occupied by each life form after n days.

      Input

      The first line of input contains t, the number of test cases. Each test case begins with three integers not greater than 100: r and c, the number of rows and columns in the grid, and n. The grid is represented by the r lines that follow, each with c characters. Each character in the grid is W, A, or G, indicating that it is occupied by Woods, Axe, or Grass respectively.

      Output

      For each test case, print the grid as it appears at the end of the nth day.

      Example

      Input:
      2
      3 3 1
      WWW
      WAW
      WWW
      3 4 2
      WAGW
      AGWA
      GWAG


      Output: WWW
      WWW
      WWW
       
      WWWA
      WWAG
      WAGW

      Added by:Infinity
      Date:2011-03-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:AWK BF C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA JS NODEJS PAS fpc PAS gpc PERL PERL 6 PHP PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n RUBY SCALA SED
      Resource:Own









      SPOJ Problem Set (classical)

      8598. Traverse through the board

      Problem code: TRAVERSE

      An n x n game board is filled with integers, one positive integer per square. The objective is to travel along any legitimate path from the upper left corner to the lower right corner of the board.  
       
      Rules
       
      1.The number in any one square describes how far a step away from that location must be.  
      2.If the step size moves out of the game board, then that step is not allowed.
      3.All steps must be either to the right or towards the bottom.  
       
      Note that a 0 is a dead end which prevents any further progress.  
       
      Consider the 4 x 4 board shown in Figure 1, where the solid circle identifies the start position and the dashed circle identifies the target. Figure 2 shows the three paths from the start to the target, with the irrelevant numbers in each removed.

      fig

      Input

      The first line contains the value of n followed by a nxn matrix depicting the board configuration.

      Output

      The output consists of  a single integer, which is the number of paths from the upper left corner to the lower right corner.

      Example 

      Input:


      2331
      1213
      1231
      3110

      Output:
      3

      Input:


      3332
      1213
      1232
      2120

      Output:

      0

      Input:

      5
      11101
      01111
      11111
      11101
      11101
            
      Output:
      7


      Added by:Infinity
      Date:2011-03-21
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:AWK BF C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA JS NODEJS PAS fpc PAS gpc PERL PERL 6 PHP PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n RUBY SCALA SED









      SPOJ Problem Set (classical)

      8611. Non-Decreasing Digits

      Problem code: NY10E

      A number is said to be made up of non-decreasing digits if all the digits to the left of any digit is less than or equal to that digit.For example, the four-digit number 1234 is composed of digits that are non-decreasing.  Some other four-digit numbers that are composed of non-decreasing digits are 0011, 1111, 1112, 1122, 2223.  As it turns out, there are exactly 715 four-digit numbers composed of non-decreasing digits.
       
      Notice that leading zeroes are required: 0000, 0001, 0002 are all valid four-digit numbers with non-decreasing digits.
       
      For this problem, you will write a program that determines how many such numbers there are with a specified number of digits.

      Input

      The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow.  Each data set is a single line that contains the data set number, followed by a space, followed by a decimal integer giving the number of digits N, (1 ≤ N ≤ 64).

      Output

      For each data set there is one line of output.  It contains the data set number followed by a single space, followed by the number of N digit values that are composed entirely of non-decreasing digits.

      Example

      Input:
      3
      1 2
      2 3
      3 4

      Output:
      1 55
      2 220
      3 715

      Added by:John Mario
      Date:2011-03-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM Greater New York Regionals 2010









      SPOJ Problem Set (classical)

      8612. Penney Game

      Problem code: NY10A

      Penney’s game is a simple game typically played by two players.  One version of the game calls for each player to choose a unique three-coin sequence such as HEADS TAILS HEADS (HTH).  A fair coin is tossed sequentially some number of times until one of the two sequences appears.  The player who chose the first sequence to appear wins the game.

      For this problem, you will write a program that implements a variation on the Penney Game.  You willread a sequence of 40 coin tosses and determine how many times each three-coin sequence appears.  Obviously there are eight such three-coin sequences: TTT, TTH, THT, THH, HTT, HTH, HHT and HHH. Sequences may overlap.  For example, if all 40 coin tosses are heads, then the sequence HHH appears 38 times.

      Input

      The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow.  Each data set consists of 2 lines.  The first line contains the data set number N.  The second line contains the sequence of 40 coin tosses.  Each toss is represented as an upper case H or an upper case T, for heads or tails, respectively.  There will be no spaces on any input line.

      Output

      For each data set there is one line of output.  It contains the data set number followed by a single space, followed by the number of occurrences of each three-coin sequence, in the order shown above, with a space between each one.  There should be a total of 9 space separated decimal integers on each output line.

      Example

      Input:
      4
      1
      HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
      2
      TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
      3
      HHTTTHHTTTHTHHTHHTTHTTTHHHTHTTHTTHTTTHTH
      4
      HTHTHHHTHHHTHTHHHHTTTHTTTTTHHTTTTHTHHHHT

      Output:
      1 0 0 0 0 0 0 0 38
      2 38 0 0 0 0 0 0 0
      3 4 7 6 4 7 4 5 1
      4 6 3 4 5 3 6 5 6

      Added by:John Mario
      Date:2011-03-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM Greater New York Regionals 2010









      SPOJ Problem Set ()

      8624. Nim-B Sum

      Problem code: NY10B

      Note: This problem has nothing to do with siting sewage plants, power lines or wind farms. NIM is an ambigram.

      The game of NIM is played with any number of piles of objects with any number of objects in each pile. At each turn, a player takes one or more (up to all) objects from one pile. In the normal form of the game, the player who takes the last object is the winner. There is a well-known strategy for this game based on the nim-2 sum.

      The Nim-B sum (nim sum base B) of two non-negative integers X and Y (written NimSum(BXY)) is computed as follows:

      1. Write each of X and Y in base B.
      2. Each digit in base B of the Nim-B sum is the sum modulo B of the corresponding digits in the base B representation of X and Y.

      For example:

       NimSum(2, 123, 456) = 1111011 ¤ 111001000 = 110110011 = 435

      NimSum(3, 123, 456) = 11120 ¤ 121220 = 102010 = 300

      NimSum(4, 123, 456) = 1323 ¤ 13020 = 10303 = 307

      The strategy for normal form Nim is to compute the Nim-2 sum T of the sizes of all piles. If at any time, you end your turn with T = 0, you are guaranteed a WIN. Any opponent move must leave T not 0 and there is always a move to get T back to 0. This is done by computing NimSum(2, TPS) for each pile; if this is less than the pile size (PS), compute the difference between the PS and the Nim-2 sum and remove it from that pile as your next move.

      Write a program to compute NimSum(BXY).

      Input

      The first line of input contains a single integer P, (1$ \le$P$ \le$1000), which is the number of data sets that follow. Each data set is a single line that contains the data set number, followed by a space, followed by three space separated decimal integers, BX and Y. 2$ \le$B$ \le$2000000, 0$ \le$X$ \le$2000000, 0$ \le$Y$ \le$2000000.

      Output

      For each data set there is one line of output. It contains the data set number followed by a single space, followed by N, the decimal representation of the Nim sum in base B of X and Y.

      Sample Input

      4
      1 2 123 456
      2 3 123 456
      3 4 123 456
      4 5 123 456

      Sample Output

      1 435
      2 300
      3 307
      4 429



      Added by:Juan Sebastian Beltran Rojas
      Date:2011-03-23
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Greater New York Region 2010









      SPOJ Problem Set (classical)

      8625. Just The Simple Fax

      Problem code: NY10C

      Fax machines use a form of compression based on run-length encoding. Run-length encoding (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. This is most useful on data that contains many such runs: for example, relatively simple graphic images such as icons, text, and line drawings. It is not useful with files that don't have many runs as it could potentially double the file size (photograph, for example).

      For this problem, you will write a program that encodes a block of data using a very simple RLE algorithm. A run is encoded using a two byte sequence. The first byte of the sequence contains the count, and the second contains the value to repeat. The count is encoded using an 8 bit value with the high order bit set to 1. The remaining 7 bits represent the count-3. This gives a maximum run count of 130 per 2 byte sequence. (This implies that the minimum run count is 3). Bytes that are not part of a run are encoded as-is with a prefix byte indicating the count of bytes in the non-run minus 1, 0 through 127, representing a range of 1 - 128 (the high order bit will always be 0 in the case of non-run data).

      If a run contains more than 130 bytes, then it must be encoded using multiple sequences, the first of which will always be a run of 130. All runs of 3 or more must be encoded as a run. If a non-run contains more than 128 bytes, then multiple non-run sequences must be used. For example, a run of 262 would be encoded as two runs of 130 followed by a non-run of 2.

      Input

      The first line of input contains a single integer P, (1$ \le$P$ \le$1000), which is the number of data sets that follow. Each data set consists of multiple lines. The first line contains two (2) decimal integer values: the problem number, followed by a space, followed by the number of bytes B, (1$ \le$B$ \le$5000), to encode. The remaining line(s) contain(s) the data to be encoded. Each line of data to encode will contain 80 hexadecimal digits (except the last line, which may contain less). 2 hexadecimal digits are used to represent each byte. Hexadecimal digits are: 0123456,789ABCDEF.

      Output

      For each data set, there are multiple lines of output. The first line contains a decimal integer giving the data set number followed by a single space, followed by a decimal integer giving the total number of encoded bytes. The remaining lines contain the encoded data each with 80 hexadecimal digits, except the last, which may contain less.

      Example

      Input:
      
      4 
      1 1 
      07 
      2 5 
      F4A5A5A5A5 
      3 44 
      0000000000000000FFFFFF66665A5A5A5A5A71727374758008011011135555555555555501020399 
      777777CC 
      4 40 
      68686868686868686868686868686868686868686868686868686868686868686868686868686868
      Output:
      1 2 
      0007 
      2 4 
      00F481A5 
      3 32 
      850080FF016666825A0A717273747580080110111384550301020399807700CC 
      4 2 
      A568

      Added by:Diego Satoba
      Date:2011-03-23
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Greater New York Region 2010









      SPOJ Problem Set (classical)

      8626. Show Me The Fax

      Problem code: NY10D

      Fax machines use a form of compression based on run-length encoding. Run-length encoding (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. This is most useful on data that contains many such runs: for example, relatively simple graphic images such as icons, text, and line drawings. It is not useful with files that don't have many runs as it could potentially double the file size (photograph, for example).

      For this problem, you will write a program that decodes a block of data using a very simple RLE algorithm. A run is encoded using a two byte sequence. The first byte of the sequence contains the count, and the second contains the value to repeat. The count is encoded using an 8 bit value with the high order bit set to 1. The remaining 7 bits represent the count-3. This gives a maximum run count of 130 per 2 byte sequence. (This implies that the minimum run count is 3). Bytes that are not part of a run are encoded as-is with a prefix byte indicating the count of bytes in the non-run minus 1, 0 through 127, representing a range of 1 - 128 (the high order bit will always be 0 in the case of non-run data).

      Input

      The first line of input contains a single integer P, (1$ \le$P$ \le$1000), which is the number of data sets that follow. Each data set consists of multiple lines. The first line contains two (2) decimal integer values: the problem number, followed by a space, followed by the number of bytes B, (1$ \le$B$ \le$5000), to decode. The remaining line(s) contain(s) the data to be decoded. Each line of data to decode contains 80 hexadecimal digits (except the last line, which may contain less). 2 hexadecimal digits are used to represent each byte. Hexadecimal digits are: 01234567,89ABCDEF

      Output

      For each data set, there are multiple lines of output. The first line contains a decimal integer giving the data set number followed by a single space, followed by a decimal integer giving the total number of decoded bytes. The remaining lines contain the decoded data, 80 hexadecimal digits per line, except the last line which may contain less.

      Example

      Input:
      
      4 
      1 2 
      0007 
      2 4 
      00F481A5 
      3 32 
      850080FF016666825A0A717273747580080110111384550301020399807700CC 
      4 2 
      A568
      Output:
      1 1 
      07 
      2 5 
      F4A5A5A5A5 
      3 44 
      0000000000000000FFFFFF66665A5A5A5A5A71727374758008011011135555555555555501020399 
      777777CC 
      4 40 
      68686868686868686868686868686868686868686868686868686868686868686868686868686868

      Added by:Diego Satoba
      Date:2011-03-23
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Greater New York Region 2010









      SPOJ Problem Set (classical)

      8627. I2C

      Problem code: NY10F

      I2C (Inter-Integrated Circuit) is a serial communication protocol that is used to attach low-speed peripherals (100 kbit/sec) to a motherboard, embedded system or cell phone. A single I2C data bus may have several devices attached, each with a different 7-bit address. One of the nice things about I2C is that it only requires two signal lines, SCL (clock) and SDA (data). One bit of data is presented on the I2C data bus (SDA line) per clock (SCL). Typically, one device on the bus is designated as the master, and the other devices are slaves. The master will initiate communication to a specific device on the bus by specifying its address in a transaction.

      If there is no activity on the I2C bus, both the SCL and SDA signals are in a high state (1). The master initiates a transaction on the bus by pulling the SDA signal to a low state (0), while the SCL signal is high (1): this is called a START bit. At this point, all slaves on the bus must start paying attention to the signaling to see if the transaction is directed at them. The master will then send the 7bit slave address (most significant bit first), one bit at-a-time. This is done by bringing the SCL signal low (0), presenting the next bit value on the SDA line, then releasing the SCL signal so it goes high (1). The slaves will read the SDA signal as soon as the clock goes high (1). This operation is repeated 7 times, one for each bit of the desired slave address. Another data bit is presented on the bus in the same manner. This last bit is an indicator as to whether the master wants to read from (1) or write to (0) the addressed slave device. When a slave recognizes its address on the bus, it must acknowledge (ACK) that it is available and ready by pulling the SDA line low. The master will see this the next time it brings the clock high, at which point, the data transfer can begin. If no ACK is seen this means that the slave specified by the address does not exist. Note: If no device pulls a signal low, it will go high by default; a device simplyreleases a signal, and it will go high.

      Data is always transferred as 8 bit bytes, 1 bit at-a-time, most significant bit first. After each byte, the slave must ACK the master by pulling the SDA line low. If the slave is not ready to transmit (or receive) the next byte of data, it may pull the SCL line low. This will cause the master to go into a wait mode until the slave is ready. The slave indicates it is ready by bringing SDA low, and releasing the SCL line so it goes high. The next byte of data can then be transferred. The sequence repeats until the master decides all the data has been transferred, at which point it will send a STOP bit. This is done when the master lets the SDA line go high while the SCL line is high.

      For this problem, you will write a program that sniffs the I2C bus signals and displays the details of transactions.

      Input

      The first line of input contains a single integer P, (1$ \le$P$ \le$1000), which is the number of data sets that follow. Each data set consists of multiple lines which represents a single I2C transaction. The first line contains two (2) decimal integer values: the problem number, followed by a space, followed by the number of signal samples S, (1$ \le$S$ \le$1161), for the transaction. The remaining line(s) contain(s) the signal samples. Each line of samples contains 40 samples (except the last which may contain less). Each sample consists of 2 binary digits characters representing SCL and SDA in that order.

      Output

      For each data set, display a single line containing a decimal integer giving the data set number followed by a single space, followed by a description of the transaction. There will only be six different descriptions (two non-error cases, and four error cases):

      Non-error cases:

      WRITE OF n BYTES TO SLAVE xx

      READ OF n BYTES FROM SLAVE xx

       Error cases:

      ERROR NO START BIT

      ERROR NO STOP BIT

      ERROR NO ACK FROM SLAVE xx

      ERROR NO ACK FOR DATA

      n is a decimal integer (1 - 128) representing the number of data bytes. 
      xx is a 2 digit hexadecimal value (00-7F) representing the slave address. 
      The ERROR NO ACK FROM SLAVE xx case occurs when there is no ACK for the supplied address 
      The ERROR NO ACK FOR DATA case occurs when there is no ACK after a data byte

      For the error cases, only the first error detected should be displayed.

      Example

      Input:
      
      4 
      1 97 
      01111001110010001000100111011101110111001000100010011100100010001000100010001000 
      10001001110010001000100010011100100010001001110010001000100111001000100010001001 
      1100100010001001110111001000101111 
      2 169 
      01111000100010011100100010001001110010001000100010011100100010001000100010001000 
      10001001110010001000100010011100100010001001110010001000100111001000100010001001 
      11001000100010011101110010001000100111001000100111001000100010001000100111001000 
      10011100100111001000100010011100100010011101110010001000100010011100100010011101 
      110111001000101111 
      3 60 
      01111000100010001001110010011101110010001000100010011100100010001000100010001000 
      1000100111001000100010001001110010001111 
      4 40 
      01111000100010011101110010011100100111001111111111111111111111111111111111111111
      Output:
      1 READ OF 4 BYTES FROM SLAVE 47
      2 WRITE OF 8 BYTES TO SLAVE 11 
      3 ERROR NO STOP BIT 
      4 ERROR NO ACK FROM SLAVE 0B

      Added by:Diego Satoba
      Date:2011-03-23
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Greater New York Region 2010









      SPOJ Problem Set ()

      8628. Selling Land

      Problem code: NWERC10G

      As you may know, the country of Absurdistan is full of abnormalities. For example, the whole country can be divided into unit squares that are either grass or swamp. Also, the country is famous for its incapable bureaucrats. If you want to buy a piece of land (called a parcel), you can only buy a rectangular area, because they cannot handle other shapes. The price of the parcel is determined by them and is proportional to the perimeter of the parcel, since the bureaucrats are unable to multiply integers and thus cannot calculate the area of the parcel.

      Per owns a parcel in Absurdistan surrounded by swamp and he wants to sell it, possibly in parts, to some buyers. When he sells a rectangular part of his land, he is obliged to announce this to the local bureaucrats. They will first tell him the price he is supposed to sell it for. Then they will write down the name of the new owner and the coordinates of the south-east corner of the parcel being sold. If somebody else already owns a parcel with a south-east corner at the same spot, the bureaucrats will deny the change of ownership.

      Per realizes that he can easily trick the system. He can sell overlapping areas, because bureaucrats only check whether the south-east corners are identical. However, nobody wants to buy a parcel containing swamp.

      Now Per would like to know how many parcels of each perimeter he needs to sell in order to maximize his profit. Can you help him? You may assume that he can always find a buyer for each piece of land, as long as it doesn't contain any swamps. Also, Per is sure that no square within his parcel is owned by somebody else.

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • One line with two integers n and m (1 ≤ n, m ≤ 1 000): the dimensions of Per's parcel.
      • n lines, each with m characters. Each character is either `#' or `.'. The j-th character on the i-th line is a `#' if position (i, j) is a swamp, and `.' if it is grass. The north-west corner of Per's parcel has coordinates (1, 1), and the south-east corner has coordinates (n,m).

       

      Output

      Per test case:

      • Zero or more lines containing a complete list of how many parcels of each perimeter Per needs to sell in order to maximize his profit. More specifically, if Per should sell p

      Example

      Input:
      
      1
      6 5
      ..#.#
      .#...
      #..##
      ...#.
      #....
      #..#.
      Output:
      6 x 4
      5 x 6
      5 x 8
      3 x 10
      1 x 12

      Added by:Diego Satoba
      Date:2011-03-23
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2010 Contest









      SPOJ Problem Set ()

      8629. Stock Prices

      Problem code: NWERC10H

      In this problem we deal with the calculation of stock prices. You need to know the following things about stock prices:

      • The ask price is the lowest price at which someone is willing to sell a share of a stock.
      • The bid price is the highest price at which someone is willing to buy a share of a stock.
      • The stock price is the price at which the last deal was established.

      Whenever the bid price is greater than or equal to the ask price, a deal is established. A buy order offering the bid price is matched with a sell order demanding the ask price, and shares are exchanged at the rate of the ask price until either the sell order or the buy order (or both) is fulfilled (i.e., the buyer wants no more stocks, or the seller wants to sell no more stocks). You will be given a list of orders (either buy or sell) and you have to calculate, after each order, the current ask price, bid price and stock price.

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • One line with an integer n (1 ≤ n ≤ 1 000): the number of orders.
      • n lines of the form "order_type x shares at y", where order_type is either "buy" or "sell", x (1 ≤ x ≤ 1 000) is the number of shares of a stock someone wishes to buy or to sell, and y (1 ≤ y ≤ 1 000) is the desired price.

      Output

      Per test case:

      • n lines, each of the form "ai bi si" , where ai, bi and si are the current ask, bid and stock prices, respectively, after the i-th order has been processed and all possible deals have taken place. Whenever a price is not defined, output "-" instead of the price.

      Example

      Input:
      
      2
      6
      buy 10 shares at 100
      sell 1 shares at 120
      sell 20 shares at 110
      buy 30 shares at 110
      sell 10 shares at 99
      buy 1 shares at 120
      6
      sell 10 shares at 100
      buy 1 shares at 80
      buy 20 shares at 90
      sell 30 shares at 90
      buy 10 shares at 101
      sell 1 shares at 80
      Output:
      - 100 -
      120 100 -
      110 100 -
      120 110 110
      120 100 99
      - 100 120
      100 - -
      100 80 -
      100 90 -
      90 80 90
      100 80 90
      100 - 80

      Added by:Diego Satoba
      Date:2011-03-23
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2010 Contest









      SPOJ Problem Set ()

      8651. Alien arithmetic

      Problem code: ALIENS1

      Little Johnny of Byteland has been kidnapped by aliens from the Andromeda galaxy! Johnny is currently locked in a small room inside an UFO, which has been parked in his backyard. Johnny is desparately trying to open the door of the room. He finds that the door asks a series of arithmetic questions: addition, subtraction, mutltiplication or exponentiation (the aliens dont know how to divide) of two given numbers. Johnny laughs aloud and thinks that it will be very easy to answer these questions and escape. But when he sees the questions, he realises that the aliens use base 42! Now Johnny has panicked and asks you to help him out.

       

      Input


      The first line of the input has a number T (<= 500), denoting the number of tests cases. T lines follows, each of the form A op B, where A and B are numbers in base 42 having upto 10000 digits without unnecessary zeros and op is either +, -, * or ^ denoting the operation to be performed. Base 42 numbers are denoted by:

      '0' to '9' denotes 0 to 9

      'A' to 'Z' denotes 10 to 35

      'a' to 'f' denotes 36 to 41

      Output

       

      For each test case, output one line: the result of the required operation in base 42 modulo LIFE42, without any unnessary zeros.

       

      Example

      Input:
      11
      a + a
      e - A
      91 * 89
      AEIOU + abcd
      A - B
      b ^ 2
      5 ^ 0
      123 - 45
      ABC * 10
      6 - 6
      0 ^ 0
      
      Output:
      1U
      U
      1W59
      L6ZR
      LIFD
      WP
      1
      de
      ABC0
      0
      1
      Warning: large Input/Output data, be careful with certain languages.

      Added by:Balajiganapathi S
      Date:2011-03-26
      Time limit:2s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      8661. Bogosort

      Problem code: CHEFFEB

      Recently Johnny have learned bogosort sorting algorithm. He thought that it is too ineffective. So he decided to improve it. As you may know this algorithm shuffles the sequence randomly until it is sorted. Johnny decided that we don't need to shuffle the whole sequence every time. If after the last shuffle several first elements end up in the right places we will fix them and don't shuffle those elements furthermore. We will do the same for the last elements if they are in the right places. For example, if the initial sequence is (3, 5, 1, 6, 4, 2) and after one shuffle Johnny gets (1, 2, 5, 4, 3, 6) he will fix 1, 2 and 6 and proceed with sorting (5, 4, 3) using the same algorithm. Johnny hopes that this optimization will significantly improve the algorithm. Help him calculate the expected amount of shuffles for the improved algorithm to sort the sequence of the first n natural numbers given that no elements are in the right places initially.

      Input

      The first line of input file is number t - the number of test cases. Each of the following t lines hold single number n - the number of elements in the sequence.

      Constraints

      1 <= t <= 175
      2 <= n <= 175

      Output

      For each test case output the expected amount of shuffles needed for the improved algorithm to sort the sequence of first n natural numbers in the form of irreducible fractions.

      Example

      Input:
      3
      2
      6
      10
      
      Output:
      2
      1826/189
      877318/35343
      
      

      Added by:Spooky
      Date:2011-03-27
      Time limit:2s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeChef February Challenge 2011









      SPOJ Problem Set (classical)

      8663. Squares Game

      Problem code: CHEFMAR

      Fat Tony and Fit Tony are playing the square painting game. There are n squares drawn on a plane. The sides of the squares are parallel to the axes. Squares don't intersect, but some of them can be inside others. In his turn a player can choose any square and paint it's internal area black. All squares inside the painted one are also painted black. The player can't paint the squares that were already painted. The loser is the player who can't make a turn. Determine the winner of the game if both players play optimally and Fat Tony's turn is the first. Also if Fat Tony can win the game determine which square he has to paint on his first turn in order to win. If there are many squares which guarantee victory to Fat Tony choose the one with the smallest number.

      Input

      The first line of input contains t - the number of test cases. Each test case starts with n - the number of squares. Next n lines consist of three integers each x, y, a - the coordinates of the lowest left corner of the square and the length of it's sides. The squares in the input are numbered from 1 to n in the order they are listed.

      Constraints

      1 <= t <= 10
      1 <= n <= 50000
      The total number of squares over all test cases in one file won't exceed 250000.
      x, y won't exceed 108 in absolute value.
      a will be positive and less than 108.

      Output

      For each test case print "Fat x", where x - is the number of square which needs to be painted on the first turn in order to win (if there are many such square chose the one with the smallest number), if Fat Tony wins or "Fit" if Fit Tony wins.

      Example

      Input:
      2
      5
      0 0 10
      15 15 1
      1 1 3
      5 5 1
      14 14 3
      2
      1 1 1
      3 3 1
      
      Output:
      Fat 2
      Fit
      
      

      Added by:Spooky
      Date:2011-03-27
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeChef March Challenge 2011









      SPOJ Problem Set (classical)

      8666. Maximum - Profit -- Version II

      Problem code: ITRIX_C

       

                      Everyone enjoyed BYTCDE11. So the “Maximum Profit ”problem is “

                      Chakra is a young and dynamic entrepreneur, who is developing rapidly as a successful hotelier. He owns the Quickbyte chain of restaurants, 'M' of which are fully functional now. He divides each day into 'M'  time slots. For each time slot 'j', in every restaurant 'i', there are Aij waiters and Bij customers. Being a quality conscious person, he wants each waiter to handle atmost one customer in a given time slot. Since he is really busy, in a day each restaurant is open only during one of the time slots. Since the hunger and demand for food varies during the day, the price which the  customer is willing to pay varies, and is given by Cij for a restaurant 'i' during a time slot 'j'.Given the values of Aij, Bij and Cij, find the maximum profit which Chakra can make in a day . “..

      Let’s add a constraint  “Only one restaurant  can be opened in a time slot  ”.Also the number of restaurants and number of time slots will be equal (‘M’).

       

      Input Format:

      The first line of input contains an integer 't', denoting the number of test cases.

      For each testcase, the first line contains an integer 'M'.

      Each of the next 'M' lines contains 'M’ integers. The jth integer on the ith line denotes the value of Aij.

      Each of the next 'M' lines contains 'M' integers. The jth integer on the ith line denotes the value of Bij

      Each of the next 'M' lines contains 'M' integers. The jth integer on the ith line denotes the value of Cij

      Output Format:

      For each test case output one value, denoting the maximum profit which Chakra can make in a day.

      Example

      Input:

      2

      2

      1 2

      3 2

      3 2

      1 2

      4 5

      3 1

      3

      1 1 1

      1 1 1

      1 1 1

      1 1 1

      1 1 1

      1 1 1

      1000 33 10

      75 1000 1000

      100 50 39

      Output:

      13

      2050

      Constraints:

      t <= 50

      1 <= M<= 15

      1 <= Aij, Bij <= 5000

      0 <= Cij <= 10^9


      Added by:Radhakrishnan
      Date:2011-03-27
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ITRIX 2011









      SPOJ Problem Set (classical)

      8667. Board-Queries

      Problem code: ITRIX_D

                          RishiKumar spends most of his time in solving Querying problems. When solving a 2D Querying problem he got exhausted and he needs the help of someone .yes he got!! .. Karthi  is in search of his girl and  asked Rishi whether he saw his girl on his way . Rishi replied he knew where she has gone but he will disclose the truth if Karthi solve this Bloody Querying problem. Help Karthi to solve this!!!!

      Given two 2D arrays X and Y  . Max size of X and Y is 500. (500 x 500)

      There are 3 Operations (Three Types of Queries)

      A)      0  x1 y1 x2 y2 ---Swaps the contents of the rectangle given by the points (x1,y1) and (x2,y2)  of X and Y

      B)       1 x1 y1 x2 y2 --- Print the sum of all elements in rectangle given by points (x1,y1)  and (x2,y2) of the array X.

      C)       2 x1 y1 x2 y2 -- - Print the sum of all elements in rectangle given by points (x1,y1)  and (x2,y2) of the array Y.

      (Points (x1,y1) and (x2,y2 ) inclusive)

      (x1,y1) –­Top Left point of the rectangle and(x2,y2) –Bottom right point of the rectangle

      Input Format:

              The first line of the input file contains N – Dimension of the array (It is clear that array is square array i.e. length=breadth) .The next N lines contains N integers per line separated by space which are the elements of array X .The next N lines contains N integers per line separated by space which are the elements of the array Y. The next line contains and integer Q –Total number of Queries  ..Then each of the following Q lines contains the Queries (as per the above operations) 

      Constraints: N <=500  , 0 <=Xij,Yij <=10^6

      Q<=100000 (10 power 5) 

      Array indexing start from [1, 1] to [N, N];

      Output Format:

               Print the result of each Query(There will be output  for query type B and Query Type C)  line by line.

      Sample Input:               

      5

      1 2 3 4 5

      6 7 8 9 0

      1 2 3 4 5

      6 7 8 9 0

      9 1 2 3 4

      1 1 1 1 1

      1 1 1 1 1

      1 1 1 1 1

      1 1 1 1 1

      1 1 1 1 1

      4

      1 1 1 4 4

      0 1 1 4 4

      1 1 1 4 4

      2 1 1 4 4

      Sample Output:

      80

      16

      80                                          

      Warning: Huge I/O, Make Your I/O  Fast


      Added by:Radhakrishnan
      Date:2011-03-27
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8668. THE BLACK AND WHITE QUEENS

      Problem code: ITRIX_E

       

                  Subru and Shanmu are playing Chess. Shanmu wonder about queens . So he asked Subru the following question

                      “How many ways are there to place a black and a white Queen on an M * N chessboard such that they do not attack each other? The queen can be moved any number of unoccupied squares in a straight line vertically, horizontally, or diagonally..

      Subru gave the answer in seconds for a given chess board of size M x N   (M<=N). Can you repeat the same with Your Code?

      Input Format:

      The first line contains the integer  “t” which indicates the number  of test cases. Each of the following t lines contains two integers M and N separated by spaces (M<=N).

      Output Format:

      Output for each case consists of one line: The number of ways of placing a black and a white queen on a M x N chess board such that they do not attack each other.

      Constraints: T<=10000 , 2<=M <=10^10 (10 power 10 )  ,2<=N<=10^10 (10 power 10). And M<=N .

      Sample Input:

      3

      5 5

      3 4

      2 2

      Sample Output:

      280

      40

      0


      Added by:Radhakrishnan
      Date:2011-03-27
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ITRIX 2011









      SPOJ Problem Set (classical)

      8670. THE MAX LINES

      Problem code: MAXLN

      In this problem you will be given a half-circle. The half-circle’s radius is r. You can take any point A on the half-circle and draw 2 lines from the point to the two sides of the diameter(AB and AC). Let the sum of square of one line’s length and the other line’s length is s.
                                

      Like in the figure s=AB^2+AC. And BC=2r.

      Now given r you have to find the maximum value of s. That is you have to find point A such that AB^2+AC is maximum.

      Input:
      First line of the test case will be the number of test case T(1<=T<=1000) . Then T lines follows. On each line you will find a integer number r(1<=r<=1000000); each representing the radius of the half-circle.

      Output:
      For each input line, print a line containing “Case I: ”, where I is the test case number and the maximum value of s. Print 2 digit after decimal(Errors should be less then .01).

      Sample Input:
      1
      1

      Sample Output:
      Case 1: 4.25



      Added by:Muhammad Ridowan
      Date:2011-03-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem(used for CSE,University of Dhaka, Newbies Contest)









      SPOJ Problem Set (classical)

      8720. Looks like Nim - but it is not

      Problem code: GAME2

      Goran and Stjepan play an interesting game. On the table between them, there is a sequence of N skyscrapers made of Lego bricks. All of them are made of equal bricks and each of them has a height, which equals the number of bricks in it.

      Goran plays first; then Stjepan, then Goran, then Stjepan and so on. In each move, a player has to find the highest skyscraper in the sequence (if there's more than one, he chooses any of them) and reduces its height - that is, takes away an arbitrary (positive) number of bricks from it.

      The winner of the game is the one who takes away the last brick. Equivalently, the loser of the game is the one who is not able to make a move.

      Help Goran and tell him in how many ways he can play his first move, so that he can certainly win (no matter how Stjepan played). If Goran doesn't have a winning strategy at all, the number of ways is zero.

      Input

      In the first line of input, there is an integer T ≤ 3, the number of test cases.

      Then follow T blocks, each of them in two lines:

      - N ≤ 300 000, the number of skyscrapers in the sequence

      - a sequence of N integers in the range [0, 106]

      Output

      For each of the T games, print the required number of ways.

      Example

      Input:
      

      3

      5

      0 1 0 1 0

      3

      0 7 0

      5

      1 0 1 0 1

      Output: 0
      1
      3

      Added by:Adrian Satja Kurdija
      Date:2011-04-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:idea of Goran Zuzic









      SPOJ Problem Set (classical)

      8725. Closest Point Pair

      Problem code: CLOPPAIR


      You are given N points on a plane and your task is to find a pair of points with the smallest euclidean distance between them.

      All points will be unique and there is only one pair with the smallest distance.

      Input

      First line of input will contain N (2<=N<=50000) and then N lines follow each line contains two integers giving the X and Y coordinate of the point. Absolute value of X,Y will be atmost 10^6.

      Output

      Output 3 numbers a b c, where a,b (a<b) are the indexes (0 based) of the point pair in the input and c is the distance between them. Round c to 6 decimal digits.

      See samples for more clarification.

       

      Input: 
      5
      0 0
      0 1
      100 45
      2 3
      9 9

      Output:

      0 1 1.000000
      Input: 
      5
      0 0
      -4 1
      -7 -2
      4 5
      1 1

      Output:

      0 4 1.414214

      Added by:SALVO
      Date:2011-04-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Standard Problem









      SPOJ Problem Set (classical)

      8728. Hierarchy

      Problem code: MAKETREE

      A group of graduated students decided to establish a company; however, they don't agree on who is going to be who's boss.

      Generally, one of the students will be the main boss, and each of the other students will have exactly one boss (and that boss, if he is not the main boss, will have a boss of his own too). Every boss will have a strictly greater salary than all of his subordinates - therefore, there are no cycles. Therefore, the hierarchy of the company can be represented as a rooted tree.

      In order to agree on who is going to be who's boss, they've chosen K most successful students, and each of them has given a statement: I want to be the superior of him, him, and him (they could be successful or unsuccessful). And what does it mean to be a superior? It means to be the boss, or to be one of the boss' superiors (therefore, a superior of a student is not necessary his direct boss).

      Help this immature company and create a hierarchy that will satisfy all of the successful students' wishes. A solution, not necessary unique, will exist in all of the test data.

      Input

      In the first line of input, read positive integers N (N ≤ 100 000), total number of students, and K (K < N), the number of successful students. All students are numbered 1..N, while the successful ones are numbered 1..K.

      Then follow K lines. In Ath of these lines, first read an integer W (the number of wishes of the student A, 1 ≤ W ≤ 10), and then W integers from the range [1, N] which denote students which student A wants to be superior to.

      Output

      Output N integers. The Ath of these integers should be 0 if student A is the main boss, and else it should represent the boss of the student A.

      Example

      Input:
      4 2
      1 3
      2 3 4
      Output:
      2
      0
      1
      2
      Input:
      
      7 4
      2 2 3
      1 6
      1 7
      2 1 2
      Output:
      4
      1
      1
      0
      4
      2
      3

      Added by:Adrian Satja Kurdija
      Date:2011-04-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8732. Best Fit

      Problem code: BFIT

      You are given a sequence of N random values (s1, s2, s3, s4, . . . . , sN)
      You have to find a function f(t) = a*t+b such that the Euclidean Distance between
      the given sequence and the function values where t varies from 1 to N is minimum.

      In effect, you have to minimize

      [math]\sqrt{\sum_{i=1}^{i=N}( a*i + b - s_{i})^{2} }[/math]

      Output the values a and b for each test case, rounded up to 4 decimal places.

      Input

      Line 1: T /* Number of test cases T <= 1000 */
      Line 2: N /* Number of values in first test case N <= 10000 */
      Line 3: s1 s2 s3 s4 … sN /* all values are less than 10000 and integers */
      .
      .
      .

      Output

      a b  /* Output the values a and b rounded up to 4 decimal places for each test case */

      Example

      Input:
      3
      3
      1 1 1
      3
      1 2 3
      3
      1 3 1 Output: 0.0000 1.0000
      1.0000 0.0000
      0.0000 1.6667

      Added by:Shashank Kumar
      Date:2011-04-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:INSOMNIA 11









      SPOJ Problem Set (classical)

      8734. Charlie and the Chocolate Factory

      Problem code: CHARLIE


      Charlie works in a magical chocolate factory. Packets of its marzipan are made on conveyor belts. To make marzipan perfect, M conveyor belts are used, and the process is as follows.

      Each of the M belts has N cells. Charlie first makes a few initial packets and puts them on the cells of the first belt (there may be zero or more packets in a particular cell).

      Then the first belt generates a second belt such that each cell of the second belt, at the same time, counts the packets in some five cells of the first belt and creates that number of packets in itself.

      Fox example, the first cell of the second belt sums the packets in the cells 1, 2, 3, 5, 9 of the first belt, the second cell of the second belt sums the packets in the cells 2, 3, 4, 5, 6 of the first belt and so on.

      Then, from the second belt, a third belt is generated in the same manner, then the fourth from the third and so on until the Mth. Since the number of packets on the belts usually increases, the number of packets in each cell is observed only modulo 10007.

      You, as the winner of the golden ticket to the factory, are able to see how the Mth belt looks like - that is, how many packets of marzipan there is in each cell. Charlie has also explained to you the production process and now you are wondering how first belt looked like.

      Input

      The first line of input contains positive integers N (N  100) and M (M 231).

      The next N lines describe the process of generating each new belt. In the Ath of these lines there are five distinct integers from the interval [1, N], denoting the cells of a previous belt from which the packets are added to the Ath cell of a new belt.

      The next line contains N integers describing the state of the Mth belt (modulo 10007).

      Output

      Print N integers describing the state of the first belt (modulo 10007). A unique solution will exist in all of the test data.

      Example

      Input:
      
      6 3
      1 2 3 4 5
      1 2 3 4 6
      1 2 3 5 6
      1 2 4 5 6
      1 3 4 5 6
      2 3 4 5 6
      13 12 12 12 14 12
      Output:
      1 0 0 0 2 0
      Explanation of the sample case: the process goes like this: 
      (1 0 0 0 2 0) - (3 1 3 3 3 2) - (13 12 12 12 14 12)

      Added by:Adrian Satja Kurdija
      Date:2011-04-17
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8735. Suffix Of Cube

      Problem code: CUBEND

      Given any string of decimal digits, ending in 1, 3, 7 or 9,  there is always a decimal
      number, which when cubed has a decimal expansion ending in the original given digit
      string. The number need never have more digits than the given digit string. 
       
      Write a program, which takes as input a string of decimal digits ending in 1, 3, 7 or 9
      and finds a number of at most the same number of digits, which when cubed, ends in
      the given digit string.

      Input

      The input begins with a line containing only the count of problem instances, nProb, as a
      decimal integer, 1 <= nProb <= 100.  This is followed by nProb lines, each of which
      contains a string of between 1 and 10 decimal digits ending in 1, 3, 7 or 9.

      Output

      For each problem instance, there should be one line of output consisting of the number,
      which when cubed, ends in the given digit string. The number should be output as a
      decimal integer with no leading spaces and no leading zeroes. 

      If there are many answers, the minimum should be chosen.

      Example

      Input:
      4 
      123
      1234567
      435621
      9876543213 Output: 947
      2835223
      786941
      2916344917

      Added by:Bống
      Date:2011-04-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8747. Substrings II

      Problem code: NSUBSTR2


      You are given a string T which consists of 40000 lowercase latin letters at most. You are also given some integers A, B and Q. You have to answer Q queries. For i-th query you are given a string Si and you need to output how many times Si appears in T. Immediately after answering the current query you need to add ((A*ans+B) modulo 26+1)-th lowercase symbol of the English alphabet to the end of T where ans is the answer to this query.

      Input

      The first line of input contains a string T. The next line consists of three integers Q (1<=Q<=40000), A (0<=A<=27) and B (0<=B<=26). The following Q lines contain Q query strings, Si-2 on i-th line. Input will not exceed 600 kb.

      Output

      Output Q lines. Output the answer to the i-th query on the i-th line output.

      Example

      Input:
      aaaaa
      2 0 0
      a
      aa

      Output:
      5
      5

      Added by:Tooru Ichii
      Date:2011-04-18
      Time limit:6.666s
      Source limit:44444B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Immagination









      SPOJ Problem Set ()

      8750. Wordplay

      Problem code: WORD

      Ivana made up a long word of N letters. Then she wrote down all K-letter-substrings of that word. For example, if the original word is BANANA and K=3, Ivana writes down the words BAN, ANA, NAN, ANA. The number of these words is, obviously, N-K+1.

      Ivana sorted these words in lexicographic order (in the given example, that would be ANA, ANA, BAN, NAN).

      But the sad thing happened: Ivana forgot the original word! Your task is to reconstruct it. A unique solution will exist in all of the test data.

      Constraints: 3 ≤ N ≤ 100 000, 2 ≤ K ≤ 15, K < N.

      Input

      [integers N, K]

      [N-K+1 words in lexicographic order, each consisting of capital English letters]

      Output

      [the required word]

      Example

      Input:
      
      6 3
      ANA
      ANA
      BAN
      NAN
      Output:
      BANANA

      Added by:Adrian Satja Kurdija
      Date:2011-04-19
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:own problem









      SPOJ Problem Set ()

      8756. Shake Shake Shaky

      Problem code: MAIN8_C

       

      Shaky has N (1<=N<=50000) candy boxes each of them contains a non-zero number of candies (between 1 and 1000000000). Shakey want to distibute these candies
      among his K (1<=K<=1000000000) IIIT-Delhi students. He want to distibute them in a way such that:

      Shaky has N (1<=N<=50000) candy boxes each of them contains a non-zero number of candies (between 1 and 1000000000). Shakey want to distibute these candies among his K (1<=K<=1000000000) IIIT-Delhi students. He want to distibute them in a way such that:

      1. All students get equal number of candies.

      2. All the candies which a student get must be from a single box only. 

      As he want to make all of them happy so he want to give as many candies as possible. Help Shaky in finding out what is the  maximum number of candies which a student can get.

      Input

      First line contains 1<=T<=20 the number of test cases. Then T test cases follow. First line of each test case contains N and K. Next line contains N integers, ith of which is the number of candies in ith box.

      Output

      For each test case print the required answer in a seperate line.

      Example

      Input:
      2
      3 2 
      3 1 4
      4 1
      3 2 3 9
      
      Output:
      3
      9

      Added by:Mahesh Chandra Sharma
      Date:2011-04-20
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for NSIT-IIITA Main contest #8









      SPOJ Problem Set (p0)

      8757. Coing tossing

      Problem code: MAIN8_D

       

      One day Rohil was getting very bored so he was tossing an unbiased coin randomly. He observed that certain patterns (a sequence of Head and Tail) appear very frequently 
      while some other are very rare. Being a programmer he decided to code a solution which takes a pattern string as input and tells what is 
      the expecetd number of times he will have to toss his coin to see that pattern. He wrote this program very quickly. Can you?

      One day Rohil was getting very bored so he was tossing an unbiased coin randomly. He observed that certain patterns (a sequence of Head and Tail) appear very frequently while some other are very rare. Being a programmer he decided to code a solution which takes a pattern string as input and tells what is the expected number of times he will have to toss his coin to see that pattern. He wrote this program very quickly. Can you?

      Input

      First line contains ( 1<=T<=25 ) the number of test cases. Each of following T lines contains a pattern string of 'H' and 'T' only. H is for Head and T is for Tail.

      |S| <= 40

      Output

      For each test case print the output in a new line (it is guaranteed that answer will always be an integer and fits in 64 bit type).

      Example

      Input:
      3
      H
      HTHT
      TTHTHTHTHTHHTHTHTHTTTTTTHTHHHHHTT
      
      Output:
      2
      20
      8589934598

      Added by:Mahesh Chandra Sharma
      Date:2011-04-20
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for NSIT-IIITA Main contest #8









      SPOJ Problem Set (classical)

      8758. Cover the string

      Problem code: MAIN8_E

       

      Given two strins A and B. You have to find the length of the smallest substring of A, such that B is the subsequence of this substing. 
      Formally speaking
      you have to find the lenght of smallest possible string S such that 
      S is the substring of A
      B is the subsequence S
      Note: Subsequence of an string S is obtained by deletnig some (possibly none) of the characters from it. for example "ah" is the subsequecne of "aohol"

      Given two strins A and B. You have to find the length of the smallest substring of A, such that B is the subsequence of this substing. 

      Formally speaking

      you have to find the lenght of smallest possible string S such that 

      S is the substring of A

      B is the subsequence S

      Note: Subsequence of an string S is obtained by deletnig some (possibly none) of the characters from it. for example "ah" is the subsequecne of "aohol"

      Input

      First line contains T, the number of test cases. Then T test cases follow, 2 lines for each test case, 1st contains A and 2nd contain B.

      |A|<=20000, |B|<=100

      Output

      For each test case print the answer in a new line. if no such substring exists print -1 instead.

      Example

      Input:
      2
      aaddddcckhssdd
      acs
      ghkkhllhjkhthkjjht
      hh
      
      Output:
      10
      3

      Added by:Mahesh Chandra Sharma
      Date:2011-04-20
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for NSIT-IIITA Main contest #8









      SPOJ Problem Set (classical)

      8759. Alpine Skiing

      Problem code: SKIING

      Believe it or not, the devices measuring time in alpine ski racing are not perfect. Instead of measuring the exact time, they measure an interval in which the ski racer finished the race (for example 53.42 sec - 53.45 sec).

      The probability is distributed evenly on this interval. (More precisely, if we choose any two sub-intervals of equal length, the probability that the ski racer finished the race in each of these sub-intervals is equal. One can also say that each moment in the given interval has equal probability assigned to it, but this in fact says nothing since the probability for each moment is equal to zero (since there are infinitely many moments in the interval) no matter how we distribute the probability.)

      And what if there are N ski racers? Then we have N intervals. Find the probability that the first ski racer on the list won the race (that is, finished the race with the minimal time).

      Input

      In the first line, there is an integer N (1 ≤ N ≤ 300).

      In the next N lines, read the intervals assigned to the ski racers: two real numbers Ai and Bi in each line, representing the interval [Ai, Bi] of the i-th ski racer. (0 < A< B< 1000)

      Output

      Print the required probability. The absolute difference between yours and official solution may be at most 10-6.

      Example

      input

      2
      1.000 5.000
      2.500 3.000
      

      output

      0.437500

      input
      4
      3.500 17.300
      12.700 21.200
      2.900 15.000
      1.000 20.000
      
      output
      0.263541

      Added by:Adrian Satja Kurdija
      Date:2011-04-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Frane Kurtoviæ









      SPOJ Problem Set (classical)

      8769. String distance

      Problem code: STRDIST2


      Prof.XYZ is an expert in sequence analysis. One such problem he works on is bar-coding DNA sequences. The problem at hand is, given two DNA sequences, find a way to compute their similarity efficiently. Formally a DNA sequence is a string (S) of length N where each character is from a set of symbols derived from a vocabulary ∑. We define the m-perturbed set of a string S to be  Δ(S,m) which contains the set of all strings S' obtained by changing atmost m characters of S with m<=N. In other words, Δ(S,m) is the set of all strings S' such that the hamming distance between S and S' (defined by H(S,S')) is atmost m. 

       

      Prof.XYZ defines an order (m1,m2) similarity between two N-length strings S1 and S2 to be the number of strings in the intersection of Δ(S1,m1) and Δ(S2,m2). It is easy to see that the number of strings in this intersection only depends on the hamming distance between S1 and S2 (rather than the entire original strings S1 and S2). In other words |Δ(S1,m1) ∩ Δ(S2,m2)| is only a function of N, the hamming distance H(S1,S2), m1, m2 and the alphabet size |∑|. Your objective is to write a program that counts the size of this intersection given  N, m1, m2, H(S1,S2) and  |∑|. Since the answer can be very large, output the answer modulo 1000000007.

      Input

      The first line of the input contains the number of test cases T (atmost 50). Each testcase consists of 5 integers in order

       (1) N : The length of each of the two strings. 1<=N<=1000

       (2) m1 : The allowed number of changes in the first string. 0<=m1 <= min(100,N/2)

       (3) m2 : The allowed number of changes in the second string. 0<=m2 <=min(100,N/2)

       (4) H(S1,S2): The hamming distance between the two strings. 0<=H <=min(100,N/2)

       (5) |∑| : The size of the vocabulary. 2<=|∑|<=1000000

      Output

      For each test-case output the required number of strings in the intersection modulo 1000000007 in a seperate line.

       

      Example

      Input:
      3
      6 1 2 2 2
      10 2 2 3 5
      20 3 4 5 7


      Output:
      3
      24
      1925

      Explanation (for the first test case)

      The length of each string is 6. We are allowed to perturb atmost one element from the first string and atmost two elements from the second. Since their hamming distance needs to be two, let S1=000000 be the first string and S2=000011 be the second. The set Δ(S1,1) is  {000000,000001,000010,000100,001000,010000,100000}. Without enumerating Δ(S2,2), we can see that the only set of strings in Δ(S1,1) that can be obtained by perturbing atmost two elements in S2 are {000000,000001,000010}. Thus |Δ(S1,m1) ∩ Δ(S2,m2)| =3.

       

      Added by:Balakrishnan
      Date:2011-04-26
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:The problem was stated in a technical talk.









      SPOJ Problem Set (main)

      8785. Cut the Silver Bar

      Problem code: SILVER

      A creditor wants a daily payment during n days from a poor miner in debt. Since the miner can not pay his daily obligation, he has negotiated with the creditor an alternative way, convenient for both parties, to pay his debt: the miner will give an equivalent of a 1µ (= 0.001mm) long piece of a silver bar as a guarantee towards the debt. The silver bar owned by the poor miner is initially nµ units long.

      By the end of n days the miner would not have any more silver to give and the creditor would have received an amount of silver equivalent to that of the silver bar initially owned by the miner. By then, the miner expected to have enough money to pay the debt at the next day so that he would have back all his silver.

      With this negotiation in mind, the miner has realized that it was not necessary to cut exactly 1µ silver piece from the bar everyday. For instance, at the third day he could give the creditor a 3µ silver piece, taking back the equivalent of a 2µ silver piece which the creditor should already have.

      Since cutting the bar was rather laborious and time consuming, the miner wanted to mini-mize the number of cuts he needed to perform on his silver bar in order to make the daily silver deposits during the n days. Could you help him?

      Input

      Input consists of several cases, each one defined by a line containing a positive integer number n (representing the length in micras of the silver bar and the number of days of the amortization period). You may assume that 0 < n < 20000. The end of the input is recognized by a line with 0.

      Output

      For each given case, output one line with a single number: the minimum number of cuts in which to cut a silver bar of length nµ to guarantee the debt during n days.

      Example

      Input:
      1
      5
      3
      0
      Output: 0
      2
      1

      Added by:John Mario
      Date:2011-04-29
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:XXIV Colombian Programming Contest ACIS REDIS 2010 - ACM ICPC









      SPOJ Problem Set ()

      8786. The Longest Chain of Domino Tiles

      Problem code: DOMINO1


      You are given N domino tiles. Each tile is made of some number of squares (not necessarily two), and each square is coloured either white or black (we use the Croatian letters: B for white and C for black).

      Find the longest chain that can be made of these tiles. Each tile can be used at most once and cannot be rotated (for example, BC cannot become CB). The chain is made by a common rule: in adjacent tiles, touching squares must be of the same colour.

      Input

      [N ≤ 100, the number of dominoes]

      in the next N lines:

      [a string of size between 1 and 100, representing the domino]

      Output

      The length of the longest chain.

      Example

      Input:
      
      4
      CB
      BCC
      BBCC
      BCBBC
      Output:
      11

      Added by:Adrian Satja Kurdija
      Date:2011-05-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      8791. Dynamic LCA

      Problem code: DYNALCA

       

      A forest of rooted trees initially consists of N (1 ≤ N ≤ 100,000) single-vertex trees. The vertices are numbered from 1 to N.

      You must process the following queries, where (1 ≤ A, B ≤ N) :

      • link A B : add an edge from vertex A to B, making A a child of B, where initially A is a root vertex, A and B are in different trees.
      • cut A : remove edge from A to its parent, where initially A is a non-root vertex.
      • lca A B : print the lowest common ancestor of A and B, where A and B are in the same tree.

      Input

      The first line of input contains the number of initial single-vertex trees N and the number of queries M (1 ≤ M ≤ 100,000). The following M lines contain queries.

      Output

      For each lca query output the lowest common ancestor (vertex number between 1 and N).

      Example

      Input:
      5 9
      lca 1 1
      link 1 2
      link 3 2
      link 4 3
      lca 1 4
      lca 3 4
      cut 4
      link 5 3
      lca 1 5

      Output:
      1
      2
      3
      2


      Added by:Andrey Naumenko
      Date:2011-05-02
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (main)

      8793. Separate Points

      Problem code: SPOINTS

      Numbers of black and white points are placed on a plane. Let’s imagine that a straight line of infinite length is drawn on the plane. When the line does not meet any of the points, the line divides these points into two groups. If the division by such a line results in one group consisting only of black points and the other consisting only of white points, we say that the
      line “separates black and white points”.

      Let’s see examples in the figure below. In the leftmost example, you can easily find that the black and white points can be perfectly separated by the dashed line according to their colors. In the remaining three examples, there exists no such straight line that gives such a separation.

      Example plane

      In this problem, given a set of points with their colors and positions, you are requested to decide whether there exists a straight line that separates black and white points.

      Input

      The input is a sequence of datasets, each of which is formatted as follows.

      n m
      x1 y1
      .
      .
      .
      xn yn
      xn+1 yn+1
      .
      .
      .
      xn+m yn+m

      The first line contains two positive integers separated by a single space; n is the number of black points, and m is the number of white points. They are less than or equal to 100. Then n + m lines representing the coordinates of points follow. Each line contains two integers xi and yi separated by a space, where (xi , yi) represents the x-coordinate and the y-coordinate of the i-th point. The color of the i-th point is black for 1 ≤ i ≤ n, and is white for n + 1 ≤ i ≤ n + m. All the points have integral x- and y-coordinate values between 0 and 10000 inclusive. You can also assume that no two points have the same position.
      The end of the input is indicated by a line containing two zeros separated by a space.

      Output

      For each dataset, output “YES” if there exists a line satisfying the condition. If not, output “NO”. In either case, print it in one line for each input dataset.

      Example

      Input:
      3 3 
      100 700
      200 200
      600 600
      500 100
      500 300
      800 500
      3 3
      100 300
      400 600
      400 100
      600 400
      500 900
      300 300
      3 4
      300 300
      500 300
      400 600
      100 100
      200 900
      500 900
      800 100
      1 2
      300 300
      100 100
      500 500
      1 1
      100 100 200 100
      2 2
      0 0
      500 700
      1000 1400
      1500 2100
      2 2
      0 0
      1000 1000
      1000 0
      0 1000
      3 3
      0 100
      4999 102
      10000 103
      5001 102
      10000 102
      0 101
      3 3
      100 100
      200 100
      100 200
      0 0
      400 0
      0 400
      3 3
      2813 1640
      2583 2892
      2967 1916
      541 3562
      9298 3686
      7443 7921
      0 0

      Output: YES
      NO
      NO
      NO
      YES
      YES
      NO
      NO
      NO
      YES

      Added by:John Mario
      Date:2011-05-03
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK NODEJS PYTH 3.2.3 n SED
      Resource:ACM International Collegiate Programming Contest Asia Regional Contest, Tokyo 2009









      SPOJ Problem Set (classical)

      8794. Swimming Jam

      Problem code: SWJAM


      Despite urging requests of the townspeople, the municipal office cannot afford to improve many of the apparently deficient city amenities under this recession. The city swimming pool is one of the typical examples. It has only two swimming lanes. The Municipal Fitness Agency, under this circumstances, settled usage rules so that the limited facilities can be utilized fully.
      Two lanes are to be used for one-way swimming of different directions. Swimmers are requested to start swimming in one of the lanes, from its one end to the other, and then change the lane to swim his/her way back. When he or she reaches the original starting end, he/she should return to his/her initial lane and starts swimming again.


      Each swimmer has his/her own natural constant pace. Swimmers, however, are not permitted to pass other swimmers except at the ends of the pool; as the lanes are not wide enough, that might cause accidents. If a swimmer is blocked by a slower swimmer, he/she has to follow the slower swimmer at the slower pace until the end of the lane is reached. Note that the blocking swimmer’s natural pace may be faster than the blocked swimmer; the blocking swimmer might also be blocked by another swimmer ahead, whose natural pace is slower than the blocked swimmer. Blocking would have taken place whether or not a faster swimmer was between them.

      Swimmers can change their order if they reach the end of the lane simultaneously. They change their order so that ones with faster natural pace swim in front. When a group of two or more swimmers formed by a congestion reaches the end of the lane, they are considered to reach there simultaneously, and thus change their order there. The number of swimmers, their natural paces in times to swim from one end to the other, and the numbers of laps they plan to swim are given. Note that here one “lap” means swimming from one end to the other and then swimming back to the original end. Your task is to calculate
      the time required for all the swimmers to finish their plans. All the swimmers start from the same end of the pool at the same time, the faster swimmers in front. In solving this problem, you can ignore the sizes of swimmers’ bodies, and also ignore the time required to change the lanes and the order in a group of swimmers at an end of the lanes.

      Input

      The input is a sequence of datasets. Each dataset is formatted as follows.

      n
      t1 c1
      . . .
      tn cn


      n is an integer (1 ≤ n ≤ 50) that represents the number of swimmers. ti and ci are integers (1 ≤ ti ≤ 300, 1 ≤ ci ≤ 250) that represent the natural pace in times to swim from one end to the other and the number of planned laps for the i-th swimmer, respectively. ti and ci are separated by a space.

      The end of the input is indicated by a line containing one zero.

      Output

      For each dataset, output the time required for all the swimmers to finish their plans in a line.

      No extra characters should occur in the output.

      Example

      Input:
      2 
      10 30
      15 20
      2
      10 240
      15 160
      3
      2 6
      7 2
      8 2
      4
      2 4
      7 2
      8 2
      18 1
      0 Output: 600
      4800
      36
      40

      Added by:John Mario
      Date:2011-05-03
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM International Collegiate Programming Contest Asia Regional Contest, Tokyo 2009









      SPOJ Problem Set (classical)

      8795. Twenty Questions

      Problem code: TWENTYQ

      Consider a closed world and a set of features that are defined for all the objects in the world. Each feature can be answered with “yes” or “no”. Using those features, we can identify any object from the rest of the ob jects in the world. In other words, each object can be represented as a fixed-length sequence of booleans. Any object is different from other objects by at least
      one feature.

      You would like to identify an object from others. For this purpose, you can ask a series of questions to someone who knows what the object is. Every question you can ask is about one of the features. He/she immediately answers each question with “yes” or “no” correctly. You can choose the next question after you get the answer to the previous question.

      You kindly pay the answerer 100 yen as a tip for each question. Because you don’t have surplus money, it is necessary to minimize the number of questions in the worst case. You don’t know what is the correct answer, but fortunately know all the ob jects in the world. Therefore, you can plan an optimal strategy before you start questioning.

      The problem you have to solve is: given a set of boolean-encoded objects, minimize the maximum number of questions by which every object in the set is identifiable.

      Input

      The input is a sequence of multiple datasets. Each dataset begins with a line which consists of two integers, m and n: the number of features, and the number of ob jects, respectively. You can assume 0 < m ≤ 11 and 0 < n ≤ 128. It is followed by n lines, each of which corresponds to an object. Each line includes a binary string of length m which represent the value (“yes” or “no”) of features. There are no two identical objects.

      The end of the input is indicated by a line containing two zeros. 

      Output

      For each dataset, minimize the maximum number of questions by which every object is identi-
      fiable and output the result.

      Example

      Input:
      8 1 
      11010101
      11 4
      00111001100
      01001101011
      01010000011
      01100110001
      11 16
      01000101111
      01011000000
      01011111001
      01101101001
      01110010111
      01110100111
      10000001010
      10010001000
      10010110100
      10100010100
      10101010110
      10110100010
      11001010011
      11011001001
      11111000111
      11111011101
      11 12
      10000000000
      01000000000
      00100000000
      00010000000
      00001000000
      00000100000
      00000010000
      00000001000
      00000000100
      00000000010
      00000000001
      00000000000
      9 32
      001000000
      000100000
      000010000
      000001000
      000000100
      000000010
      000000001
      000000000
      011000000
      010100000
      010010000
      010001000
      010000100
      010000010
      010000001
      010000000
      101000000
      100100000
      100010000
      100001000
      100000100
      100000010
      100000001
      100000000
      111000000
      110100000
      110010000
      110001000
      110000100
      110000010
      110000001
      110000000
      0 0

      Output:
      0
      2
      4
      11
      9

      Added by:John Mario
      Date:2011-05-03
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM International Collegiate Programming Contest Asia Regional Contest, Tokyo 2009









      SPOJ Problem Set (classical)

      8796. Cubist Artwork

      Problem code: CUBARTWK


      International Center for Picassonian Cubism is a Spanish national museum of cubist artworks, dedicated to Pablo Picasso. The center held a competition for an artwork that will be displayed at the facade of the museum building.

      The artwork is a collection of cubes that are piled up on the ground and is intended to amuse visitors, who will be curious how the shape of the collectionof cubes changes when it is seen from the front and the sides. The artwork is a collection of cubes with edges of 1 foot long and is built on a flat ground that is divided into a grid of unit squares, measuring 1 foot long on each side. Due to some technical reasons, cubes of the artwork must be either put on the ground, fitting into a unit square in the grid, or put on another cube in the way that the bottom face of the upper cube exactly meets the top face of the lower cube. No other way of putting cubes is possible.

      You are a member of the judging committee responsible for selecting one out of a plenty of artwork proposals ubmitted to the competition. The decision is made primarily based on artistic quality but the cost for installing the artwork is another important factor. Your task is to investigate the installation cost for each proposal. The cost is proportional to the number of cubes, so you have to figure out the minimum number of cubes needed for installation.

      Each design proposal of an artwork consists of the front view and the side view (the view seen from the right-hand side), as shown in Figure 1.

      Figure 1: An example of artwork proposal

      The front view (resp., the side view) indicates the maximum heights of piles of cubes for each column line (resp., row line) of the grid.

      There are several ways to install this proposal of artwork, such as follows.

       

      Explanation of Figure 1

       

      In these figures, the dotted lines on the ground indicate the grid lines. The left figure makes use of 16 cubes, which is not optimal. That is, the artwork can be installed with a fewer number of cubes. Actually, the right one is optimal and only uses 13 cubes.


      Notice that swapping columns of cubes does not change the side view. Similary, swapping rows does not change the front view. Thus, such swaps do not change the costs of building the artworks.

      For example, consider the artwork proposal given in Figure 2.

       

      Figure 2: Another example of artwork proposal

       

      An optimal installation of this proposal of artwork can be achieved with 13 cubes, as shown in the following figure, which can be obtained by exchanging the rightmost two columns of the optimal installation of the artwork of Figure 1.

       

      Explanation

      Input

       

      The input is a sequence of datasets. The end of the input is indicated by a line containing two
      zeros separated by a space. Each dataset is formatted as follows.


      w d
      h1 h2 ··· hw
      h′1 h′2 ··· h′d

      The integers w and d separated by a space are the numbers of columns and rows of the grid, respectively. You may assume 1 ≤ w ≤ 10 and 1≤ d ≤ 10. The integers separated by a space in the second and third lines specify the shape of the artwork. The integers hi (1≤ hi ≤ 20, 1≤ i w) in the second line give the front view, i.e., the maximum heights of cubes per each column line, ordered from left to right (seen from the front); The integers h′i (1≤ h′i ≤ 20, 1≤ i d) in the third line give the side view, i.e., the maximum heights of cubes per each row line, ordered from left to right (seen from the right-hand side).

      Output

      For each dataset, output a line containing the minimum number of cubes. The output should not contain any other extra characters.

      You can assume that for each dataset there is at least one way to install the artwork.

      Example

      Input:
      5 5
      1 2 3 4 5
      1 2 3 4 5
      5 5
      2 5 4 1 3
      4 1 5 3 2
      5 5
      1 2 3 4 5
      3 3 3 4 5
      3 3
      7 7 7
      7 7 7
      3 3
      4 4 4
      4 3 4
      4 3
      4 2 2 4
      4 2 1
      4 4
      2 8 8 8
      2 3 8 3
      10 10
      9 9 9 9 9 9 9 9 9 9
      9 9 9 9 9 9 9 9 9 9
      10 9
      20 1 20 20 20 20 20 18 20 20
      20 20 20 20 7 20 20 20 20
      0 0

      Output:
      15
      15
      21
      21
      15
      13
      32
      90
      186

      Added by:John Mario
      Date:2011-05-03
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM International Collegiate Programming Contest Asia Regional Contest, Tokyo 2009









      SPOJ Problem Set (classical)

      8816. Mravograd

      Problem code: MRAVOGRA

      The hard working ants have built a town called Ant Town. They modeled their town after Manhattan, with H horizontal and V vertical streets which cross in V×O intersections. As ants don't like water, with the first raindrops comes chaos in Ant Town. Town authorities have placed umbrellas under which any number of ants can hide, but only on N intersections.

      When the rain starts, each ant on an intersection starts running, using streets, to the nearest intersection with an umbrella. But, if an ant can choose from more than one such intersection, it panics and, not knowing where to go, stays on its starting intersection and gets wet. Town authorities use the name "wet intersections" for such starting intersections.

      For example, if Ant Town has 10 horizontal and 10 vertical streets, and if there are 4 intersections with umbrellas, then the question marks in the figure represent "wet intersections":

      Picture represents first example. We count streets from left to right from 1 to V and from down upwards from 1 to H.

      Write a program which, given the locations of intersections with umbrellas, determines the number of "wet intersections" in Ant Town.

      Input

      The first line contains two integers H and V (1 ≤ H, V ≤ 30 000), the numbers of horizontal and vertical streets in Ant Town.

      Horizontal streets are numbered 1 to H, vertical streets 1 to V.

      The second line contains an integer N (1 ≤ N ≤ 10), the number of intersections with umbrellas.

      Each of the following N lines contains two integer h and v, meaning that there is an umbrella on the crossing of horizontal street h and vertical street v. The locations of all umbrellas will be distinct.

      Output

      Output the number of "wet intersections" in Ant Town.

      Example

      Input: 
      10 10
      4
      4 4
      4 6
      6 4
      9 9

      Output:
      19


      Input:

      9 9
      3
      2 2
      5 5
      8 8

      Output:
      36


      Input:

      100 100
      2
      50 50
      50 51

      Output:
      0

      Added by:Stjepan Glavina
      Date:2011-05-05
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Croatian National 2007









      SPOJ Problem Set (classical)

      8820. Okret

      Problem code: OKRET


      There is a text consisting of N characters. At each step Mirko chooses two numbers A and B and then reverses the subsequence consisting of characters between indices A and B, inclusive. Indices are 1-based.

      Write a program that prints the final text after all operations are made.

      Input

      The first line of input contains the initial text of length N (1 ≤ N ≤ 2500000). It consists only of lowercase letters of the English alphabet.

      The second line contains integer M (1 ≤ M ≤ 2500), the number of steps.

      Each of the following M lines contain two integer A and B (1 ≤ A ≤ B ≤ N).

      Output

      In the first and only line output the final text.

      Example

      Input: 
      lukakuka
      3
      1 4
      5 8
      1 8

      Output:
      kukaluka


      Input:

      kukulelebodumepcele
      5
      3 7
      10 12
      2 10
      5 18
      5 15

      Output:
      kubeeludomepcelluke

      Added by:Stjepan Glavina
      Date:2011-05-06
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Croatian Student 2010









      SPOJ Problem Set ()

      8836. Yet Another Sequence Problem

      Problem code: SEQ7

      We have an infinite non-decreasing sequence A which is created as follows :

      • A[1] = 1 and A[2] = 2.
      • A number i occurs A[i] times in the sequence.

      First few terms in the sequence are: { 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7... }. Note that 3 occurs 2 times in the sequence, (because A[3] = 2).

      Your task is to find the term A[n] for any given n, where 0 < n <= 1e13.

      Input

      First line contains t, the number of testcases. Each of the next t lines contains a number n.

      Output

      For every case, print the nth term of the sequence.

      Example

      Input:
      2
      5
      12

       

      Output:
      3
      6


      Added by:Paranoid Android
      Date:2011-05-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8839. Longest Common Difference Subsequence

      Problem code: LCDS


      GIven two sequences of integers, your task is to find the longest common subsequence where every two adjacent values differ the same.

      For example, if the sequences are A = {1, 5, 8, 3} and B = {3, 10, 5}, then the common subsequence with adjacent values same are AL = {1, 8, 3} and BL = {3, 10, 5} since the differences in AL are 7 and -5 which is also the same in BL.

      Input

      First line of the input contains NA and NB, the sizes of the sequences A and B. Then follow two lines, the sequences A and B. (1 <= NA, NB <= 1000 and all values in the sequence will lie between -1e9 and 1e9).

      Output

      Print one line, the length of the LCDS as described above.

      Example

      Input:
      4 3
      1 5 8 3
      3 10 5

      Output:
      3

      Input:
      1 2
      5
      6 8

      Output:
      1


      Added by:Paranoid Android
      Date:2011-05-09
      Time limit:1s-40s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8841. Avaricious Maryanna

      Problem code: AVARY


      After Maryanna found the treasure buried by 27 pilots in a secret cave, she wanted to leave there immediately. Unfortunately, finding the door closed because of the overweight treasure she carried, she had to find out the password of the lock. She remembered someone had told her the password is an N-digit natural decimal integer (without extra leading zeroes), and the N least significant digits of any positive integral power of that integer is same as itself. She, being a smart girl, came up with all the possible answers within 1 minute. After a few times of tries, she escaped from that cave successfully. To show your intelligence you may solve the same task with your computer within only 10 seconds!

      Input

      The first line contains T (T <= 1000), the number of test cases. T lines follow, each contains a single positive integer N(N <= 500).

      Output

      For each test case, output a single line, which should begin with the case number counting from 1, followed by all the possible passwords sorted in increasing order. If no such passwords exist, output Impossible instead. See the sample for more format details.

      Example

      Input:
      2
      2
      1
      
      Output:
      Case #1: 25 76
      Case #2: 0 1 5 6
      

      Added by:[Trichromatic] XilinX
      Date:2011-05-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #2, by Blue Mary









      SPOJ Problem Set (classical)

      8842. Boring Homework

      Problem code: BWORK

      Professor Z. always gives his students lots of boring homework. Last week, after explaining binary search trees (BSTs), he asked his students to draw a picture of BST according to the list of numbers inserted into the tree sequentially. Maryanna spent so much time playing the game "Starcraft II" that she can't finish her homework in time. She needs your help.

       A binary search tree, which may sometimes also be called ordered or sorted binary tree, is a node-based binary tree data structure which has the following properties:

      The left subtree of a node contains only nodes with keys less than the node's key.

      The right subtree of a node contains only nodes with keys greater than the node's key.

      Both the left and right subtrees must also be binary search trees.

      --from Wikipedia 

      To draw a picture of BST, you may follow the rules listed below: 

      1. The picture of a 1-node BST, whose size is 1*1, is a single 'o' (15th small Latin letter).
      2. If a BST has a non-empty subtree, draw a single '|' just above the subtree's root, and a single '+' just above previous drawn '|'. Finally, in the row of '+', use the least number (including 0) of '-'s to connect '+' (denoting the left subtree and right subtree) and 'o' (denoting the parent node of the subtree)
      3. The left subtree (if exists) must be drawn on the left side of its parent. Similarly, the right subtree (if exists) must be drawn on the right side of its parent.
      4. The column of the BST's root must not contain any character from left subtree or right subtree.
      5. Any column containing any characters from BST's left subtree must not contain any characters from BST's right subtree, and vice versa. That is, for a node of the BST, the picture of its left subtree and the picture of its right subtree do not share common columns in the picture of the whole tree.

       The sample output may give a clear clarification about the format of the picture.

      Input

      The first line contains T (T <= 2500), the number of test cases. T lines follow. Each line contains a positive integer N (N < 80), followed by N integers - a permutation of 1 to N. The permutation indicates the insert order for the BST.

      Output

      For each test case:

      Output the case number counting from 1 in the first line. The next lines should be the image described above without any trailing spaces. See the sample for more format details.

      Notice that no trailing whitespaces after the last visible characters of each line are allowed.

      Example

      Input:
      3
      3 3 1 2
      6 4 5 6 1 3 2
      5 3 4 5 2 1
      
      Output:
      Case #1:
      +-o
      |
      o+
       |
       o
      Case #2:
      +--o+
      |   |
      o-+ o+
        |  |
       +o  o
       |
       o
      Case #3:
       +o+
       | |
      +o o+
      |   |
      o   o
      

      Added by:[Trichromatic] XilinX
      Date:2011-05-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #2, by Blue Mary









      SPOJ Problem Set (classical)

      8843. Complete the Set

      Problem code: COMPLETE


      Archaeologists have made a discovery on the Temple of Topology. The temple was once used as a place for ritual ceremony thousands of years ago. Among the relics that were unearthed, a scroll of parchment raised the interest of scientists. The parchment contained many numbers written in ancient symbols.

      By decrypting the words carved on a stone, scientists know that these numbers form an interesting set of integers satisfying the following two properties:

      1. Bitwise AND any number of integers from the set result in an integer in that set again.

      2. Bitwise OR any number of integers from the set result in an integer in that set again.

      As the parchment is extremely old, some part of it were broken and the numbers were lost. Now you job is to complete the original set from the remaining integers such that the size of the set is as small as possible.

      Input

      The input contains several test cases. The total number of test cases is less than 1100. Each test case begins with a line containing an integer n (n > 1). The following line contains n integers ai (0 <= ai < 216), the remaining integers on the parchment. The integers are distinct.

      Output

      For each test case, output one line containing a single integer, the minimal number of additional integers to make the set complete. If these numbers are already a complete set, print 0.

      Example

      Input:
      4
      5
      0 1 3 5 7
      2
      2 4
      3
      3 7 11
      3
      1 2 4
      
      Output:
      Case #1: 0
      Case #2: 2
      Case #3: 1
      Case #4: 5
      

      Added by:[Trichromatic] XilinX
      Date:2011-05-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #2, by cuiaoxiang









      SPOJ Problem Set (classical)

      8844. Detection of Extraterrestrial

      Problem code: DETECT


      E.T. Inc. employs Maryanna as alien signal researcher. To identify possible alien signals and background noise, she develops a method to evaluate the signals she has already received. The signal sent by E.T is more likely regularly alternative.

      Received signals can be presented by a string of small latin letters 'a' to 'z' whose length is N. For each X between 1 and N inclusive, she wants you to find out the maximum length of the substring which can be written as a concatenation of X same strings. For clarification, a substring is a consecutive part of the original string.

      Input

      The first line contains T, the number of test cases (T <= 200). Most of the test cases are relatively small. T lines follow, each contains a string of only small latin letters 'a' - 'z', whose length N is less than 1000, without any leading or trailing whitespaces.

      Output

      For each test case, output a single line, which should begin with the case number counting from 1, followed by N integers. The X-th (1-based) of them should be the maximum length of the substring which can be written as a concatenation of X same strings. If that substring doesn't exist, output 0 instead. See the sample for more format details.

      Example

      Input:
      2
      arisetocrat
      noonnoonnoon
      
      Output:
      Case #1: 11 0 0 0 0 0 0 0 0 0 0
      Case #2: 12 8 12 0 0 0 0 0 0 0 0 0
      

      Hint

      For the second sample, the longest substring which can be written as a concatenation of 2 same strings is "noonnoon", "oonnoonn", "onnoonno", "nnoonnoo", any of those has length 8; the longest substring which can be written as a concatenation of 3 same strings is the string itself. As a result, the second integer in the answer is 8 and the third integer in the answer is 12.


      Added by:[Trichromatic] XilinX
      Date:2011-05-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #2, By Blue Mary









      SPOJ Problem Set (classical)

      8845. Entertainment

      Problem code: TENNIS

      Maryanna and Lucyanna play tennis every Sunday afternoon since 10 years ago.

      A tennis match is determined through 5 sets. Typically the first player to win 3 sets wins the match. A set consists of games, and games, in turn, consist of points.

      A game consists of a sequence of points played with the same player serving. A game is won by the first player to have won at least four points in total and at least two points more than the opponent. The running score of each game is described in a manner peculiar to tennis: scores from zero to three points are described as "love", "fifteen", "thirty", and "forty" respectively. If at least three points have been scored by each player, and the scores are equal, the score is "deuce". If at least three points have been scored by each side and a player has one more point than his opponent, the score of the game is "advantage" for the player in the lead. During informal games, "advantage" can also be called "ad in" or "ad out", depending on whether the serving player or receiving player is ahead, respectively.

      A set consists of a sequence of games played with service alternating between games, ending when the count of games won meets certain criteria. Typically, a player wins a set by winning at least six games and at least two games more than the opponent.

      The first servers of two consecutive sets are different.

      Maryanna has found out when she is the server, her winning probability of this point is M%; otherwise, Y%. She wants to know her winning probability of the whole match if she serves first.

      Input

      The first line contains T (T <= 10000), the number of test cases. T lines follow. Each line contains two space-separated positive integers M, Y (0 < M, Y < 100).

      Output

      For each test case, output a single line, which should begin with the case number counting from 1, followed by Maryanna's winning percentage accurate to 4 decimal places. See the sample for more format details.

      Example

      Input:
      2
      50 50
      51 51
      
      Output: 
      Case #1: 50.0000%
      Case #2: 63.5654%
      

      Added by:[Trichromatic] XilinX
      Date:2011-05-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #2, by Blue Mary









      SPOJ Problem Set (classical)

      8846. Fudan Extracurricular Lives

      Problem code: MAHJONG

      Click here to get the PDF version of this problem. It seems that the style of this problem is the same as problem TRACTOR added by me about 2 years ago, but this one is far easier than that one. This problem is solved by a team at 286 minutes after the real-time contest start.


      Added by:[Trichromatic] XilinX
      Date:2011-05-10
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #2, by lcosvse









      SPOJ Problem Set (classical)

      8848. Herbicide

      Problem code: HERBICID

      Professor Z. has a courtyard beside his house. In the past, he loved to clean it and prune the flowers in his yard. However, with the JavaFF class taught by Professor Z. being offered, he indulged in assigning boring homework to the students and had no time for caring his yard.

      Consequently, weeds begin to grow up and then his yard becomes overgrown. In the last weekend, after Professor Z. assigned a mass of boring homework again, he suddenly brought his yard to mind. And after he saw the weedy ground, he decided to remove the weeds. But he did not have much time to deal with the garden’s problem because of the uncompleted plans of further boring homework in the next JavaFF class. 

      He sprayed herbicide on the ground optionally and, strangely, herbicide was sprayed as several simple polygons on the ground. In order to determine whether he should continue his work or not, Professor Z. needed to know how many weeds were covered by the herbicide.

      Notice that we assume that the weeds were not killed by the herbicide applied before. In the other words, a single weed can be counted several times in different polygon of herbicide. It seems that counting this number is quite a tough job. Then he asked Maryanna, one of his students in JavaFF class, for help. But Maryanna has no time because her boring homework had never been finished. Please help her!

      Input

      The very first line of input contains an integer T (T <= 100) indicating the number of test cases. The first line of each test case is an integer N (N <= 1000), which is the number of weeds in Professor Z's yard. In the following N lines, each line has a pair of integers (Xi, Yi) denoting the coordinate of a weed (-10000 <= Xi, Yi <= 10000). You can assume all the coordinates are unique. The next line is an integer M (M <= 1000) which denotes the number of polygons covered by herbicide, all these polygon's vertices are located on one of the N weeds, then M polygons descriptions are following. Each polygon Pi has two lines, the first line of ith polygon has an integer Si (3 <= Si <= N) denoting the number of vertices in this polygon. The following line contains Si integers, describing the vertices of this polygon in clockwise or counter-clockwise order. In detail, each integer in this line is an index of the coordinates of the N weeds listed before. Notice that the indexes start from 1. See the sample input for further details.

      Output

      For each test case, output M lines, each line has a single integer indicating the number of weeds covered by the corresponding polygon. If a weed lies on the edge of a polygon, then we consider such a weed as being covered.

      Example

      Input:
      1
      6
      1 1
      3 2
      2 3
      1 -1
      -1 -2
      -1 1
      3
      3 5 4 3
      3 1 5 6
      5 5 4 2 3 6
      
      Output:
      Case #1:
      4
      3
      6
      

      Added by:[Trichromatic] XilinX
      Date:2011-05-10
      Time limit:7s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Fudan University Local Contest #2, by lcosvse









      SPOJ Problem Set (classical)

      8849. Imitation

      Problem code: IMITATE

      Iris is a student of ethology studying the animal behavior. She is interested by the imitation behavior of animals. Imitation is an advanced behavior whereby an individual observes and replicates another’s.

      Iris is such a good researcher that she builds a mathematical model to describe the body figure of animals. She describes the body as a number of joints. And the figure or the status of animal body can be denoted as a set of ordered pairs of two different joints. To study the imitation of the animals, Iris defines the correlation of joints. She defines the correlation as the transitive closure of the ordered pairs of body status with its reflexive pairs eliminated. That is to say, the correlation is an anti-reflexive relation. In this case, we could say that one body status is imitating the other one when the correlations of both body statuses are the same.

      For example, for the joint set {J1, J2, J3}. The first body status contains the ordered pair (J1, J2), (J2, J3). And the second body status contains the ordered pair (J1, J2), (J2, J3), (J1, J3). We could say that the first body status is imitating the other one because both of the correlation sets are (J1, J2), (J2, J3), (J1, J3) since the definition of the correlation is the transitive closure of body status.

      For a given body status, that is, a given set of ordered pairs of joints, Iris want to get another body status, which is imitating the given one. At the same time, the desired body status must contain the minimum number of ordered pairs or the maximum number of ordered pairs. Your task is to calculate the minimum number and the maximum number.

      Input

      There are several test cases. The first line of the input contains a single integer denoting the number of test cases. There are about 100 test cases, but 90% of them are relatively small.

      For each test case, the first line contains two integers N and M where N is the number of joints of both the given body status and the desired body status, M is the number of ordered pairs of the given body status. (1 <= N <= 1000, 0 <= M <= 10000)

      Next M lines, each line denoting an ordered pair (Xi, Yi). The Xi and Yi are integers between 1 and N. Note that we consider the joints as the number between 1 and N.

      Output

      For each test case, output two integers denoting the minimum and maximum number of ordered pairs of the desired set. Two integers are separated by a single space.

      Example

      Input:
      3
      3 3
      1 2
      2 3
      1 3
      3 3
      1 2
      2 3
      3 1
      9 9
      1 2
      2 3
      3 1
      4 5
      5 6
      6 4
      7 8
      8 9
      9 7
      
      Output:
      Case #1: 2 3
      Case #2: 3 6
      Case #3: 9 18
      

      Hint

      In mathematics, the transitive closure of a binary relation R on a set X is the transitive relation R+ on set X such that R+ contains R and R+ is minimal. If the binary relation itself is transitive, then the transitive closure will be that same binary relation; otherwise, the transitive closure will be a different relation.

      A relation R on a set X is transitive if, for all x, y, z in X, whenever x R y and y R z then x R z. Examples of transitive relations include the equality relation on any set, the "less than or equal" relation on any linearly ordered set, and the relation "x was born before y" on the set of all people. Symbolically, this can be denoted as: if x < y and y < z then x < z.

      (From Wikipedia::transitive closure)


      Added by:[Trichromatic] XilinX
      Date:2011-05-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #2, by g201513









      SPOJ Problem Set (classical)

      8850. Juice Extractor

      Problem code: JUICE

      Jerry loses himself in the interesting game: Fruit Ninja. Fruit Ninja is a game of iPhone and iPad in which the players cut the fruits coming from the bottom of the screen and gain the bonus from cutting more than two fruits with a single slice. Once a fruit is cut, it breaks into small pieces and cannot be cut any more.

      After months of training, he becomes pro of this game. Actually, he can cut all the fruits on the screen at any time. Jerry also has a bad habit that he has no willing to leave some fruits for the future cutting. In the other words, after Jerry cuts the fruits, all the fruits on the screen breaks and no one left. That is why all his friends call him Juice Extractor.

      Now he only consider about the bonus, when he cuts more than two fruits, he can gain some bonus scores as same as the number of fruits he slice at that time. For example, if Jerry cuts 4 fruits with a single slice, he can get 4 scores from this slice.

      After Jerry gets the fruit schedule, he knows the appearing time and the disappearing time for every single fruit. He can only cut a fruit into pieces between its appearing time and disappearing time inclusive. He wants to know the maximum possible bonus scores he can receive.

      Input

      There are several test cases; the first line of the input contains a single integer T, denoting the number of the test cases. (T <= 200)

      For each test case, the first line contains an integer N, denoting the total number of fruits. (1 <= N <= 1000)

      The next N lines, each line describe a fruit. For each line, there are two integers Xi and Yi, where Xi is the appearing time of the fruit and Yi is the disappearing time of this fruit. (0 <= Xi <= Yi <= 1000000000)

      Output

      For each test case, output a single integer denoting the maximum scores that Jerry could possibly gain. See the sample for further details.

      Example

      Input:
      1
      10
      1 10
      2 11
      3 12
      4 13
      13 14
      14 15
      13 19
      20 22
      21 23
      22 24
      
      Output:
      Case #1: 10
      

      Added by:[Trichromatic] XilinX
      Date:2011-05-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #2, by g201513









      SPOJ Problem Set (classical)

      8869. Roti Prata

      Problem code: PRATA

      IEEE is having its AGM next week and the president wants to serve cheese prata after the meeting. The subcommittee members are asked to go to food connection and get P(P<=1000) pratas packed for the function. The stall has L cooks(L<=50) and each cook has a rank R(1<=R<=8). A cook with a rank R can cook 1 prata in the first R minutes 1 more prata in the next 2R minutes, 1 more prata in 3R minutes and so on(he can only cook a complete prata) ( For example if a cook is ranked 2.. he will cook one prata in 2 minutes one more prata in the next 4 mins an one more in the next 6 minutes hence in total 12 minutes he cooks 3 pratas in 13 minutes also he can cook only 3 pratas as he does not have enough time for the 4th prata). The webmaster wants to know the minimum time to get the order done. Please write a program to help him out.

       

      Input

      The first line tells the number of test cases. Each test case consist of 2 lines. In the first line of the test case we have P the number of prata ordered. In the next line the first integer denotes the number of cooks L and L integers follow in the same line each denoting the rank of a cook.

      Output

      Print an integer which tells the number of minutes needed to get the order done.

       

      Example

      Input:

      3
      10
      4 1 2 3 4
      8
      1 1
      8
      8 1 1 1 1 1 1 1 1
      Output:
      12
      36
      1

      Added by:Saransh Bansal
      Date:2011-05-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem- NTU IEEE codejam 2011









      SPOJ Problem Set (classical)

      8886. Guess number!

      Problem code: GNUM


      There was an application "Guess number!" in one of the popular social network recently. On each of the levels of this offered game it is necessary to define the secret number with some information provided.

      In particular, one of the most difficult levels consists in guessing the rational number x (0 < x < 1). It is known, that the result of multiplication of this number by natural number k is exactly one alteration: the i-th and j-th digits after a decimal point are exchanged by each other.

      As the number in front of decimal point isn't changed, the inequality 0 < kx < 1 is executed. Initially the numbers after a decimal point can be infinite.

      Your problem consists in writing the program which will define value x on numbers i, j, k.

      Input

      The first input line contains in one integer t (about 1000). Each of the following t  lines contains three numbers: i, j, k (1 ≤ i < j ≤ 1000; 2 ≤ k ≤ 109).

      Output

      If the required number exists, output consists in two integers — numerator and denominator of a non-reducible fraction setting required number. Otherwise output is "NO SOLUTION".

      Example

      Input:
      
      1
      1 4 13
      
      Output:
      
      2997 40000
      

      Added by:Ruslan Sennov
      Date:2011-05-15
      Time limit:5s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:RCC 2011









      SPOJ Problem Set (classical)

      8894. Double Time

      Problem code: DOUTI


       

      In 45 BC a standard calendar was adopted by Julius Caesar - each year would have 365 days, and every fourth year have an extra day - the 29th of February. However this calendar was not quite accurate enough to track the true solar year, and it became noticeable that the onset of the seasons was shifting steadily through the year. In 1582 Pope Gregory XIII ruled that a new style calendar should take effect. From then on, century years would only be leap years if they were divisible by 400. Furthermore the current year needed an adjustment to realign the calendar with the seasons. This new calendar, and the correction required, were adopted immediately by Roman Catholic countries, where the day following Thursday 4 October 1582 was Friday 15 October 1582. The British and Americans (among others) did not follow suit until 1752, when Wednesday 2 September was followed by Thursday 14 September. (Russia did not change until 1918, and Greece waited until 1923.) Thus there was a long period of time when history was recorded in two different styles.
      Write a program that will read in a date, determine which style it is in, and then convert it to the other style.
      Input will consist of a series of lines, each line containing a day and date (such as Friday 25 December 1992). Dates will be in the range 1 January 1600 to 31 December 2099, although converted dates may lie outside this range. Note that all names of days and months will be in the style shown, that is the first letter will be capitalised with the rest lower case. The file will be terminated by a line containing a single '#'.
      Output will consist of a series of lines, one for each line of the input. Each line will consist of a date in the other style. Use the format and spacing shown in the example and described above. Note that there must be exactly one space between each pair of fields. To distinguish between the styles, dates in the old style must have an asterisk ('*') immediately after the day of the month (with no intervening space). Note that this will not apply to the input.

       

      In 45 BC a standard calendar was adopted by Julius Caesar - each year would have 365 days, and every fourth year have an extra day - the 29th of February. However this calendar was not quite accurate enough to track the true solar year, and it became noticeable that the onset of the seasons was shifting steadily through the year. In 1582 Pope Gregory XIII ruled that a new style calendar should take effect. From then on, century years would only be leap years if they were divisible by 400. Furthermore the current year needed an adjustment to realign the calendar with the seasons. This new calendar, and the correction required, were adopted immediately by Roman Catholic countries, where the day following Thursday 4 October 1582 was Friday 15 October 1582. The British and Americans (among others) did not follow suit until 1752, when Wednesday 2 September was followed by Thursday 14 September. (Russia did not change until 1918, and Greece waited until 1923.) Thus there was a long period of time when history was recorded in two different styles.
      Write a program that will read in a date, determine which style it is in, and then convert it to the other style.

       

       

      Input

      Input will consist of a series of lines, each line containing a day and date (such as Friday 25 December 1992). Dates will be in the range 1 January 1600 to 31 December 2099, although converted dates may lie outside this range. Note that all names of days and months will be in the style shown, that is the first letter will be capitalised with the rest lower case. The file will be terminated by a line containing a single '#'.

      Output

      Output will consist of a series of lines, one for each line of the input. Each line will consist of a date in the other style. Use the format and spacing shown in the example and described above. Note that there must be exactly one space between each pair of fields. To distinguish between the styles, dates in the old style must have an asterisk ('*') immediately after the day of the month (with no intervening space). Note that this will not apply to the input.

      Example

      Input:
      
      Saturday 29 August 1992
      Saturday 16 August 1992
      Wednesday 19 December 1991
      Monday 1 January 1900
      #
      Output:
      Saturday 16* August 1992
      Saturday 29 August 1992
      Wednesday 1 January 1992
      Monday 20* December 1899

      Added by:Andres Tellez
      Date:2011-05-17
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8895. Power Crisis

      Problem code: POCRI

       

      During the power crisis in New Zealand this winter (caused by a shortage of rain and hence low levels in the hydro dams), a contingency scheme was developed to turn off the power to areas of the country in a systematic, totally fair, manner. The country was divided up into N regions (Auckland was region number 1, and Wellington number 13). A number, m, would be picked 'at random', and the power would first be turned off in region 1 (clearly the fairest starting point) and then in every m'th region after that, wrapping around to 1 after N, and ignoring regions already turned off. For example, if N = 17 and m = 5, power would be turned off to the regions in the order:1,6,11,16,5,12,2,9,17,10,4,15,14,3,8,13,7.
      The problem is that it is clearly fairest to turn off Wellington last (after all, that is where the Electricity headquarters are), so for a given N, the 'random' number m needs to be carefully chosen so that region 13 is the last region selected.
      Write a program that will read in the number of regions and then determine the smallest number m that will ensure that Wellington (region 13) can function while the rest of the country is blacked out.

       

      During the power crisis in New Zealand this winter (caused by a shortage of rain and hence low levels in the hydro dams), a contingency scheme was developed to turn off the power to areas of the country in a systematic, totally fair, manner. The country was divided up into N regions (Auckland was region number 1, and Wellington number 13). A number, m, would be picked 'at random', and the power would first be turned off in region 1 (clearly the fairest starting point) and then in every m'th region after that, wrapping around to 1 after N, and ignoring regions already turned off. For example, if N = 17 and m = 5, power would be turned off to the regions in the order:1,6,11,16,5,12,2,9,17,10,4,15,14,3,8,13,7.
      The problem is that it is clearly fairest to turn off Wellington last (after all, that is where the Electricity headquarters are), so for a given N, the 'random' number m needs to be carefully chosen so that region 13 is the last region selected.
      Write a program that will read in the number of regions and then determine the smallest number m that will ensure that Wellington (region 13) can function while the rest of the country is blacked out.

       

       

       

      Input

      Input will consist of a series of lines, each line containing the number of regions (N) with 13 <= N < 100. The file will be terminated by a line consisting of a single 0.

      Output

      Output will consist of a series of lines, one for each line of the input. Each line will consist of the number m according to the above scheme.

       

      Example

      Input:
      17
      0
      
      Output:
      7

      Added by:Andres Tellez
      Date:2011-05-17
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8896. Pattern Matching

      Problem code: PATT

       

      A regular expression is a string which contains some normal characters and some meta characters.
      The meta characters include,
      . means any character
      [c1 − c2]means any character between c1 and c2 (c1 and c2 are two characters)
      [ ˆ c1 − c2] means any character not between c1 and c2 (c1 and c2 are two characters)
       means the character before it can occur any times
      + means the character before it can occur any times but at least one times
      \ means any character follow should be treated as normal character
      You are to write a program to find the leftmost substring of a given string, so that the substring
      can match a given regular expression. If there are many substrings of the given string can match
      the regular expression, and the left positions of these substrings are same, we prefer the longest
      one.

       

      A regular expression is a string which contains some normal characters and some meta characters.
      The meta characters include,
      . means any character
      [c1 − c2]means any character between c1 and c2 (c1 and c2 are two characters)
      [ ˆ c1 − c2] means any character not between c1 and c2 (c1 and c2 are two characters)
       means the character before it can occur any times
      + means the character before it can occur any times but at least one times
      \ means any character follow should be treated as normal character
      You are to write a program to find the leftmost substring of a given string, so that the substring can match a given regular expression. If there are many substrings of the given string can match the regular expression, and the left positions of these substrings are same, we prefer the longest one.

      Input

      Every two lines of the input is a pattern-matching problem. The first line is a regular expression, and the second line is the string to be matched. Any line will be no more than 80 character. A line with only an eEvery two lines of the input is a pattern-matching problem. The first line is a regular expression, and the second line is the string to be matched. Any line will be no more than 80 character. A line with only an end will terminate the input.nd will terminate the input.

      Output

       

      For each matching problem, you should give an answer in one line. This line contains the string to be matched, but the leftmost substring that can match the regular expression should be bracketed. If no substring matches the regular expression, print the input string.

       

       

      Example

      Input:
      
      .*
      asdf
      f.*d.
      sefdfsde
      [0-9]+
      asd345dsf
      [^\*-\*]
      **asdf**fasd
      b[a-z]*r[s-u]*
      abcdefghijklmnopqrstuvwxyz
      [T-F]
      dfkgjf
      end
      Output:
      (asdf)
      se(fdfsde)
      asd(345)dsf
      **(a)sdf**fasd
      a(bcdefghijklmnopqrstu)vwxyz
      dfkgjf
      
      
      
      
      
      Added by:Andres Tellez
      Date:2011-05-17
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set ()

      8910. Probablistic OR

      Problem code: PROBOR

      Everyone knows OR operation. Let us define new operation which we will call Probablistic OR. We will denote this operation as #. For given real number p (0 <= p <= 1) and two bits a and b:

      • if a = 1 and b = 1, then #(a, b) = 1;
      • if a = 0 and b = 0, then #(a, b) = 0;
      • else #(a, b) = 0 with probability p, #(a, b) = 1 with probability 1-p.

      Now for two given non-negative integers x and y we can define bitwise Probablistic OR operation. The result of this operation is a number received by performing # operation for each pair of bits of x and y in same positions. For example, for p= 0.5, x = 2, and y = 4, we will get 0, 2, 4 or 6 each with probability 0.25. You will be given a list of non-negative integers. You have to implement a program which will calculate the expected value of the result of performing bitwise probablistic OR operation on all these numbers given some p. The numbers will be taken from left to right.

      Input

      Input file starts with real number p (0 <= p <= 1) with exactly two digits after the decimal point. Integer n follows (1 <= n <= 100). Next line contains n numbers ai in the order they are taking pert in the operation (0 <= ai <= 109).

      Output

      Output the expected value of performing Probablistic OR operation on the given numbers for given p. Print the result with two digits after the decimal point.

      Example

      Input:
      0.25 4
      1 2 3 4
      
      Output:
      5.11
      
      

      Added by:Spooky
      Date:2011-05-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Open All-Ukrainian Collegiate Contest Semi-Final, 2011









      SPOJ Problem Set (classical)

      8916. Villages by the River

      Problem code: VILLAGES


      In a far away country there is a wide river, N villages on the left and N villages on the right side of this river (denoted by 1..N on each side). There are also M small ships, each of them connecting one village from the left and one village from the right side (in both ways).

      You are to organize a film festival in four of these villages: two from the left and two from the right side. Each two of these four villages must be connected by a ship (directly) if they belong to opposite sides of the river.

      Help yourself to choose these four villages and first find out; in how many ways can you choose them?

      Input

      In the first line there are integers N ≤ 1000 and M ≤ N2.

      In the next M lines there are two integers from the interval [1, N] representing the village from the left and the village from the right side connected by this ship.

      Output

      Print the required number of ways to choose villages for the festival.

      Example

      Input:
      3 5
      1 1
      1 2
      1 3
      2 2
      2 3
      Output: 1

      (the only possibility is to choose the villages 1, 2 from the left and 2, 3 from the right side)

      Added by:Adrian Satja Kurdija
      Date:2011-05-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Croatian junior team selection test 2011









      SPOJ Problem Set (classical)

      8917. How Many Plusses

      Problem code: PLUSEVI


      Mirko is a strange boy so he has written down a square matrix full of ones and zeroes. Now he is interested in how many plusses there are in his matrix.

      A plus is a square such that its side has an odd length greater than 1 and all of its cells are zero, except for the middle row and the middle column: they must be full of ones. For example, in the matrix below there are two plusses, one inside the other:

      00100
      00100
      11111
      00100
      00100

      Input

      In the first line there is an integer N ≤ 2000, dimenzion of the square matrix.

      The next N lines are the rows of the matrix.

      Output

      Print the number of plusses appearing in the matrix.

      Example

      Input:
      8
      00010000
      00010000
      00010000
      11111111
      00010000
      00010010
      00010111
      00010010


      Output: 3

      Added by:Adrian Satja Kurdija
      Date:2011-05-21
      Time limit:1s-6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Croatian junior team selection test 2011









      SPOJ Problem Set (classical)

      8930. Party!

      Problem code: PAAAARTY

      Kate is preparing a party. She have bought a very strange garland for it. The garland is a closed chain of bulb. Each bulb can be in one of the following states: N - don't glow, R - glow red, G - glow green, B - glow blue. Each second the state of each bulb changes according to the following table:

       
      NRGB
      NNRGB
      RRNBG
      GGBNR
      BBGRN

      where row is chosen by the current state of the bulb and column is chosen by the state of the bulb on the right. The value at the intersection of the chosen row and column gives the new state of the bulb. For example, if the bulb glows red (R) and the bulb on its right glows green (G) then in the next second the bulb will glow blue (B). And if the bulb and its right neighbour both glow blue then the bulb won't glow at all in the next second. Also all the bulbs change their states simultaneously. Such behaviour should (theoretically) lead to constant twinkling of the garland. Unfortunately it turns out that sometimes eventually the garland goes into such a state that all bulb don't glow. So the garland stops twinkling. Kate is rather worried that this can spoil the party. She is going to set the initial states of each bulb as she like. Help her determine for how long the garland will twinkle starting from this initial state.

      Input

      The input file consists of a single string containing characters 'N', 'R', 'G' and 'B', which describes the initial state of the garland. Each character defines the initial state of some bulb. The bulbs are listed from left to right. There is the first bulb on the right of the last one. The length of the string will be no more than 1234567 characters.

      Output

      Print the number of seconds during which the garland will twinkle. If the garland won't stop twinkling (at least until the power is turned off) print "Party!" (quotes for clarity).

      Example

      Input:
      RGBG
      
      Output:
      4
      
      

      Explanation

      The garland will change the state in such a way:

      RGBG
      BRRB
      GNGN
      GGGG
      NNNN
      

      Added by:Spooky
      Date:2011-05-22
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Open All-Ukrainian Collegiate Contest Semi-Final, 2011









      SPOJ Problem Set (classical)

      8945. Grid points (speed variation)

      Problem code: GRIDPNTS


      There's a Cartesian lattice with 0<=x,y<=n. Given one point (x1, y1>0) in this lattice rotating clockwise as little as possible around the origin find the next point (x2, y2). The given and searched points mustn't have another point between the origin (0, 0) and this point itself.
      x1, y1, x2, y2 are non-negative integers.

      Graphic for GridPnt

      Input

      In the first line the number T (T<10000) of test cases.
      Then T lines with the space-separated n (1<=n<=1000000), x1 and y1.

      Output

      For each test case the space-separated x2 and y2.

      Example

      Input:
      3
      1 1 1
      5 3 2
      100 97 98 Output: 1 0
      5 3
      98 99

      Added by:HWK
      Date:2011-05-24
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8951. brownie

      Problem code: XIXO


      Bessie has baked a rectangular brownie that can be thought of as
      an RxC grid (1 <= R <= 500; 1 <= C <= 500) of little brownie squares.
      The square at row i, column j contains N_ij (0 <= N_ij <= 4,000)
      chocolate chips.
      
      Bessie wants to partition the brownie up into A*B chunks (1 <= A
      <= R; 1 <= B <= C): one for each of the A*B cows. The brownie is
      cut by first making A-1 horizontal cuts (always along integer
      coordinates) to divide the brownie into A strips.  Then cut each
      strip *independently* with B-1 vertical cuts, also on integer
      boundaries. The other A*B-1 cows then each choose a brownie piece,
      leaving the last chunk for Bessie. Being greedy, they leave Bessie
      the brownie that has the least number of chocolate chips on it.
      
      Determine the maximum number of chocolate chips Bessie can receive,
      assuming she cuts the brownies optimally.
      
      As an example, consider a 5 row x 4 column brownie with chips
      distributed like this:
      
               1 2 2 1
               3 1 1 1
               2 0 1 3
               1 1 1 1
               1 1 1 1
      
      Bessie must partition the brownie into 4 horizontal strips, each
      with two pieces. Bessie can cut the brownie like this:
      
             1 2 | 2 1
             ---------
             3 | 1 1 1
             ---------
             2 0 1 | 3
             ---------
             1 1 | 1 1
             1 1 | 1 1
      
      Thus, when the other greedy cows take their brownie piece, Bessie
      still gets 3 chocolate chips.
      
      
      Input
      5 4 4 2
      1 2 2 1
      3 1 1 1
      2 0 1 3
      1 1 1 1
      1 1 1 1
      

      Output

      3


      probm was added from USACO.

      Added by:სვანიძე
      Date:2011-05-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: BASH C99 strict
      Resource:...









      SPOJ Problem Set (classical)

      8952. Catapult that ball

      Problem code: THRBL

      Bob has unusual problem. In Byteland we can find a lot of hills and cities. King of Byteland ordered Bob to deliver magic balls from one city to another. Unfortunately, Bob has to deliver many magic balls, so walking with them would take too much time for him. Bob came up with great idea - catapulting them.

      Byteland is divided into intervals. Each interval contains city and hill.

      Bob can catapult magic ball accurately from city A to city B, if between them there isn't higher hill than A's hill.

      Input

      Every test case contains N and M (N<=50000) (M<=50000), number of intervals and number of balls.

      In next line there's N numbers H(H<=10^9) separated by one space.

      In next M lines numbers A and B (1<=A,B<=N), number of city from which we want to catapult the ball and number of city to which we want to catapult the ball.

      Output

      Write one number - number of magic balls that Bob can catapult successfully.

      Example

      Input:
      7 3
      2 3 5 4 2 1 6
      3 5
      2 5
      4 6

      Output:
      2

      Bob can catapult ball number 1 and 3.

      Added by:Krzysztof Lewko
      Date:2011-05-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8980. Cost

      Problem code: KOICOST

      You are given an undirected graph with N verticies and M edges, where the weights are unique. 

      There is a function Cost(u,v), which is defined as follows:

      While there is a path between vertex u and v, delete the edge with the smallest weight. Cost(u,v) is the sum of the weights of the edges that were deleted in this process.

      graph

      For example, from the graph above (same as the sample input), Cost(2,6) is 2+3+4+5+6 = 20.

      Given an undirected graph, your task is to calculate the sum of Cost(u,v) for all vertices u and v, where u<v. Since the answer can get large, output the answer modulo 10^9.

      Input

      The first line of the input consists of two integers, N and M. (1<=N<=100,000, 0<=M<=100,000)

      The next M lines consists of three integers, u, v, and w. This means that there is an edge between vertex u and v with weight w. (1<=u,v<=N, 1<=w<=100,000)

      Output

      Output the sum specified in the problem statement.

      Example

      Input:
      6 7
      1 2 10
      2 3 2
      4 3 5
      6 3 15
      3 5 4
      4 5 3
      2 6 6

      Output: 256

      Added by:Joon Young Seo
      Date:2011-06-01
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:2011 KOI Regional









      SPOJ Problem Set (classical)

      8982. Representatives

      Problem code: KOIREP


      There are N classes in a school, each with M students. There is going to be a race of 100m dash, and a representative from each class will be chosen to participate in this race. You were assigned a task to choose these representatives. Since you did not want the race to be one sided, you wanted to choose the representatives such that the difference between the ability of the best representative and the worst representative is minimal.

      For example, if N = 3 and M = 4, and each class has students with following abilities:

      Class 1: {12,16,67,43}

      Class 2: {7,17,68,48}

      Class 3: {14,15,77,54}

      it is best to choose the student with ability 16 from Class 1, 17 from Class 2, and 15 from Class 3. Thus, the difference in this case would be 17-15 = 2.

      Your task is to calculate the minimal possible difference you can achieve by choosing a representative from each class.

      Input

      The first line of the input consists of two integers, N and M. (1<=N<=1000, 1<=M<=1000).

      The next N lines will have M integers. The jth element of ith line is the ability of the jth student in ith class. The number is between 0 and 10^9, inclusive.

      Output

      Output the minimal difference one can achieve by choosing the representative from each class.

      Example

      Input:
      3 4
      12 16 67 43
      7 17 68 48
      14 15 77 54

      Output: 2
      Input:
      4 3
      10 20 30
      40 50 60
      70 80 90
      100 110 120




      Output:
      70



      Added by:Joon Young Seo
      Date:2011-06-01
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:2011 KOI regional









      SPOJ Problem Set (classical)

      8985. Line up

      Problem code: KOILINE

      N people are lined up in a straight line to enter a concert. Each person in this line knows how many people in front have shorter or same heights. Let's call the sequence representing these numbers S. So in other words, S[i] means that there are S[i] people in front of the ith person who have shorter or same heights than that of person i. 

      Given the heights of N people and a sequence S, determine the correct order of people lined up. (left is front)   

      Input

      The first line of the input is an integer N. (1<=N<=100,000)

      The next N lines each consists of one integer H. (1<=H<=2*10^9) These N integers are the heights of people lined up.

      Then, sequence S is given in a single line, separated by a space.  

      Output

      Determine the correct ordering of people lined up. Total of N lines should be output. The integer on the ith line represents the height of the ith person in the line. 

      Example

      Input:
      12
      120
      167
      163
      172
      145
      134
      182
      155
      167
      120
      119
      156
      0 1 0 0 3 2 6 7 4 6 9 4
      Output: 134
      167
      120
      119
      156
      120
      167
      182
      155
      163
      172
      145

      Added by:Joon Young Seo
      Date:2011-06-02
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:2011 KOI Regional









      SPOJ Problem Set ()

      8989. Funny programming contest

      Problem code: FUPRCO


      Bob is trying to solve many problems.

      Today he's trying to do his best at "Funny programming contest". In this contest there is N rounds.

      Each round is starting in moment Ai and ends in moment Bi. Rounds can overlap on each other. For each round there is one problem to solve. He can't solve more than one problem at once.

      Bob knows that problems are very difficult, so he assumed that he will do each round for more than half of time the round lasts.

      He knows start and end time for each round.

      Help him figuring out if he can spend as much time as he want for each round.

      Input
      First line contains number N(1<=N<=2*10^5)

      In next N lines there are three numbers, ai,bi,ci (0<=ai<bi<=10^9 , (bi-ai)/2 < ci <= bi-ai ), time when round i starts, time when round i end, and time which Bob wants to spend for round i.

      Output

      Print "YES" if Bob can spend as much time as he wants for each round, otherwise print "NO"
      Example

      Input:

      2
      1 5 3
      1 2 1


      Output:
      YES

      Input:

      2
      1 5 3
      2 3 1


      Output:
      NO


      Added by:Krzysztof Lewko
      Date:2011-06-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://oboz.ilo.pl/ http://main.edu.pl/pl/archive/proserwy









      SPOJ Problem Set (classical)

      8991. Number Guessing Game 2

      Problem code: GUESSLNK


      I really enjoy setting problem GUESSING. After three years, I decided to set another "kind of interactive" problem based on it.

      Given a link for GUESSING problem, find the server's response

      Specification

      The script runs on server works like this, the URL contains 12 digits, first 6 digits represents SEED generated by random number generator, and it won't change during a guessing session. The last 6 digits represents GUESS, which is the number user just typed.

      The unknown part (for you, of course) is an integer function f which is a bijection from [0,999999] to [0,999999].

      The server first generate TARGET = f(SEED), then it compares TARGET and GUESS and give response back to user.

      for more details on f, it's in format (expr(x) % 1000000), and expr (x) is a expression contains only operation add, subtract, multiply, division, modulo, each exactly once, and every constants are in [0,999999], every variable is x(of course), brackets are allowed.

      for example, expr(x) could be "x/12-34%(x+1)*56", but it's invalid since f is not a bijection.

      the modulo/division operations here works well if left side is a negative number, for example, -2 % 5 = 3, -2 / 5 = -1. but it's undefined if the number on the right side is not positive.

      Input

      each line contains a link in format "http://www.spoj.pl/problems/GUESSING/XXXXXXYYYYYY/", where XXXXXXYYYYYY contains exactly 12 digit.

      Output

      The server's response, in format "XAYB".

      Example

      Input:
      http://www.spoj.pl/problems/GUESSING/123456123456/
      http://www.spoj.pl/problems/GUESSING/000000000000/
      
      Output:
      1A3B
      1A5B
      

      Added by:Bin Jin
      Date:2011-06-06
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      8992. A los saltos

      Problem code: SALTOS

      (the english version is following the spanish version at each section, and is in green letters)

      Una secuencia de k números enteros positivos , (k > 1), es saltarina, si los valores absolutos de las diferencias entre elementos sucesivos toman todos los valores posibles desde 1 hasta k-1.

      Por ejemplo: la secuencia 51423, es una secuencia saltarina de longitud 5, porque las diferencias entre los elementos sucesivos de la secuencia son: 4,3,2,1

      Se desea conocer cuántas secuencias saltarinas hay de longitud L.

      En este problema consideramos que las secuencias están formadas únicamente por valores en 1..k.

      A sequence of k > 1 integers is called a jolly jumper if the absolute values of the difference between successive elements take on all the values 1 through k-1. For instance,

      the sequence 51423 is a jolly jumper of lenght 5, because the differences between consecutive elements are 4,3,2,1

      You must to find out how many jolly jumpers are with lenght = L.

      (in this problem we only consider the jolly jumpers built with values only in the 1..k range).

       

      Input

      Cada línea de la entrada consta de un entero k, (> 1). Cada línea es un caso diferente para informar. La entrada termina con una línea conteniendo el valor 0, el cual no se procesa.

      Each line of the input have an integer k, (> 1). Each line is a different case to process. The input ends with a line that contains the value 0 (this value is the end of data signal and won't be processed).

      Output

      Por cada línea de la entrada, se debe generar una línea de salida que informa la cantidad de secuencias saltarinas de longitud igual a k.

      Your program must to generate one output line for each input line. At each output line you must inform the quantity of jolly jumpers with length equal to k.

      Sample Input

      2

      3

      4

      0


       

      Sample Output

      2

      4

      4



       


      Added by:Coach UTN FRSF
      Date:2011-06-06
      Time limit:1s-22s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://uva.onlinejudge.org/external/100/10038.html









      SPOJ Problem Set (classical)

      8995. CANDY

      Problem code: LQDCANDY


      John had a chocolate bar with the size of 2^i. At his birthday party, he shared this chocolate bar to his friend. But his friend just wanted to taste a piece of this chocolate bar which had the length of N (1<=N<=10^18) so that John had to break this chocolate bar into pieces to get the piece for his friend.Unfortunately, this chocolate bar was so breakable that John just can break it into half each time.
      Help him find the smallest length of the chocolate bar that he needs and the minimum times of breaking the chocolate bar to get the piece for his friend.

      Input

      T - the number of test cases
      In each of the next T lines, there is one numbers N

      Output

      For every test case, print one line the length of the chocolate bar and the minimum number of times to break the bar.

      Example

      Input:
      3
      8
      5
      7 Output: 8 0
      8 3
      8 3

      Added by:tmb
      Date:2011-06-07
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI









      SPOJ Problem Set (classical)

      9000. Bob and his new kite factory

      Problem code: KITEPRBL

      Bob, owner of kite factory decided to make some good money.

      He has bought new machine to produce kites, but this machine doesn't have any software in it ! He was very sad, oh, so very sad. Every kite is produced from big square sheet of paper.

      He didn't want to spend next big sum of money hiring programmists, so he decided to ask you for help.

      He wants his machine to :

      -cut exactly as much color paper as needed to cover kite and then cover it immidiately

      -make N very little small holes in the kite ( through which he can put colorful bows and other shiny things )

      -at the end he wants his machine to sort convex shape kites and non-convex shapes kites ( he thinks that convex shape kites should be transported to "Biedronka" - shop for poor people, so he doesn't want to mix them with really expensive ones )

      Input

      In first line there is number T, number of test cases.

      In first line of each test case there is number X(X<200), number of verticles of the each kite.

      Then X pairs of number, xi and yi, coords of each verticle.

      Left-bottomst corner of paper have (0,0) coords.

      In next line number N(N<20000), number of holes to make in the kite.

      Then N number, xi and yi, coords of each hole to make in the kite.

      Obviously, hole cannot be made on the perimeter of kite.

      We can assume that no three points are colinear, also there is no point duplicate. Bob always would give you verticles of kite in clockwise order.

      Output

      For each test case print area ( 10^-3 precision ) of paper which was used to produce each kite, holes which were made successfully, and digit 1 if kite is convex shape, otherwise digit 0. Separate each test case with new line

      Example

      Input:
      1
      6
      0 0
      5 0
      4 2
      5 4
      0 4
      1 2
      3
      1 1
      1 2
      5 2

      Output:
      32.000 1 0

      Explaination: 32.000 area of paper to cover the kite. Only 1st hole can be made successfully (2nd is on parimeter, 3rd is out the kite)
      Kite has non-convex shape

      Added by:Krzysztof Lewko
      Date:2011-06-09
      Time limit:0.5s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set ()

      9012. Maximum Self-Matching

      Problem code: MAXMATCH

      You're given a string s consisting of letters 'a', 'b' and 'c'.

      The matching function ms( i ) is defined as the number of matching characters of s and its i-shift. In other words, ms( i ) is the number of characters that are matched when you align the 0-th character of s with the i-th character of its copy.

      You are asked to compute the maximum of ms( i ) for all i ( 1 <= i <= |s| ). To make it a bit harder, you should also output all the optimal i's in increasing order.

      Input

      The first and only line of input contains the string s. 2 <= |s| <= 105.

      Output

      The first line of output contains the maximal ms( i ) over all i.

      The second line of output contains all the i's for which ms( i ) reaches maximum.

      Example

      Input:
      caccacaa
      
      Output:
      4
      3

      Explanation:

      caccacaa
      caccacaa


      The bold characters indicate the ones that match when shift = 3.


      Added by:Gustav Matula
      Date:2011-06-10
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      9030. Bob and his towers

      Problem code: KVALTWR

      Bytie has got a set of wooden blocks for his birthday. The blocks are indistinguishable from one another, as they are all cubes of the same size. Bytie forms piles by putting one block atop another. Soon he had a whole rank of such piles, one next to another in a straight line. Of course, the piles can have different heights.

      Bytie's father, Byteasar, gave his son a puzzle. He gave him a number and asked to rearrange the blocks in such a way that the number of successive piles of height at least is maximised. However, Bytie is only ever allowed to pick the top block from a pile strictly higher than and place it atop one of the piles next to it. Further, Bytie is not allowed to form new piles, he can only move blocks between those already existing.

      Input

      In the first line of the standard input there are two integers separated by a single space: (), denoting the number of piles, and (), denoting the number of Byteasar's requests. The piles are numbered from to . In the second line there are integers separated by single spaces (). The number denotes the height of the -th pile. The third line holds integers separated by single spaces (). These are the subsequent values of the parameter for which the puzzle is to be solved. That is, the largest number of successive piles of height at least that can be obtained by allowed moves is to be determined for each given value of the parameter .

      Output

      Your program should print out integers, separated by single spaces, to the standard output - the -th of which should be the answer to the puzzle for the given initial piles set-up and the parameter .

      Example

      For the input data:

      5 6
      1 2 1 1 5
      1 2 3 4 5 6

      the correct result is:

      5 5 2 1 1 0


      Added by:Krzysztof Lewko
      Date:2011-06-14
      Time limit:1s-25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:XVII POI









      SPOJ Problem Set (classical)

      9032. Cube Free Numbers

      Problem code: CUBEFR

       

      A cube free number is a number who’s none of the divisor is a cube number( A cube number is a cube of a integer like 8(2*2*2) , 27(3*3*3) ). So cube free numbers are 1,2,3,4,5,6,7,9,10,11,12,13,14,15,17,18 etc(we will consider 1 as cube free). 8,16,24,27,32 etc are not cube free number. So the position of 1 among the cube free numbers is 1, position of 2 is 2, 3 is 3 and position of 10 is 9. Given a positive number you have to say if its a cube free number and if yes then tell its position among cube free numbers.

      Input:

      First line of the test case will be the number of test case T(1<=T<=100000) . Then T lines follows. On each line you will find a integer number n(1<=n<=1000000).

      Output:

      For each input line, print a line containing “Case I: ”, where I is the test case number. Then if it is not a cube free number then print “Not Cube Free”. Otherwise print its position among the cube free numbers.

      Sample Input:

      10

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      Sample Output:

      Case 1: 1

      Case 2: 2

      Case 3: 3

      Case 4: 4

      Case 5: 5

      Case 6: 6

      Case 7: 7

      Case 8: Not Cube Free

      Case 9: 8

      Case 10: 9

       

       


      Added by:Muhammad Ridowan
      Date:2011-06-14
      Time limit:0s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own. For alternate thanks Sayef Azad Sakin









      SPOJ Problem Set (classical)

      9034. Help Tohu

      Problem code: TOHU


      Tohu wants to enter Moscow State Univercity, and he must pass the math exam. He does not know math, and asks you to help him. The problem is to find the sum [math] S_n = a_1 + a_2 + \ldots + a_n [/math] of the sequence [math] \left{ a_n \right} [/math] on condition [math] \forall k \in \mathbb{N} : a_1 + 2a_2 + \ldots + ka_k = \frac{k+1}{k+2} [/math]

      Input

      First line contains single integer T<=20000 - the number of test cases.

      Each of the next T lines contains single integer 1 <= n <= 10^9.

      Output

      For each n output the value [math] S_n [/math] with 11 digits after decimal point.

      Example

      Input:
      2
      2
      5
      Output: 0.70833333333
      0.73809523810

      Added by:Ефиме
      Date:2011-06-15
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9038. Chessboard Billiard

      Problem code: BISHOP2

      Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.

      More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.

      It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.

      You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size.

      Input

      The first line of input contains two integers n and m (2 ≤ n, m ≤ 1016).

      Output

      Print a single line for each input line containing a single number, the maximum possible number of billiard balls that do not pairwise beat each other.

      Example

      Input:
      3 4
      2 2
      5 5

      Output:

      2
      2
      5

      ID RESULT TIME
      code...



      Added by:Bidhan Roy ( বিধান )
      Date:2011-06-15
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: F# FORT HASK PYTH 2.7 PYTH 3.2.3
      Resource:Codeforces Beta Round









      SPOJ Problem Set (classical)

      9040. Tug of War

      Problem code: TUG


      We want to pick a certain number of people from a group of N people and make them play a game of tug of war!

      Then, we would like to split these people into two teams.

      Afterwards, an intense game of tug of war would start.

      However, when the strength of each team is not equivalent, the game is not very fun. A team's strength is the sum of the strengths of the people in the team.

      Since you want the game that is fun, it is necessary to determine if it is possible to pick some people and split them into two teams such that the two teams' strengths are equal.

      Input

      The input consists of a number of test cases.

      The first line is the number of test case, T. (1<=T<=200)

      Each case starts with N (1<=N<=100,000), the total number of people.

      The next line consists of N integers, separated by a space. The ith integer indicates the strength of the ith person. These integers are less than 100, but larger than 0. 

      Output

      For each test case, output "YES" if it is possible to pick some people from the group and separate into two teams of equal strengths. If not, output "NO". Refer to the sample test cases for further clarifications.

      Example

      Input:
      2
      4
      10 20 30 40
      3
      10 18 15


      Output: YES
      NO
      There are a number of ways to pick teams for the first test case. One example would be {10,20} and {30}.

      Added by:Joon Young Seo
      Date:2011-06-16
      Time limit:1s-20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      9042. HQNP Incomputable

      Problem code: HQNP

      HQ9+ is an esoteric programming language specialized for certain tasks. For example, printing “Hello,world!” or writing a quine (a program that prints itself) couldn’t be any simpler. Unfortunately, HQ9+ doesn’t do very well in most other situations. This is why we have created our own variant of the language,HQ0-9+−INCOMPUTABLE?!.A HQ0-9+−INCOMPUTABLE?! program is a sequence of commands, written on one line without any whitespace (except for the trailing newline). The program can store data in two memory areas: the buffer, a string of characters, and the accumulator, an integer variable. Initially, the buffer is empty and the accumulator is set to 0. The value of the buffer after executing all the commands becomes the program’s output.

         
                    HQ0-9+−INCOMPUTABLE?! supports the following commands:
      commanddescription
      hH

      appends helloworld to the buffer

      qQ

      appends the program source code to the buffer (not including the trailing newline)

      0-9

      replaces the buffer with copies of its old value – for example, ‘2’ doubles the buffer

      +

      increments the accumulator

      -

      decrements the accumulator

      iI

      increments the ASCII value of every character in the buffer

      nN

      applies ROT13 to the letters and numbers in the buffer (for letters ROT13 preserves case; for digits we define ROT13(d) = (+ 13) mod 10)

      cC

      swaps the case of every letter in the buffer; doesn’t change other characters

      oO

      removes all characters from the buffer such that their index, counted from the end, is a prime or a power of two (or both); the last character has index 1 (which is a power of 2)

      mM

      sets the accumulator to the current buffer length

      pP

      removes all characters from the buffer such that their index is a prime or a power of two (or both); the first character has index 1 (which is a power of 2)

      uU

      converts the buffer to uppercase

      tT

      sorts the characters in the buffer by their ASCII values

      aA

      replaces every character in the buffer with its ASCII value in decimal (1–3 digits)

      bB

      replaces every character in the buffer with its ASCII value in binary (exactly eight ‘0’/‘1’ characters)

      lL

      converts the buffer to lowercase

      eE

      translates every character in the buffer to l33t using the following table: 
      ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 
      48(03=6#|JXLM~09Q257UVW%Y2 a6<d3f9hijk1m^0p9r57uvw*y2 O!ZEA$G/B9

      ?

      removes 47 characters from the end of the buffer (or everything if it is too short)

      !

      removes 47 characters from the beginning of the buffer (or everything if it is too short)

      command  description
               appends helloworld to the buffer
          h, H
               appends the program source code to the buffer (not including the trailing newline)
          q, Q
               replaces the buffer with n copies of its old value – for example, ‘2’ doubles the buffer
          0-9
               increments the accumulator
             +
               decrements the accumulator
             -
               increments the ASCII value of every character in the buffer
          i, I
               applies ROT13 to the letters and numbers in the buffer (for letters ROT13 preserves
          n, N
               case; for digits we define ROT13(d) = (d + 13) mod 10)
               swaps the case of every letter in the buffer; doesn’t change other characters
          c, C
               removes all characters from the buffer such that their index, counted from the end, is a
          o, O
               prime or a power of two (or both); the last character has index 1 (which is a power of 2)
               sets the accumulator to the current buffer length
          m, M
               removes all characters from the buffer such that their index is a prime or a power of two
          p, P
               (or both); the first character has index 1 (which is a power of 2)
               converts the buffer to uppercase
          u, U
               sorts the characters in the buffer by their ASCII values
          t, T
               replaces every character in the buffer with its ASCII value in decimal (1–3 digits)
          a, A
               replaces every character in the buffer with its ASCII value in binary (exactly eight ‘0’/‘1’
          b, B
               characters)
               converts the buffer to lowercase
          l, L
               translates every character in the buffer to l33t using the following table:
          e, E
               ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789
               48(03=6#|JXLM~09Q257UVW%Y2 a6<d3f9hijk1m^0p9r57uvw*y2 O!ZEA$G/B9
               removes 47 characters from the end of the buffer (or everything if it is too short)
             ?
               removes 47 characters from the beginning of the buffer (or everything if it is too short)
             !

      In this task you have to print the HQ0-9+−INCOMPUTABLE?! program that will give the number n as output.

      Limits

      Any HQ0-9+−INCOMPUTABLE?! program( output for each case ) must be at most 10 000 commands long. The accumulator is unbounded (it can store an arbitrarily large integer). After each command, the buffer must be at most 10 000 characters long. To prevent code injection vulnerabilities, during the execution of your program( output for each case ) the buffer must never contain non-alphanumeric characters, i.e. characters other than A-Z, a-z, and 0-9. If it happens, your solution will be judged as wrong.

       

         Input

      First line has integer T i.e number of test cases. ( T <= 100 ). Next T lines has a number n. ( 0 <= n <= 10^100 )

       

         Output

      For each n, output the required HQ0-9+−INCOMPUTABLE?! program which will give n as output. If there are multiple solutions, output any one of them. Output of each test case must be in a single line.

                                                                           

         Example

      Input:

      3

      0

      321

      4124144

      Output:

      Find yourself :)

       

      Following are some HQ0-9+−INCOMPUTABLE?! programs and their corresponding outputs:

      h5!  rld
      QCq  qcQQCq
      q23  q23q23q23q23q23q23
      h?h  helloworld
      H2O  hlwolheo
      h4op  ollwldwlhe
      hint  ccfkrsvzzz
      q18N  d41Ad41Ad41Ad41Ad41Ad41Ad41Ad41A
      3QAh  518165104helloworld
      Qb  0101000101100010
      opaque  094QU3
      h1Qt  1Qdehhllloortw
      H9999 
       (error: buffer size exceeded 10 000)
      quine  (error: buffer contains “|”)
      LMAO

       (empty output)

       


      Added by:XeRoN!X
      Date:2011-06-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Variation of IPSC Problem









      SPOJ Problem Set (main)

      9046. Clock Hands

      Problem code: HANDS

      The minute hand and hour hand love each other. The ‘Second’ hand is a spy who wants to keep track on how many times they pass over each other in a given interval on a day. Help the second hand.

      Input

      First line contains the number of test cases t. Each test case has two lines representing the start time and end time respectively. The time would be in format (hh:mm). hh will be between 00 and 23, mm will be between 00 and 59. If the minute and hour hand are overlapping right at the start time (like at 12:00) then it would not be counted. (00:00 <= 'start time' < 'end time' <= 23:59)

      Output

      For each test case print, on a separate line, the number of times they overlap each other.

      Example

      Input

      5

      00:00
      03:00

      00:00
      00:10

      06:00
      12:00

      11:59
      12:01

      00:00
      12:00

      Output

      2
      0
      6
      1
      11


      Added by:Nikunj Jain
      Date:2011-06-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set ()

      9050. Tohu again

      Problem code: TOHU2


       

      Tohu was very tired during the preparation for entrance exams at
      MSU and Ksjuchi decided to joke on him (of course to cheer).
      She said him that she is magican and she can read his thoughts
      To prove that she's prepeared some tables of characters where 
      every character have an unique number more than 0 but less than 100.
      She shows one of tables to him and asked to make a two-digit integer, 
      subtract from this number the sum of its digits and concentrate on 
      symbol with this number from the table.
      Then she calls the character of which he thinks.
      Magic, is not it? =)
      But Ksjuchi is preparing for the exam in philosophy now, and while she was drowing these tables noxious Socrates mixed up some of the cells.
      Now Ksjuchi need to know what tables she can use to surprise Tohu. Help her.

      Tohu was very tired during the preparation for entrance exams at Moscow State University and Ksjuchi decided to joke on him (of course to cheer). She said him that she is magican and she can read his thoughts. To prove that she's prepeared some tables of characters where every character have an unique number more than 0 but less than 100. She shows one of tables to him and asked to make a two-digit integer, subtract from this number the sum of its digits and concentrate on symbol with this number from the table.

      Then she calls the character of which he thinks.

      Magic, is not it? =)

      But Ksjuchi is preparing for the exam in philosophy now, and while she was drowing these tables noxious Socrates mixed up some of the cells. Now Ksjuchi need to know what tables she can use to surprise Tohu. Help her

      Input

      First line : number of tests T<=1000

      Test:

      99 lines where every have a type:

      i ch where i = 1..99 included and "ch" - 'a'..'z' or 'A'..'Z'

       

      Output

       

      Print YES if Ksjuchi might uniquely define symbol that Tohu put forth.

      Otherwise print NO

       

      Example

      Input:
      1
      1 k
      2 q
      3 J
      4 Q
      5 P
      6 R
      7 e
      8 G
      9 L
      10 c
      11 g
      12 T
      13 w
      14 v
      15 p
      16 P
      17 X
      18 X
      19 p
      20 I
      21 X
      22 z
      23 L
      24 u
      25 K
      26 F
      27 t
      28 H
      29 Q
      30 r
      31 V
      32 e
      33 F
      34 V
      35 D
      36 u
      37 c
      38 n
      39 z
      40 w
      41 Z
      42 K
      43 Y
      44 j
      45 Y
      46 M
      47 u
      48 U
      49 H
      50 i
      51 n
      52 S
      53 k
      54 q
      55 W
      56 o
      57 L
      58 J
      59 O
      60 S
      61 Z
      62 G
      63 m
      64 T
      65 P
      66 k
      67 i
      68 b
      69 J
      70 a
      71 E
      72 g
      73 O
      74 P
      75 M
      76 s
      77 M
      78 A
      79 O
      80 P
      81 g
      82 h
      83 V
      84 U
      85 M
      86 G
      87 Y
      88 u
      89 D
      90 F
      91 h
      92 q
      93 h
      94 a
      95 l
      96 P
      97 d
      98 T
      99 w
      
      Output:
      NO
        

      Hint: Ksjuchi is not a magican. Really.

       

       


      Added by:Egor
      Date:2011-06-19
      Time limit:1s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:own problem









      SPOJ Problem Set (classical)

      9055. Most Frequent Value

      Problem code: FREQ2


      You are given a sequence of n integers a0, a1, ..., an-1. You are also given several queries consisting of indices i and j (0 ≤ i ≤ j ≤ n-1). For each query, determine the number of occurrences of the most frequent value among the integers ai, ..., aj.

      Input

      First line contains two integers n and q (1 ≤ n, q ≤ 100000). The next line contains n integers a0, ... ,an-1 (0 ≤ ai ≤ 100000, for each i ∈ {0, ..., n-1}) separated by spaces. The following q lines contain one query each, consisting of two integers i and j (0 ≤ i ≤ j ≤ n-1), which indicates the boundary indices for the query.

      Output

      For each query, print one line with one integer: The number of occurrences of the most frequent value within the given range.

      Example

      Input:

      5 3
      1 2 1 3 3
      0 2
      1 2
      0 4 Output:
      2
      1
      2

      NOTE - This problem is similar to a problem Frequent values.

      Added by:Dominik Gleich
      Date:2011-06-20
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:My own problem.









      SPOJ Problem Set (classical)

      9066. Sum of Distinct Numbers

      Problem code: XXXXXXXX

      You are given N numbers. You have to perform two kinds of operations:
      U x y - x-th number becomes equal to y.
      Q x y - calculate the sum of distinct numbers from x-th to y-th. It means that the sum for the set {1, 2, 3, 2, 7} will be equal to 13 (1+2+3+7).

      Input

      The first line of input contains an integer N. 1<=N<=50000
      The second line consists of N numbers.
      The third line consists of an integer Q. 1<=Q<=100000
      The following Q lines will consist of queries of the form described in the task description.
      All numbers in input will fit in the signed 32-bit type.

      Output

      Output an answer for every query of the second type.

      Example

      Input:
      5
      1 2 4 2 3                                                                              
      3
      Q 2 4
      U 4 7
      Q 2 4

      Output:
      6
      13

      Hint: Time limit is ~ 1.5*(my program's execution time in the worst case)


      Added by:Tooru Ichii
      Date:2011-06-23
      Time limit:6.666s
      Source limit:44444B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Known problem









      SPOJ Problem Set (classical)

      9070. Lightning Conductor

      Problem code: LIGHTIN

      Progressive climate change has forced the Byteburg authorities to build a huge lightning conductor that would protect all the buildings within the city. These buildings form a row along a single street, and are numbered from to .

      The heights of the buildings and the lightning conductor are non-negative integers. Byteburg's limited funds allow construction of only a single lightning conductor. Moreover, as you would expect, the higher it will be, the more expensive.

      The lightning conductor of height located on the roof of the building (of height ) protects the building (of height ) if the following inequality holds:

      where denotes the absolute value of the difference between and .

      Byteasar, the mayor of Byteburg, asks your help. Write a program that, for every building , determines the minimum height of a lightning conductor that would protect all the buildings if it were put on top of the building .

      Input

      In the first line of the standard input there is a single integer () that denotes the number of buildings in Byteburg. Each of the following lines holds a single integer () that denotes the height of the -th building.

      Output

      Your program should print out exactly lines to the standard output. The -th line should give a non-negative integer denoting the minimum height of the lightning conductor on the -th building.

      Example

      For the input data:

      6
      5
      3
      2
      4
      2
      4

      the correct result is:

      2
      3
      5
      3
      5
      4

      Added by:Krzysztof Lewko
      Date:2011-06-25
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:XVIII POI









      SPOJ Problem Set (classical)

      9076. Hablu and Bablu

      Problem code: HABLU


      Hablu is a hardworking programmer. He solves lots of easy problems everyday :P. Hablu's teammate Bablu is busy with studies, so amount of solved by him is smaller than Hablu's.

      Their coach NannaMia noticed the fact that the number of solved problems by Hablu is a multiple of number of solved problems by Bablu.

      Then NannaMia asked Hablu a question. Giving a collection of integers S, NannaMia said that the number of solved problems by Bablu is not a multiple of any integer contained in S (S only contains primes or 1). How many valid integers are there which could be the number of problems solved by Bablu.

      As Hablu solves only easy problems, he is unable to solve this one. So, you need to help him :)

      Input

      The first line contains t, number of test cases (t<=1500).

      Each case starts with an integer H, the number of problems solved by Hablu and K, the size of the collection S. The next line contains K space separated integers (the members of S).

      Remember that the online judge in which they solve has only(!) 1012 problems. So no number will be greater than 1012. And K will be between 0 and 500.

      Output

      Print a line for each test case containing the number of possible integers which can be the number of solved problems by Bablu.

      Example

      Input:
      1
      58 2
      2 3

      Output:
      2

      Note : May be it's impossible to pass the time limit in several languages.

      Added by:Bidhan Roy ( বিধান )
      Date:2011-06-26
      Time limit:1s-2s
      Source limit:25000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem , Thanks to Muhammad Ridowan for his alternate solution.









      SPOJ Problem Set (classical)

      9081. Snail family problems

      Problem code: INCEST

      In this problem we'll be looking at a group of snails. Two snails, numbered a and b can get married, and some time after that they may even get divorced. Any snail may be married to number of other snails.

      The problem arises because snails don't like being married to their ancestors, and they don't know who their ancestors are - they only know the set of snails they're directly related to. A marriage between two snails from which one is an ancestor of the other is called "bad".

      If they knew who the oldest snail (the ancestor of everyone else) is, everyone would know their ancestors.

      For the given group of N snails numbered from 1 to N, you'll be given N-1 pairs of snails (a, b), indicating that snails a and b are directly related.

      Next you'll be given Q queries of the form:

      Q n  -  suppose n is the oldest snail, how many "bad" marriages are there in the group?
      M a b  -  snails a and b just got married.
      D a b  -  snails a and b just got divorced.

      No snail can ever get married to himself.

      You may assume that no pair will get married twice (if they are already married). You may also assume that no pair will get divorced if they don't get married before that.

      Input

      The first line of input contains an integer N (2 <= N <= 200000).
      Each of the next N-1 lines contains a pair of integers a and b (1 <= a < b <= N).
      The next line contains an integer Q (1 <= Q <= 300000).
      Each of the next Q lines contains a query as defined above.

      Output

      For each query of type Q output a single line containing the number of "bad" marriages if snail numbered n was the oldest one.

      Example

      Input:
      5
      1 2
      1 3
      2 4
      2 5
      9
      Q 1
      M 3 5
      Q 1
      Q 3
      M 1 4
      Q 3
      Q 4
      D 3 5
      Q 3 Output: 0
      0
      1
      2
      1
      1
       

      Added by:Gustav Matula
      Date:2011-06-27
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem, idea from a yuoi problem









      SPOJ Problem Set (classical)

      9084. Journey to Mars

      Problem code: JRNTMRS


      Byteazar has decided on going to Mars to tour the space stations there being in existence. All marsian space stations lie on a circumference of a circle. Byteazar lands in one of them and then moves around by means of a special vehicle which is powered by an appropriate fuel. A litre of this fuel allows him to travel one meter. However, the provisions of the fuel are meagre, different quantities of it are available in each space station. Byteazar may refuel in the space station he is currently in, though he cannot get more fuel than it is available in that very place (the capacity of his fuel tank is unlimited). This quantity of fuel should allow him to reach the next space station. Byteazar has to decide where to land, so that he can visit all of the space stations. In the end he has to return to the space station in which he has landed. During his journey Byteazar has to travel on the circumference of the circle, constantly in one of the two possible directions.

      Task

      Write a programme which:

      • reads from the standard input the number of space stations, distances between them and the amount of fuel available in each of them,
      • for each of the space stations checks, whether Byteazar can land there i.e. whether by starting in that very station and travelling in a freely chosen direction he is able to visit all of the space stations and return to his spaceship,
      • writes the outcome to the standard output.

      Input

      The first line of the standard input contains a single integer (). It denotes the number of space stations on Mars. The space stations are numbered from to . In the next lines there is a description of all of the stations and the distances between them. The 'st line contains two integers and (, ). The first one denotes the amount of fuel (in litres) available in the 'th space station. The other denotes the distance (in metres) between the 'th and 'st space station (obviously denotes the distance between the 'th and the st space station). The total amount of available fuel, as well as the sum of all distances between the space stations does not exceed .

      Output

      The programme should write lines to the standard output. The 'th line should contain the word TAK (i.e. yes is Polish), if Byteazar can land in the 'th space station or NIE (i.e. no in Polish) when it is not possible.

      Example

      For the input data:

      5
      3 1
      1 2
      5 2
      0 1
      5 4

      the correct result is:

      TAK
      NIE
      TAK
      NIE
      TAK

      Added by:Krzysztof Lewko
      Date:2011-06-28
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:XII POI









      SPOJ Problem Set (classical)

      9086. Formula 3D

      Problem code: JZPFOR

      There are n lattice points in the 3D space. One point can get to another if and only if their euclid distance is 1. Find out the number of simple cycles (that has length > 2). The number of points with same x coordinates do not exceed 8. 

      Input

      First line, n. 
      Following are n lines, each describes one pointcoordinates. 

      First line, n. 

      Following are n lines, each describes one point, no two points share same coordinates. 

      n<=400    coordinates in range [-10^9, 10^9] (inclusive).

      Output

      One number, the required answer mod 1000000007. 

      Example

      Input:
      8
      0 0 0
      0 0 1
      0 1 0
      0 1 1
      1 0 0
      1 0 1
      1 1 0
      1 1 1
      
      Output:
      28
      

      Added by:sevenkplus
      Date:2011-06-29
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      9096. Bob and magical scale

      Problem code: MGCSCLS

      Small Bob received scales with magical bricks. They are magical because they can have minus weight.

      His mom made L towers on the left arm and P towers on the right arm of the scale. Every tower is made with exactly N bricks.

      She asked him how many brick he has to put off from each arm to balance the scale. Obviously Bob can only take bricks from top of the tower and he can't put back taken off bricks.It's too difficult for him.Can you help him solve it in minimum number of moves?

      Input

      In first line number N,L,P . Number of bricks in every tower. Number of towers on left arm and Number of towers on right arm.

      In next L lines: construction of towers on the left arm.

      In next P lines: construction of towers on the right arm. ( look at picture )

      N<=50

      L<=25

      P<=25

      -50<=weight of every brick<=50

      Output

      Minimal number of moves to balance the scale.

      Example

      2 2 2
      4 3
      -1 2
      7 3
      1 -2

      Output: 2

      I made timelimit so high because i want all correct solutions to get accepted, but not n! solution.

      Added by:Krzysztof Lewko
      Date:2011-07-01
      Time limit:1s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:III POIG









      SPOJ Problem Set (classical)

      9097. Derangements HARD

      Problem code: NOVICE65


      A derangement of n numbers is a permutation of those numbers in which none of the numbers appears in its original place. For example, the numbers {1,2,3} can be deranged into {2,3,1} and {3,1,2}. We can modify this slightly for n numbers that are not necessarily distinct by saying that no number in the derangement can be in the place that a number of the same value was in in the original ordering. So the numbers {1,1,2,2,3} could be deranged into {2,2,1,3,1}, {2,2,3,1,1}, {2,3,1,1,2}, and {3,2,1,1,2}.

      Input

      First line contains T(1<=T<=100) the number of test cases. Each test case contains two lines. First line contains an integer N(1<=N<=15) denoting total number of elements in the array. Second line contains a space separated list of N integers Ai such that 0<=Ai<N.

      Output

      For each test case output an integer, the total number of derangements of the array.

      Example

      Input:
      2
      5
      1 1 2 2 3
      6
      0 0 0 1 1 1
      Output:
      
      4
      
      1

      Added by:amit karmakar
      Date:2011-07-01
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9098. Long Common Subsequence

      Problem code: LCS3

       

      Given a sequence of N(1<=N<=1000000) numbers range from 0 to 10000 and several other sequence of M(0<=M<=5) numbers, you have to compute the Longest Common Subsequence of this sequences with the main sequence.

       

      Given a main sequence of N(1<=N<=1000000) numbers range from 0 to 10000 and several other sequence of M(0<=M<=5) numbers, you have to compute the Longest Common Subsequence of this sequences with the main sequence.

       

       

      Input

      First line of the input will be N the number of elements of the main sequence. After that line there will be N numbers in one or more lines. Each of this number will be between 0 to 10000(inclusive). Then there will be Q(1<=Q<=5000) the number of query. Then following Q lines will be queries. In each query, start with a number M(0<=M<=5), followed by M numbers also between 0 to 10000(inclusive).

      Output

      For each query first print the number of elements in the longest common subsequence of the main and query sequences. Then print the subsequence. If there is more then one then print the lexicographically smallest.

      Example

      Input:
      10
      5 1 4 3 2 6 5 5 0 7
      5
      1 5
      1 10
      4 5 0 4 7
      5 4 1 2 3 5
      5 2 6 5 0 7

       

      Output:
      1 5
      0
      3 5 0 7
      3 1 2 5
      5 2 6 5 0 7
      
      
      
      Huge Test Case(Almost 5MB)

       

       


      Added by:Muhammad Ridowan
      Date:2011-07-02
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own. Thanks msh_shiplu and zobayer for alternate









      SPOJ Problem Set (classical)

      9103. Special Numbers

      Problem code: NOVICE63

      Ted thinks that integers having equal number of 1's and 0's in their binary representation are special. Therefore, he wants to know how many such integers are present.

      Note: For this problem, the binary representation of an integer(>0) is considered from the least significant bit to the last set bit. Which means, 5 has a binary representation of 101, 3 has a binary representation of 11 etc. As such, one example of a special number is 9 which has a binary representation, 1001.

      Input

      First line contains an integer T(atmost 100) denoting the total number of test cases. Each test case contains a single integer N(2 <= N <= 2^60). N is always a power of 2.

      Output

      A single integer denoting the total number of such special numbers in the range 1 to N (inclusive).

      Example

      Input:
      3
      8
      16
      32
      
      Output:
      1
      4
      4
      
      

      Added by:amit karmakar
      Date:2011-07-02
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used in - http://www.spoj.pl/NOVICE6/









      SPOJ Problem Set (classical)

      9104. Match the words

      Problem code: NOVICE62


      You may have come across questions like, Match-The-Following words with their synonyms in the second column and alike. Ted also stumbled upon one such question. Being weak at english, he tried guessing the answers. While he guessed, he thought about how unlucky he was at guessing.

      Being also weak at math, he needs help from you for a slightly different task. Find the total number of ways of completing the solution to this question in which he gets none of the matches correct.

      Note: In the match-the-following problem, there are two columns of words. Each column contains N words. Words in the first column have to be matched with words in the second column. A valid solution to this question requires every word in the first column to be matched with only one word in the second column and vice-versa.

      Input

      First line contains a single integer T(1 <= T <= 1000) denoting the total number of test cases. Each test case contains a single integer N (1 <= N <= 1000000).

      Output

      For each test case, print a single integer the required number of ways modulo 1000000007

      Example

      Input:
      3
      1
      2
      7
      
      Output:
      0
      1
      1854
      

      Added by:amit karmakar
      Date:2011-07-02
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem......









      SPOJ Problem Set (classical)

      9117. Faculty Dividing Powers

      Problem code: GCPC11A

      Fred Faculty and Paul Power love big numbers. Day after day Fred chooses a random integer n and he computes n!. His friend Paul amuses himself by computing several powers of his randomly chosen integer k like k2, k3 and so on. On a hot summer day, Fred and Paul got really, really bored, so they decided to play a joke on their buddy Dave Divider. Fred chooses a random integer n while Paul chooses a random integer k. They want Dave to find the biggest integer i such that ki divides n! without a remainder, otherwise they will throw a cake in Dave's face. Because Dave does not like cakes in his face, he wants you to help him finding that integer i.

      Input

      The first line contains the number of test cases t (1 ≤ t ≤ 100). Each of the following t lines contains the two numbers n,k (2 ≤ n ≤ 1018, 2 ≤ k ≤ 1012) separated by one space.

      Output

      For each test case, print the maximum integer i on a separate line.

      Example

      Input:
      2
      5 2
      10 10
      
      Output:
      3
      2
      

      Be careful with overflows in this problem (use 64 bit integers, avoid multiplications which will lead to overflow).


      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Authors: Christopher Dennl and Thomas Fersch)









      SPOJ Problem Set (classical)

      9118. Genetic Fraud

      Problem code: GCPC11B

      Computer Scientists have a rough life. Due to the shortage of bright young minds like yourself, good programmers are mostly like famous movie stars. It's just like everyone wants to get their hands on your hard earned cash. The situation got so out of hand that you are faced by a lawsuit nearly every day of the year. Each lawsuit is filed by someone claiming alimonies for your alleged child. Luckily for you, you know pretty much about genetic sequences. You know that the human DNA sequence can be represented by a possibly N characters long string, containing only characters 'a' to 'z'. And you know that a similarity test of the DNA strings of the alleged child to your own can prove your innocence.

      The only problem is that this does not only happen to you. As all labs are busy, testing needs at least a year. Still, not all hope is lost. You managed to get the information from one of the DNA labs on how to compute the probability of a genetic relationship between two DNA strings. If you could only help the DNA labs to test two DNA strings for a genetic relationship really fast, you could get the evidence you need for your own lawsuits.

      A genetic relationship test, or GRT, requires some heavy computation on the DNA strings. They first acquire all similar regions within two DNA strings. We understand a region within a DNA string to be a consecutive interval within the DNA string. Regions a[i..i+l] (0 ≤ i < N-l) and b[j..j+l] (0 ≤ j < N-l) of DNA strings a, b are similar to each other, if |a[i+k] - b[j+k]| ≤ 1 for 0 ≤ k ≤ l. A GRT between two DNA sequences is positive, whenever the two DNA sequences have a similar region of at least one half the length of the DNA sequences.

      Input

      The first line of the input gives the number of test cases C (0 < C ≤ 1000). The first line of each such test case holds an integer N (1 ≤ N ≤ 1000), denoting the length of the two DNA strings to be tested. The following two lines contain a string of N lower-case letters each, giving the two DNA substrings of the two persons to test.

      Output

      For each test case print one line. If the GRT is positive, print out POSITIVE. Print NEGATIVE, if the test fails.

      Example

      Input:
      3
      4
      aaaa
      bbcc
      8
      iacdefgh
      abeaaaaa
      8
      iacdefgh
      abeafaaa
      
      Output:
      POSITIVE
      NEGATIVE
      NEGATIVE
      

      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Author: Moritz Kobitzsch)









      SPOJ Problem Set (classical)

      9119. Indiana Jones and the lost Soccer Cup

      Problem code: GCPC11C

      In 1930 the first FIFA World Cup was held in Uruguay, and Uruguay won the Cup in a dramatic final against Argentina. All of this seems like ages past, and now myth and legend rank around that historic first world cup. Some even claim that the original trophy cup that was awarded to Uruguay for their victory has mythical powers and would grant any side the strength to win the World Cup.

      Now that original cup has been lost in time, and even though its mythical powers are probably just stories, it is still an important artifact which belongs in a museum. Clearly an expert is needed to recover it.

      Famous archaeologist and adventurer Indiana Jones has taken this dangerous task onto himself and traveled to Uruguay to find the cup. His search has led him to an ancient underground cave system where the cup is rumoured to have been hidden. Many traps lure within these caves, and only his instinct and his faithful whip have saved Indy from certain death. Now he has reached a mysterious enormous gate and he can only speculate that the cup must be hidden behind that gate. Unfortunately it is shut close.

      The gate is riddled with switches and levers, and all of them are denoted with letters and numbers. As you may have guessed, the gate will only open if the switches and levers are pulled in the correct order, but beware! - For if anyone is unlucky enough to get the order wrong, doom awaits him.

      Luckily, during his exploration of the caves Indy has found several encrypted hints which provide clues about the correct sequence. Here's one: "The faithful knows that X comes before O" And another: "Under no circumstances should you touch a unless b has been moved!" Clearly these clues give hints about the correct order, but there are a lot of switches and levers, and there are lots of clues. Indy needs help!

      Given all of the hints Indy has collected, can you help him determine the correct order of the levers and switches so that he can successfully complete his adventure? But beware - Indy could have missed some hints; or perhaps he misinterpreted some of them. The former case will likely leave more than one possible sequence while the latter will lead to no possible sequence at all. You must detect these cases and warn Indy.

      Input

      The first line of input contains the number of test cases C (C ≤ 30). For each test case there is one line with the number n (1 ≤ n ≤ 104) of switches/levers on the gate and the number h (0 ≤ h ≤ 105) of hints that Indy has discovered. Then follow h lines, one for each clue, with the numbers a and b (1 ≤ a,b ≤ n, a ≠ b), meaning that lever a must be pulled before lever b.

      Output

      For each test case output one line with the correct sequence of the numbers 1 to n. Separate the numbers with a whitespace. If there is no possible sequence, print recheck hints instead. Otherwise if there are multiple possible sequences, print missing hints instead.

      Example

      Input:
      3
      3 2
      1 2
      3 1
      3 1
      1 2
      3 2
      1 2
      2 1
      
      Output:
      3 1 2
      missing hints
      recheck hints
      

      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Author: Holger Frydrych)









      SPOJ Problem Set (classical)

      9120. Magic Star

      Problem code: GCPC11D


      A magic star consists of all the numbers from 1 to 12 arranged in the shape of a hexagram:

      example image

      The magic comes from the fact that in each line of 4 numbers, the sum of the numbers is 26. In the example given above, the six lines consist of the following numbers:

      • 1 + 4 + 10 + 11
      • 11 + 5 + 3 + 7
      • 7 + 6 + 12 + 1
      • 2 + 10 + 5 + 9
      • 9 + 3 + 6 + 8
      • 8 + 12 + 4 + 2

      There are several possible ways to arrange the numbers to get a magic star. Given a partially labelled star, your task is to extend the solution such that a magic star is formed.

      Input

      The input consists of a visualization of the star; the unlabelled fields of the star will be represented by an 'x' character, and labelled fields will contain a letter between 'A' and 'L', where the i-th letter in the alphabet represents number i. The character '.' is used to align the fields of the star in the shape of a hexagram. You may assume that each input will use the same alignment of the fields as the one in the sample input.

      Output

      Print the lexicographically smallest extension of the given partial solution which is a magic star (lexicographically smallest means that the concatenation of the rows should result in a string which is lexicographically smaller than other potential solutions). You may assume that there is always a solution for the given input.

      Example

      Input:
      ....x....
      .A.I.D.x.
      ..x...x..
      .x.x.x.x.
      ....x....
      
      Output:
      ....F....
      .A.I.D.L.
      ..H...E..
      .C.J.B.K.
      ....G....
      

      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Author: Adrian Kuegel)









      SPOJ Problem Set (classical)

      9121. Magical Crafting

      Problem code: GCPC11E


      One of the recent hypes in terms of independent games has been Minecraft, a cute little game in which you mine some materials and are able to craft a lot of stuff using these materials. Since you already mastered the Minecraft universe, you decide to write your own little mod for the game to add magical crafting.

      Given some magic stone m1, by adding a specific amount of diamonds you can transform it into two magic stones m2 and m3, where m1, m2 and m3 are upper-case letters. This is called a crafting recipe.

      There is also a default transformation which transforms a magic stone into its matching lighting effect; the matching lighting effect for a magic stone labelled with an upper-case letter is the corresponding lower-case letter, e. g. the magic stone 'A' can be transformed into the lighting effect 'a'. This transformation always costs exactly 1 diamond. The default transformation is used whenever you do not use a magic stone for another crafting recipe. The lighting effects will show in a certain order. For each used crafting recipe m1 -> m2 m3, the lighting effects which are derived from the magic stone m2 will show before the lighting effects derived from the magic stone m3.

      You want to be able to craft wonderful magic lights for your own world. But as you are aware of the rareness of the precious diamonds, and also very picky about the lighting effect sequences you want to achieve, you have to test your crafting recipes. The question arises if your set of crafting recipes allows you to create all your desired lighting effect sequences if you only have the magic stone 'A' to start with, and the minimum number of diamonds you will need for the transformations.

      Input

      The first line of the input gives the number of test cases C (0 < C ≤ 100). Each test case starts with two integers 0 ≤ R ≤ 30, 0 ≤ L ≤ 10 on a single line, denoting the set of recipes and the number of lighting effect sequences. The next R lines contain the set of recipes. Each crafting recipe is given on a single line by the magic stones m1, m2, and m3 as well as the number d (0 ≤ d ≤ 1000) of diamonds necessary for the transformation. The next L lines contain the lighting effect sequences you want to create. Each of these lines contains an integer l (1 ≤ l ≤ 100), which represents the length of the lighting effect sequence. The line completes with a single string of length l, consisting only of lower case characters 'a' to 'z', which represents the sequence of lighting effects you want to create.

      Output

      For every test case print CASE # followed by the number of the test case, starting with 1, on a single line. For each lighting effect sequence print a single line. If the effect is possible print POSSIBLE WITH X DIAMONDS, with X representing the number of diamonds you will need to achieve the lighting effect sequence. In the case the lighting effect sequence cannot be crafted, print IMPOSSIBLE.

      Example

      Input:
      2
      1 4
      A A A 2
      3 aaa
      8 aaaaaaaa
      5 ababa
      1 a
      3 1
      A B C 1
      C P C 7
      B I C 11
      4 icpc
      
      Output:
      CASE #1
      POSSIBLE WITH 7 DIAMONDS
      POSSIBLE WITH 22 DIAMONDS
      IMPOSSIBLE
      POSSIBLE WITH 1 DIAMONDS
      CASE #2
      POSSIBLE WITH 23 DIAMONDS
      

      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:35s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Author: Moritz Kobitzsch)









      SPOJ Problem Set ()

      9122. Diary

      Problem code: GCPC11F


      Nowadays, people who want to communicate in a secure way use asymmetric encryption algorithms such as RSA. However, my older brother uses another, simpler encryption method for his diary entries. He uses a substitution cipher where each letter in the plaintext is substituted by another letter from the alphabet. The distance between the plaintext letter and the encrypted letter is fixed. If we would define this fixed distance d to 5, A would be replaced by F, B by G, C by H, ..., Y by D, Z by E.

      With a fixed and known distance d the decryption would be somewhat simple. But my brother uses random distances for each of his diary entries. To decrypt his diary I have to guess the distance d for each entry. Thus, I use the well known phenomenon that the letter E is used more often in English words than other letters. Can you write a program for me that calculates the distance d based on the fact that the most used letter in the encrypted text corresponds to the letter E in plaintext? Of course, I am interested in the decrypted text, too.

      Input

      The input consists of several test cases c that follow (1 ≤ c ≤ 100). Each test case is given in exactly one line containing one diary entry. Diary entries only use upper case letters (A-Z) and spaces. Each diary entry consists of at most 1000 encrypted letters (including spaces).

      Output

      For each test case, print one line containing the smallest possible distance d (0 ≤ d ≤ 25) and the decrypted text. If the decryption is not possible because there are multiple distances conforming to the rules above, print NOT POSSIBLE instead. Spaces are not encrypted.

      Example

      Input:
      4
      RD TQIJW GWTYMJWX INFWD JSYWNJX ZXJ F XNRUQJ JSHWDUYNTS YJHMSNVZJ
      THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
      XVIDRE TFCCVXZRKV GIFXIRDDZEX TFEKVJK UVTIPGKZFE
      XVIDRE TFCCVXZRKV GIFXIRDDZEX TFEKVJK
      
      Output:
      5 MY OLDER BROTHERS DIARY ENTRIES USE A SIMPLE ENCRYPTION TECHNIQUE
      10 JXU GKYSA RHEMD VEN ZKCFI ELUH JXU BQPO TEW
      17 GERMAN COLLEGIATE PROGRAMMING CONTEST DECRYPTION
      NOT POSSIBLE
      

      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Author: Tobias Werth)









      SPOJ Problem Set ()

      9123. Security Zone

      Problem code: GCPC11G

      The manager of a large security company has to build a new surveillance system for different sites. A site consists of N objects where each object has its own security circle. At the border of the surveillance system a high voltage fence has to be installed. The security zone inside of the fence has to be connected. Furthermore, all objects and their security circles should be inside the security zone. The security circles of different objects will never overlap or touch. Now the manager needs your help. He asks you for the minimal needed fence length.

      example image example image

      Input

      The first line of the input gives the number of test cases C (0 ≤ C ≤ 100). The first line of each such test case holds the integer N: the number of objects in the current site (0 < N ≤ 25). Each of the following N lines holds three integers xi, yi, and ri that describe an object. The coordinates of the i-th object and the radius for the needed security circle for this object. (|xi|,|yi| ≤ 100, 0 < ri ≤ 100) (The center of the security circle around an object is the position of the object itself.)

      Output

      For each test case print one line containing the minimal fence length for this case. Your output should have an absolute or relative error of at most 10-7.

      Example

      Input:
      3
      3
      2 2 1
      8 2 1
      5 6 1
      2
      6 4 2
      2 4 1
      4
      2 2 2
      6 1 1
      5 5 2
      1 6 1
      
      Output:
      22.2831853072
      17.6761051635
      25.4247779608
      

      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Author: Alexander Rass)









      SPOJ Problem Set (classical)

      9124. Sightseeing

      Problem code: GCPC11H

      As a computer science student you are of course very outdoorsie, so you decided to go hiking. For your vacation this year, you located an island full of nice places to visit. You already identified a number of very promising tracks, but are still left with some problems. The number of choices is so overwhelming, that you had to select only a "small" subset of at most 105 sights.

      And if that is not enough, you are very picky about the order in which you want to visit the sights. So you have already decided on an order in which you want to visit the preselected tracks. The problem you are left with is to decide in which direction to travel along each single track, and whether you may have to reduce your choice of tracks even further. After identifying the travel time between the endpoints of different tracks, you decide to write a program to figure out if you can make all your trips within the time you have planned for your vacation. Since you also do not want to waste any precious time, you only care about an optimal solution to your problem. Furthermore, the tracks can get pretty challenging. Thats why you do not want to hike along a track more than once.

      Input

      The first line of the input gives the number of test cases C (0 < C ≤ 100). The first line of each such test case holds two integers N, T the number of tracks of the current hiker (1 ≤ N ≤ 105) and the maximal time spent hiking throughout the vacation (0 ≤ T ≤ 106). Each of the following N lines holds five integers cp, cbb, cbe, ceb and cee that describe a track (in order of importance). cp gives the length of the track in minutes. cxy gives the travel time of the official begin or end of a track to the beginning or end of the next most important track, where x and y are either b or e. All values given are non-negative integers not greater than 106. Since you have to get back to your car, the list is circular. Furthermore, we will ignore the time it takes you to get to the start of your trip with your car.

      Output

      For each test case print one line. The output should contain a list of either F or B for every track (in order) indicating whether you have to hike the track in forward direction or backward direction. If you cannot make the full trip within the planned time T, you should print IMPOSSIBLE to indicate that these trips are just too much hiking. You can assume that the optimal solution is always unique.

      Example

      Input:
      3
      2 100
      4 7 8 2 3
      1 4 6 1 2
      2 20
      4 2 3 7 8
      1 1 2 4 6
      3 5
      1 2 2 2 1
      1 1 2 2 2
      1 2 2 1 2
      
      Output:
      FF
      BB
      IMPOSSIBLE
      

      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Author: Moritz Kobitzsch)









      SPOJ Problem Set (classical)

      9125. Suiting Weavers

      Problem code: GCPC11I

      example image

      Willy the Weaver is in desperate hope to get married to the most beautiful and delightful female weaver Wilmar. Of course, Willy is not the only weaver interested in Wilmar.

      In order to impress the females, weavers build elaborately woven nests using leaf fibers. Tomorrow is the big day on which Wilmar will inspect all nests. There is a heavy storm at the moment, and no weaver can leave his nest within the hours before sunrise. However, the storm will produce many piles of leaf fibers, so that all weavers will have a chance to improve their nests. Therefore, Willy is curious if he can succeed weaving the most impressive nest, so that Wilmar will finally decide on getting married to him. Since size matters, Willy tries to figure out how large his nest and the ones of his rivals may become.

      For this purpose, Willy takes into consideration all known places offering leaf fibers suitable for nest construction. Since weavers do not like to leave their known territory, many of these places can be accessed by a subset of all weavers only, and some might even not be reachable by any weaver.

      To reduce complexity, Willy does not want to set up a flight plan. This implies that he does not consider any particular strategy of his rivals nor does he make any assumptions on how many fibers they can carry at a time or how quick and when they fly. It is therefore possible that a weaver succeeds in picking up all fibers in his territory. Finally, Willy assumes that all weavers are as integer as he is: they do not steal fibers from nests of their rivals.

      Is there any chance that no weaver will have a larger nest (number of fibers) than Willy after all leaf fibers have been picked up?

      Input

      The first line contains the number of testcases T (1 ≤ T ≤ 100). Each test case starts with a line containing two integers. The first integer W (1 ≤ W ≤ 100) is the number of weavers (including Willy); the second one P (1 ≤ P ≤ 400) is the number of places with leaf fibers.

      Next come W lines describing the nest of each weaver with four integers x, y, f, and r (0 ≤ x, y, r ≤ 10000, 1 ≤ f ≤ 10000): x and y define the position of the nest, f is the size of the nest in number of fibers, and r is the radius of the territory in which the owner of the nest will search for additional fibers. The first of these W lines describes Willy's nest.

      Thereafter follow P lines defining the places with available leaf fibers with three integers x, y, and f (0 ≤ x, y ≤ 10000, 1 ≤ f ≤ 10000): x and y define the position of the place, and f is the number of available leaf fibers.

      Output

      For each test case print one single line containing the string Suiting Success, if Willy has a chance to marry Wilmar after all fibers have been picked up (a tie in nest size is sufficient); else print Lonesome Willy.

      Example

      Input:
      2
      3 2
      0 0 1 10
      10 0 1 10
      20 0 1 10
      5 0 2
      15 0 4
      3 2
      0 0 1 10
      10 0 1 10
      20 0 1 10
      5 0 2
      15 0 5
      
      Output:
      Suiting Success
      Lonesome Willy
      

      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Authors: Christian Renner and Christoph Weyer)









      SPOJ Problem Set (classical)

      9126. Time to live

      Problem code: GCPC11J

      As you might know, most computer networks are organized in a tree-like fashion, i.e. each computer is reachable by each other computer but only over one, unique path.

      The so-called Time to live (TTL) specifies after how many hops a network packet is dropped if it has not reached its destination yet. The purpose of the TTL is to avoid situations in which a packet circulates through the network caused by errors in the routing tables.

      The placement of a router that connects the network to another network is optimal when the maximal needed TTL for packets that are sent from this router to any other computer within the same network is minimal. Given a network as specified above, you should calculate the maximal needed TTL in this network if you can select the computer that should be used as router.

      Input

      The first line of the input consists of the number of test cases c that follow (1 ≤ c ≤ 100). Each test case starts with a line specifying N, the number of computers in this network (1 < N ≤ 105). Computers are numbered from 0 to N-1. Then follow N-1 lines, each specifying a network connection by two numbers a and b which means that computer a is connected to computer b and vice versa, of course (0 ≤ a,b < N).

      Output

      For each test case in the input, print one line containing the optimal TTL as specified above.

      Example

      Input:
      3
      2
      1 0
      5
      3 2
      2 1
      0 2
      2 4
      9
      3 1
      6 5
      3 4
      0 3
      8 1
      1 7
      1 6
      2 3
      
      Output:
      1
      1
      2
      

      Added by:Adrian Kuegel
      Date:2011-07-05
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:German Collegiate Programming Contest 2011 (Author: Tobias Werth)









      SPOJ Problem Set (classical)

      9137. Pyramid Sums

      Problem code: PYRSUM


      This is an easier version of PYRSUM2

      Tommy is stacking square blocks in columns labelled from 1 to 1000000 (106). Since it can be quite boring writing out the locations of every block he instead specifies a set of 2D pyramids that when built on top of each other will make the shape he wants. Pyramids always have height H=(W+1)/2 and take up N=H2 blocks so it is quite easy for him to work out how many blocks he will need in total from this description.

      What is not so easy is working out how many blocks he will need to build in the space that occurs in the range between two columns (inclusive!). Given a set of instructions consisting of either

      • “build [centre] [w]” (build another pyramid, width [w] with its midpoint at [centre]) or
      • “count [left] [right]” (count the number of blocks added so far within the range of these columns inclusive)

      you must try to answer the queries as quickly as possible.

      Input

      First line: (1<=T<=20), the number of test cases.

      Within each test case:

      1. (1<=N<=1000), the number of operations to perform.
      2. N lines, each containing one operation (as detailed above).

      Output

      Answer each count query on its own line, putting an additional blank line after each test case.

      Please use 64-bit counters as the result may overflow a 32-bit container!

      Example

      Input:
      4
      3
      build 5 3
      build 6 5
      count 4 7
      2
      build 200 99
      count 151 151
      4
      build 2 1
      count 1 1
      count 2 2
      count 1 2
      6
      build 5000 3999
      count 1 10000
      build 2 1
      build 3 1
      count 2 2
      count 2 3
      
      Output:
      12
      
      1
      
      0
      1
      1
      
      4000000
      1
      2
      
      Visualisation of first test case:
      ----BB---
      ----BB---
      ---BABB--
      ---AAABB-
         ^  ^

      Added by:Robin Lee
      Date:2011-07-07
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Self









      SPOJ Problem Set (classical)

      9138. Pyramid Sums 2

      Problem code: PYRSUM2

      This is a harder version of PYRSUM

      Tommy is stacking square blocks in columns labelled from 1 to 1000000 (106). Since it can be quite boring writing out the locations of every block he instead specifies a set of 2D pyramids that when built on top of each other will make the shape he wants. Pyramids always have height H=(W+1)/2 and take up N=H2 blocks so it is quite easy for him to work out how many blocks he will need in total from this description.

      What is not so easy is working out how many blocks he will need to build in the space that occurs in the range between two columns (inclusive!). Given a set of instructions consisting of either

      • “build [centre] [w]” (build another pyramid, width [w] with its midpoint at [centre]) or
      • “count [left] [right]” (count the number of blocks added so far within the range of these columns inclusive)

      you must try to answer the queries as quickly as possible.

      Input

      (1<=N<=200000), the number of operations to perform.

      N lines, each containing one operation (as detailed above).

      Output

      Answer each count query on its own line, putting an additional blank line after each test case.

      Please use 64-bit counters as the result may overflow a 32-bit container!

      Example

      Input:
      3
      build 5 3
      build 6 5
      count 4 7
      
      Output:
      12
      
      Visualisation of example test case:
      ----BB---
      ----BB---
      ---BABB--
      ---AAABB-
         ^  ^

      Added by:Robin Lee
      Date:2011-07-08
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Self









      SPOJ Problem Set (classical)

      9161. Legendre symbol

      Problem code: LEGRENDS

      Given 2 integers a and p (1<=a,p<=1000000, p is prime) calculate the Legendre symbol (a/p).

      Input

      In the first line the number of test cases t<100000. Then t lines with the 2 integers a and p.

      Output

      t lines with the Legendre symbol (a/p).

      Example

      Input:
      4
      2 7
      5 7
      14 7
      3 2 Output: 1
      -1
      0
      1

      Added by:HWK
      Date:2011-07-11
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9185. TORNJEVI

      Problem code: TORNJEVI

      We are being attacked on a map represented by a rectangular grid of R×S squares. The attackers are barefoot robbers, and we use small cannons on small wooden towers to defend ourselves.

      Each tower is equipped with two cannons, placed to fire in a 90 degree angle. More precisely, cannons on one tower can be set to fire in one of the following four configurations:

      1. fire left and down;
      2. fire down and right;
      3. fire right and up;
      4. fire up and left.

      A cannon ball that hits the attacker destroys him and continues to fly in the same direction. A cannon ball which hits a castle stops and does no damage to the castle (because castles are big and strong). But, when a cannon ball hits a tower, it destroys it (because towers are small and fragile).

      We want to turn the cannons on the towers so that, when we fire exactly one shot from every cannon, we destroy all the attackers, and all our towers remain undamaged.

      Input

      The first line contains two integers R and S (1 ≤ R, S ≤ 100), the dimensions of the map.

      The next R lines contain S characters each, the map.

      Each character on the map can be the uppercase letter 'T' (tower), lowercase letter 'n' (attacker), the character '#' (castle) or the character '.' (empty).

      Note: There will always be a solution, although not necessarily unique.

      Output

      Output the map in the same format as in the input, replacing 'T' characters with the orientations of the cannons – each tower should be replaced with one of the digits '1', '2', '3' or '4', corresponding to the four orientations as described above.

      Examples

      Input:
      9 13
      .............
      ...........n.
      .n.T..nnnn#..
      .............
      .T#n..n....T.
      .............
      .n.T..T....n.
      .............
      ......n......
      
      
      Output:
      .............
      ...........n.
      .n.3..nnnn#..
      .............
      .4#n..n....4.
      .............
      .n.1..2....n.
      .............
      ......n......
      
      
      Input:
      5 9
      .n..T..n.
      .T..n....
      .n..#..n.
      ....n..T.
      .n..T..n.
      
      Output:
      .n..4..n.
      .2..n....
      .n..#..n.
      ....n..4.
      .n..3..n.
      
      
      Input:
      9 8
      n.Tnnnnn
      nnnnnnTn
      nTnnnnnn
      nnnnTnnn
      Tnnnnnnn
      ..#nnTnn
      nnnnnnnT
      nnnTn.n.
      .nTnnnnn
      
      
      Output:
      n.3nnnnn
      nnnnnn1n
      n2nnnnnn
      nnnn1nnn
      3nnnnnnn
      ..#nn4nn
      nnnnnnn4
      nnn4n.n.
      .n3nnnnn
      
      

      Added by:Bin Jin
      Date:2011-07-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.0.0-8
      Resource:CROATIAN HIGHSCHOOL COMPETITIONS IN INFORMATICS 2007, Final Exam #2









      SPOJ Problem Set (classical)

      9190. Perfect Maze

      Problem code: TREEMAZE

      Hi, Guys.

      Yestarday my nephew come and we played with lego. We decided to create castle with maze.

      We took board 5 x 5  and started build different mazes. We decided that we need perfect maze - One that has minimum lego pieces, but there should be exactly one path between each pair of cells without lego.

      We quikly find out that we need just 6 pieces and build all 22 configurations using them

      Some of them:

      Maze

      But then he took his board 13 x 13 and said - let's build perfect maze here!

      Now we have no idea how much pieces we need and how much configurations we should build. Please help!

       

       

      Output

      Two numbers - number of single lego pieces we need to build perfect maze on 13x13 board and number of configurations of them.

       

      Thanks!

       

       


      Added by:Oleg Chernyakhovskiy
      Date:2011-07-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:AWK NODEJS PYTH 3.2.3 n SED TEXT









      SPOJ Problem Set (classical)

      9199. Circular Track

      Problem code: SPEED

       

      Two person are running on a circular track either in same direction or opposite direction indefinitely. The speed of both of them is given to you. Speed will be positive in clockwise direction, and negative in anticlockwise direction. Print the number of distinct points, they will meet on the circle.
      Input
      First line contains t, number of test cases.
      Each test case contains two numbers, S1 and S2 (not equal to zero) which are the speeds of the two persons. S1 and S2 will be distinct.
      Output
      Print in a separate line, the number of distinct points at which they meet.
      Example
      Input
      2
      1 2
      1 -1
      Output
      1
      2

      Two persons are running on a circular track either in the same direction or in the opposite direction, indefinitely. The speed of both of them is given to you. Speed will be positive in clockwise direction, and negative in anticlockwise direction. Print the number of distinct points, at which they will meet on the circle.

      Input
      First line contains t, number of test cases. Each test case contains two numbers, S1 and S2 (not equal to zero) which are the speeds of the two persons. S1 and S2 will be distinct.

      Output
      Print in a separate line, the number of distinct points at which they meet.

      Example

      Input
      2
      1 2
      1 -1

      Output
      1
      2

       


      Added by:Nikunj Jain
      Date:2011-07-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9213. Mafia

      Problem code: MAFBOI08

      The police in Byteland got an anonymous tip that the local mafia bosses are planning a big transport from the harbour to one of the secret warehouses in the countryside. The police knows the date of the transport and they know that the transport will use the national highway network.

      The highway network consists of two-way highway segments, each segment directly connecting two distinct toll stations. A toll station may be connected with many other stations. A vehicle can enter or exit the highway network at toll stations only. The mafia transport is known to enter the highways at the toll station closest to the harbour and leave it at the toll station closest to the warehouse (it will not leave and re-enter the highways in between). Special police squads are to be located in selected toll stations. When the transport enters a toll station under surveillance, it will be caught by the police.

      From this point of view, the easiest choice would be to place the police squad either at the entry point or the exit point of the transport. However, controlling each toll station has a certain cost, which may vary from station to station. The police wants to keep the overall cost as low as possible, so they need to identify a minimal controlling set of toll stations, which satisfies the two conditions:

      • all traffic from the harbour to the warehouse must pass through at least one station from that set,
      • the cost of monitoring these stations (i.e. the sum of their individual monitoring costs) is minimal.

      You may assume that it is possible to get from the harbour to the warehouse using the highways.

      Input

      The first line of the standard input contains two integers and (, ) - the number of toll stations and the number of direct highway segments. The toll stations are numbered from to .

      The second line contains two integers and (, ) - the numbers of the toll stations closest to the harbour and to the warehouse, respectively.

      The following lines describe the monitoring costs. The -th of these lines (for ) contains one integer - the monitoring cost of the -th station (which is positive number not exceeding ).

      The following lines describe the highway network. The -th of these lines (for ) contains two integers and (), indicating that there is a direct highway segment between toll stations numbered and . Each highway segment is listed once.

      Output

      The only line of the output should contain the numbers of toll stations in a minimal controlling set, given in increasing order, separated by single spaces. If there is more than one minimal controlling set, your program may output anyone of them.

      Example

      For the input data:

      5 6
      5 3
      2
      4
      8
      3
      10
      1 5
      1 2
      2 4
      4 5
      2 3
      3 4

      the correct result is:

      1 4

      The figure shows the highway network with the toll station numbers (in the upper-left corners) and the monitoring costs. Stations number 1 and 4 constitute the minimal controlling set with total controlling cost 5.

       


      Added by:Krzysztof Lewko
      Date:2011-07-23
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:boi 08









      SPOJ Problem Set (classical)

      9219. Nikhil Problem

      Problem code: BHAT007

      Nikhil is a very interesting and creative charater. Nikhil had best friend whose name was Kasat. Kasat was inspired from SKG ,a mathematics professor  having  an experience of 30 years of teaching in IIT Kanpur , So he decided to open Mathematics classes named as “SAI KRIPA GANIT BHANDAR”  .But unfortunately no one joined  his classes as the fees he charged was too less compared to other institutions ,so people thought that he is not a good teacher and his wait for the students continued ,but the best friend Nikhil was not able to see his friend Kasat in such a gloomy situation. So to boost kasat’s spirit he became the only student of  the “SAI KRIPA GANIT BHANDAR” .

      Nikhil  learned addition multiplication in different number system (like binary number system : base 2, octal number system : base 8, Hexagonal number system , Kasat number system : base 7, Shrotriya number system : base 3, bhat number system : base 13, rajnikant number system base:100, ravikant number system base:101 etc. ).

      Nikhil was given daily assignment on this but helping friends and being lazy are two different things ,all he could help kasat was to join coaching classes and completing those complex  assignment were not  his cup of tea. Kasat thought an innovative idea for Nikhil to sharp his mind in the field of number system. So , he gives the same type of problem daily in assignment.

      Problem :

      x(b1) + y(b1) = z1

      x(b2) + y(b2) = z2

      x(b): number x in base b number system .

      x and y are two numbers ( must be valid in decimal (i.e. base 10), base b1 and base b2 number system like  1A is not valid in base 10 i.e. decimal number system but valid in base 16,17,18,etc )

      z1 and z2 is the result of addition of x and y number in base b1 and b2 number system respectively . 

      If z1 and z2 are similar then answer is "yes" else "No".

       

      0<= x < 2100

      0<= y < 2100

      1<= b1 < 100

      1<= b2 < 100

       

      Your task is to write the program to solve the problem of Nikhil.

       

      Input

      The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing four integers x,y  (0 <= x,y <= 2^100) and b1,b2 (1 <=b1,b2<= 100).

       

      Output

       

      Your program should print one line of output for each test case. Output can either be "yes" or "no" .

      Example

      Input:
      
      3
      10 01 2 10
      11 11 2 10
      12 12 8 10
      Output:

      yes
      no
      yes

      Added by:om
      Date:2011-07-24
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:inspired from interesting character of nikhil :)









      SPOJ Problem Set (classical)

      9242. B Beware, the end of the world

      Problem code: AHORCADO


      The end of the world always has been a subject of controversy thru history, for example, in year 999 and in the 1999. Now there are persons that believe that the mayan predicted a change in 2012, specifically in 21st december, 2012, some other speculate that the EoW will come with certain asteroid crashing onto Earth, or that planetary aligning has something to do with it....

      At ACM(Association of Catastrophe Mitigation) they are 100% sure that the end might come with a Zombie Apocalypsis, accordingly they are preparing with a Zombie Detection Mechanism, that it is some sort of radar. Right now the mechanism is on beta testing because is having errors identifying zombies. Sometimes it gives false positives measures. They have asked you, a wonderful programmer, to make a program that tells them if a lecture is right or not, basically you will be given two 2-D snapshots of zombies locations, let's call them the previous and the present snapshots, the zombies will be represented by a '*', while empty spaces will be represented by '.', your awesome program must tell if the present snapshot is a valid one, based on the previous one. A present snapshot is considered valid if:

      1) It has no less zombies than the previous snapshot.

      2) Every zombie in the previous snapshot could have moved only one square in each of the eight directions, or it is in the same square it was previously.

      Input

      The first line will have the dimensions of the snapshots, in the form of R C.

      2 ≤ R,C ≤ 20

      Then R lines of C characters follow, describing the previous snapshot, then another set of R lines and C characters each line, that belongs to the present snapshot. The two snapshots are separated by a line with the character 'N'.

      The last test case is followed by 0 0.

      There will be at most 9 zombies in previous snapshot.

      Output

      For each test case print VALID, if the two snapshots correspond each other, NOT VALID otherwise.

       

      Example

      Input:
      5 4
      ....
      ....
      .*..
      ....
      ....
      N
      ....
      ....
      ..*.
      ....
      ....
      6 6
      ......
      .*..*.
      ......
      ......
      ......
      ......
      N
      ......
      ....*.
      ......
      ....*.
      ......
      ..*...
      0 0

      Output:

      VALID
      NOT VALID


      Added by:Olson Ortiz
      Date:2011-07-27
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Used in 3ra Olimpiada de Programación PUCMM-ACM-ISC in december/2012









      SPOJ Problem Set (classical)

      9255. Publication

      Problem code: PUBLICAT

      The Orizondo number is a way of describing the "collaborative distance" between a scientist and Rodrigo Orizondo by authorship of scientific publications.

      Rodrigo Orizondo is the only person who has an Orizondo number equal to zero. To be assigned a finite Orizondo number, a scientist must publish a paper in co-authorship with a scientist with a finite Orizondo number. The Orizondo number of a scientist is the lowest Orizondo number of his coauthors + 1. The order of publications and numbers assignment doesn't matter, i.e., after each publication the list of assigned numbers is updated accordingly.

      You will be given the publications, each element of which describes the list of authors of a single publication and is formatted as "AUTHOR_1 AUTHOR_2 ... AUTHOR_N" (quotes for clarity only). Rodrigo Orizondo will be given as "ORIZONDO".

      Print out the list of Orizondo numbers which will be assigned to the authors of the listed publications. Each element of the printout should be formatted as "AUTHOR NUMBER" if AUTHOR can be assigned a finite Orizondo number, and just "AUTHOR" otherwise. The authors in the printout list must be ordered lexicographically.

      Input

      The first line of the input gives the number of test cases C (0 < C ≤ 10,000).

      Each test case starts with an integer N, the number of publications, then N publications follow. Each publication consists in a space separated list of authors.(each publication in a single line).

      Notes

      - All authors mentioned in the list must be present in output.
      - Assume that all publications of mentioned authors are given in publications.
      - String S is lexicographically before string T if S is a proper prefix of T, or if S has an earlier character at the first position where the strings differ.
       

      Constraints

      - publications will contain between 1 and 50 elements, inclusive.
      - Each element of publications will contain between 1 and 50 characters, inclusive.
      - An author is a string of between 1 and 50 uppercase letters ('A'-'Z'), inclusive.
      - Each element of publications will be a list of authors, separated by single spaces.
      - Each element of publications will not have any trailing spaces.
      - The authors in each element of publication will be distinct.
      - There will be at most 100 distinct authors in all publications.
      - Rodrigo Orizondo will be given as "ORIZONDO", and at least one publication will list him as one of the authors.

      Output

      For each test case, output one line containing each author with his Orizondo Number, all space separated.

      Example

      Input:
      3
      1
      ORIZONDO
      2
      KLEITMAN LANDER
      ORIZONDO KLEITMAN
      4
      ORIZONDO B
      A B C
      B A E
      D F


      Output:
      ORIZONDO 0
      KLEITMAN 1 LANDER 2 ORIZONDO 0
      A 2 B 1 C 2 D E 2 F ORIZONDO 0

      Added by:Olson Ortiz
      Date:2011-07-28
      Time limit:1s-64s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:AWK C C# C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n SED









      SPOJ Problem Set (classical)

      9260. Perfect Road

      Problem code: PERFECTR

         Byteland is a ficticious city commonly mentioned here on SPOJ.

         An ancient legend tells that bytelandians lived in a simple town, just like the Old Western California, where there was just a single straight road of about 500 Meters and all houses, bars and hotel had the road in front of them. In Byteland, although there is a small difference, here, including the Main Road, each house has its own road that connects to the main road, but according to the law, each particular road need to be perpendicular to the main road.

         So their world can be abstracted as a two-dimensional grid with integer coordinates. The main road is the x-axis and houses are points connected perpendicularly to the x-axis (in both the positive and negative y directions).

         In this particular city, if a person A needs to visit any other person B, he needs to walk along the street that connects his home to the main road until it reaches the main road, then walk through the main road up to the street that comes from the other home, and then walk this street to B's home. But in the case their homes are in the same street, they only need to walk the segment that connects their houses.

         The distance between two persons home is defined as:

      1)If two homes have the same 'x' coordinate. The distance between them is the absolute difference between their 'y' coordinates. (this is the case where they live in the same street)

      2)Otherwise, the distance is the distance between Person A and the main road + the distance between Person B and the main road + the absolute difference between their 'x' coordinates.

      Here are 3 persons, one at (1,1), other at (1,4), and the last one at (4,1). This is the first example.


         
         

       

         The government is about to make a bold decision that will make the lives of the bytelandians easier. They will minimize the maximum distance between any pair of persons by moving the main road to a horizontal line y = N, where N is an integer. If the main road is already at the optimal position, it will not be moved.

         You will be given the 'x' and 'y' coordinates of the houses, print the maximum distance between any pair of persons after the main road is moved to the optimal position.

      Input

      The first line is T (3 ≤ T ≤ 1,000), the number of test cases, then T test cases follows.

      Each test case starts with N (2 ≤ N ≤ 50), the number of persons in byteland.

      then N lines, each one with two integers separated by a space.

      Each one of these integers is the x and y coordinates, respectively, of a bytelandian home.

      Constraints:

      -The absolute value of each x and y coordinate will be between 0 and 109, inclusive.

      Output

      For each test case print out the required distance in a single line.

      Example

      Input:
      3
      3
      1 4
      4 1
      1 1
      5
      -1 -1
      -2 3
      -1 -3
      0 0
      2 3
      4
      1 1
      1 10
      1 100
      1 1000

      Output:
      6
      9
      999
      The government is about to make a bold decision that will make the lives of the monkeys easier. They will minimize the maximum distance between any pair of monkeys by moving the ground to a horizontal line y = N, where N is an integer. If the ground is already at the optimal position, it will not be moved.

      Added by:Olson Ortiz
      Date:2011-07-30
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:AWK C C# C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n SED
      Resource:Used in 2nd PUCMM-ACM-ISC Programming Olympiad phase1 (2011)









      SPOJ Problem Set (classical)

      9331. DCD

      Problem code: DCD

      Once upon a time, there was a secret group of boys. People used to call them 'Dushtu Cheler Dol' (Gang of Naughty boys) or DCD in short. Members of DCD were very good at making fool of people.

      Suppose, you are a member of DCD and you want to borrow money from N people ( you are definitely not going to return the money because that will go against the values of DCD ). Some of  the N people will not lend you money as they know about DCD. But at first you don't know how many of them know about it. Then there are M members of DCD who want to borrow money from you. As you know none of the M people will return your money, you will try to escape from them when they will ask you for money, but you are not sure of being able to escape. Failure of escaping means, you must give them the money they want. So, before starting you wanted to determined how much money you will have after the whole process. As many solutions are possible, you will determine an interval, which contains the maximum number of possible solutions. The difference between the starting point and ending point will be of definite size (given in the input).

      Input

      Test cases start with two integers N and M. Next, there will be N integers in the same or different lines where [0<=Ni<=1015] is the amount of money you will borrow form ith person. Then there will be M integers in the same or different lines, where [0<=Mi<=1015] is the amount of money ith DCD member will ask for.  (N+M)<=17. Then you will be given an integer D [1<=D<=1015], the difference between the starting point and ending point of the desired interval.

      There will be at most 200 test cases.

      Output

      For each test case, you have to print three integers S,T and E. S and T are the endpoints of an interval of difference D, (S<=T). E is the number of solutions between S and T(inclusive).

      If there are several solutions, print the interval where S itself is a possible solution. If still there are several solutions, print the interval having minimum value of S.

       

      Note : 1. Same money values achieved by different ways are considered different.
      2. If you can't escape, you will have to pay money even if you have zero or less money left. Then your amount will be considered negative.
      3. If the starting value of the interval is X, the ending value will be X+D-1.

       

      Example

      Input:
      2 0
      1 2
      1
      4 1
      5 6 9 9
      2
      5

      Output:
      0 0 1
      11 15 9


      Added by:Bidhan Roy ( বিধান )
      Date:2011-08-06
      Time limit:1s-35s
      Source limit:20000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own, Alternate Writer: Hasnain Heickal Jami









      SPOJ Problem Set (classical)

      9334. Point in tetrahedron

      Problem code: TETRAHED

      There're given 5 points in 3D coordinates (integers 0<=x,y,z<100). Their order is arbitrary. 4 of them are the vertices of a tetrahedron whose edges can be of different size. One is lying in this tetrahedron. Find its index (1-5) in the array of points.

      Input

      In the first line the number T (T<1000) of test cases.
      Then for each test case 5 lines with the space separated x-, y- and z-coordinates of the 5 points.

      Output

      For each test case a line with the index of that point which is lying in the tetrahedron formed of the 4 other points.

      Example

      Input:
      1
      5 72 66
      92 23 68
      60 60 49
      74 78 33
      67 76 27 Output: 3

      Added by:HWK
      Date:2011-08-07
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9340. Arbitrage

      Problem code: ARBITRAG

      Arbitrage is the use of discrepancies in currency exchange rates to transform one unit of a currency into more than one unit of the same currency. For example, suppose that 1 US Dollar buys 0.5 British pounds, 1 British pound buys 10.0 French francs, and 1 French franc buys 0.21 US dollars. Then, by converting currencies, a clever trader can start with 1 US dollar and buy 0.5 * 10.0 * 0.21 = 1.05 US dollars, making a profit of 5 percent.

      Your job is to write a program that takes a list of currency exchange rates as input and then determines whether arbitrage is possible or not.

      Input

      The input file will contain one or more test cases. On the first line of each test case there is an integer n (1<=n<=30), representing the number of different currencies. The next n lines each contain the name of one currency. Within a name no spaces will appear. The next line contains one integer m, representing the length of the table to follow. The last m lines each contain the name ci of a source currency, a real number rij which represents the exchange rate from ci to cj and a name cj of the destination currency. Exchanges which do not appear in the table are impossible.
      Test cases are separated from each other by a blank line. Input is terminated by a value of zero (0) for n.

      Output

      For each test case, print one line telling whether arbitrage is possible or not in the format "Case case: Yes", respectively "Case case: No". 

      Example

      Input:
      
      3
      USDollar
      BritishPound
      FrenchFranc
      3
      USDollar 0.5 BritishPound
      BritishPound 10.0 FrenchFranc
      FrenchFranc 0.21 USDollar
      
      3
      USDollar
      BritishPound
      FrenchFranc
      6
      USDollar 0.5 BritishPound
      USDollar 4.9 FrenchFranc
      BritishPound 10.0 FrenchFranc
      BritishPound 1.99 USDollar
      FrenchFranc 0.09 BritishPound
      FrenchFranc 0.19 USDollar
      
      0
      Output:
      Case 1: Yes
      Case 2: No

      Added by:Vincenzo Bonifaci
      Date:2011-08-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:University of Ulm Local Contest 1996









      SPOJ Problem Set (classical)

      9367. Segment Flip

      Problem code: SFLIP

      You are given N number a1, a2, ... , aN. In a segment flip, you can pick a contiguous segment ai, ai+1, ... , aj of these numbers, where i<=j and negate all the numbers in this segment. 

      You are permitted atmost K segment flip operations overall. Also, no 2 segments that you pick can overlap. That is, if you flip ai, ... , aj and ak, ... , al then either j<k or l<i.

      Your aim is to maximize the sum of all the numbers in the resulting sequence by applying appropriate segment flip operations meeting these constraints.

      For instance, suppose the sequence is -5, 2, -3 and you are allowed a single segment flip. The best sum you can achieve is 6, by flipping all 3 numbers as a single segment to 5, -2, 3.

      Your aim is to maximize the sum of all the numbers in the sequence by applying appro-
      priate segment 

      ips meeting these constraints.

      For instance, suppose the sequence is -5, 2, -3 and you are allowed a single segment flip. The best sum you can achieve is 6, by flipping all three numbers as a single segment to 5, -2, 3.

      Input

      The first line contains 2 integers N and K. The next line contains N integers, the initial values of a1, a2, ... , aN.

      Output

      A single integer denoting the maximum possible sum of the final array.

       

      Constraints

      0 <= K <= N

      -10000 <= ai <= 10000

      1 <= N <= 100000

       

      Example

      Input:
      3 1
      -5 2 -3
      
      Output:
      6

      Added by:jack(chakradarraju)
      Date:2011-08-10
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Proposed by venkateshb









      SPOJ Problem Set (classical)

      9378. Landfill

      Problem code: LANDFILL

      You are given a sequence H[1], H[2], ... , H[N] representing the initial heights of N pieces of land and an integer K. It costs C[i] Rupees to elevate each of H[i], H[i+1], ... , H[i+K-1] by E[i]; if i+K > N, it will just elevate all the pieces of land from A[i] to A[N] - Let us call this an operation. The following constraints must be satisfied:

      1) For each i, the operation can be performed atmost once.

      2) The sum of the costs of all the operations performed must be <= Budget.

      You have to calculate the maximum height V such that each plot's elevation is atleast V before you exhaust the budget.

      Input

      The first line of input contains 3 integers N, Budget and K.

      The next N lines consists of 3 integers H[i], E[i] and C[i].

      Output

      Output a single integer V such that all the plots have atleast height V.

      Constraints

      1 <= K <= 11

      1 <= N <= 100

      0 <= Budget, H[i], E[i], C[i] <= 1000000

      Example

      Input:
      4 20 1
      1 3 5
      1 7 3
      4 6 9
      3 5 13
      
      Output:
      3
      Explanation:

      You can raise the level of the (unit) segments 1, 2 and 3, yielding a sequence of final heights 4, 8, 10 and 3. The minimum height among these is 3.


      Added by:jack(chakradarraju)
      Date:2011-08-12
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Proposed by Anudhyan









      SPOJ Problem Set ()

      9382. Complan Carnival

      Problem code: CARNIVAL


       

      Peet is very excited because he is visiting a carnival for the first time in his life! As luck would have it, the carnival he is visiting today happens to be the largest one in the galaxy. It is known throughout the universe for its gigantic and super-fast anti-gravity Ferris wheels.
      Peet is looking forward to riding as many rides as he can. Each of the rides cost a certain about of money. He has brought only a limited amount of money. Peet was starting to worry. However, to complicate matters even more, each of the rides have a height requirement: one has to be at least a certain height to be allowed to ride it. Peet is pretty short for his species, and he isn't tall enough to ride most of the rides!
      There is still hope. Since he paid attention at his biophysics classes at school, Peet realises that because of centrifugal force, the super-fast anti-gravity ferries wheels will actually increase his height when he rides them! 
      The carnival contains N rides. Peet initially has M intergalactic dollars with him and his height is initially H feet. For each ride i (1 <= i <= N), Peet has to pay m[i] intergalactic dollars and his height has to be at least t[i] feet.  Peet has calculated that his height would increase by h[i] feet after riding the ith ride. Help him find the maximum number of rides he can ride at the carnival.

      Peet is very excited because he is visiting a carnival for the first time in his life! As luck would have it, the carnival he is visiting today happens to be the largest one in the galaxy. It is known throughout the universe for its gigantic and super-fast anti-gravity Ferris wheels.

      Peet is looking forward to riding as many rides as he can. Each of the rides cost a certain about of money. He has brought only a limited amount of money. Peet was starting to worry. However, to complicate matters even more, each of the rides have a height requirement: one has to be at least a certain height to be allowed to ride it. Peet is pretty short for his species, and he isn't tall enough to ride most of the rides!

      There is still hope. Since he paid attention at his biophysics classes at school, Peet realises that because of centrifugal force, the super-fast anti-gravity ferries wheels will actually increase his height when he rides them! 

      The carnival contains N rides. Peet initially has M intergalactic dollars with him and his height is initially H feet. For each ride i (1 <= i <= N), Peet has to pay m[i] intergalactic dollars and his height has to be at least t[i] feet.  Peet has calculated that his height would increase by h[i] feet after riding the ith ride. Help him find the maximum number of rides he can ride at the carnival.

       

      Input

      The first line contains 3 integers N, M and H.

      The next N lines contain 3 integers each. The (i+1)th line contains integers t[i], m[i] and h[i].

      Output

      Print a single integer - the maximum number of rides Peet can take at the carnival.

      Constraints

      1 <= N <= 100

      0 <= m[i] <= M <= 1000

      0 <= t[i], h[i], H <= 10^7

      Example

      Input:
      5 10 1
      3 4 5
      10 1 3
      2 4 0
      1 10 7
      1 2 2
      
      Output:
      3
      Explanation:

      Peet can take ride 5, spending 2 intergalactic dollars and increasing his height from 1 to 3. Now that he has at least height 3, he can take ride 1. He spends 4 more dollars and his height increases to 8. Finally, he can use the remaining 4 dollars to take ride 3. He cannot take any more rides since he has run out of money. You can check that Peet cannot ride more than 3 rides in this example.


      Added by:jack(chakradarraju)
      Date:2011-08-12
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Proposed by Anudhyan









      SPOJ Problem Set (classical)

      9385. Strictly not a Prime

      Problem code: MAIN111

      Tim defines an integer as "Strictly not a Prime", if no subsequence(considering the integer as a string of digits) of the integer is a prime. He needs your help in finding how many such integers are present between two given integers A and B(including A and B).

      Input

      First line contains an integer T(1 <= T <= 100000) which denotes the total number test cases. Each test case consists of two integers A and B (1 <= A, B <= 100000) on a single line.

      Output

      For each test case, print the total count of integers which are "Strictly not a prime" between A and B(including A and B) as per tim.

      Example

      Input:
      2
      3 6
      7 10
      Output:
      2
      
      3

      Added by:amit karmakar
      Date:2011-08-15
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used in - http://www.spoj.pl/MAIN11/









      SPOJ Problem Set (main)

      9386. Re-Arrange II

      Problem code: MAIN112

      For a sequence of N integers, A1, A2, ..... AN

      We can calculate the stability factor P, as

      P = sum of all (abs(Ai-Ai-1)*C[i]) where 2 <= i <= N

      C[i] is the cost of putting a number at position i

      Your task is find the minimum P for the given N numbers considering all the different permutations of them.

      Input

      First line contains an integer T(1<=T<=10) which denotes the total number of test cases. Each test case consists of three lines.

      The first line contains the integer N(1<=N<=15). The second line contains a space separated list of N integers(<150) which denote the given set of numbers.

      The third line contains a space separated list of N integers. The ith integer on this line denotes the value for C[i](1 <= C[i] < 150)

      Output

      For each test case, print the minimum possible value of P considering all permutations of the given numbers.

      Example

      Input:
      1
      5
      1 8 3 6 5
      1 2 3 4 5
      
      Output
      24
      

      One of the possible permutation of given numbers which has p = 24 is 1, 3, 5, 6, 8


      Added by:amit karmakar
      Date:2011-08-15
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK NODEJS PYTH 3.2.3 n SED
      Resource:own problem used in - http://www.spoj.pl/MAIN11/









      SPOJ Problem Set (classical)

      9387. Special String

      Problem code: MAIN113

      A string of letters X, Y, Z is special if there are three consecutive letters from which one is X, one is Y, and one is Z. For example, XYZXYZ is special, while XXYYZ is not. Your task is to calculate how many such strings of length n are not special.

      Input

      First line contains an integer T(1 <= T <= 30) which denotes the total number of test cases. Each test case contains an integer N(1 <= N <= 30) in a single line.

      Output

      For each test case print total number of strings which have a length N and are not special.

      Example

      Input:
      1
      2
      
      Output:
      9
      

      Added by:amit karmakar
      Date:2011-08-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9392. Play With Sequence

      Problem code: PS11A


      You are given a sequence A[1], A[2],..., A[N]. On this sequence you have to apply M operations: Add all the elements whose value are in range [l, r] by d or, ask for a query how many element are in range [l, r].

      Input

      There are only one case in each input file, process until the end of the file. The first line of each case contains two numbers, N, M, described as above. And then start from the second line, have N numbers described the sequence's initial value.

      ( 1≤ N ≤ 250,000, M ≤ 50,000), |A[i]| ≤ 1,000,000,000 .)

      The following M lines described the operation:

      • C l r d: Add all the element whose value are in range [l, r] by d. (Redeclare: Not its Position! .. )
      • Q l r: ask for a query how many elements, whose value are in range [l, r].

      (l ≤ r, |l|、|r|、|d|≤ 1,000,000,000. notes [l, r] are closed interval, i.e not less than l and not greater than r. )

      We guarantee every elements are suits 32-integer, and will not cause overflow, even during the running-time. (.. but still be careful ;) Besides, all the test-data are generated randomly.

      Output

      For each query, print the result.

      Example

      Input 1:
      10 3
      1 2 3 4 5 6 7 8 9 10
      C 6 10 5
      C 1 5 -5
      Q 1 10

      Output 1:
      0

      Input 2:
      10 10
      10 4 -5 8 8 3 0 -2 4 7
      C -9 8 2
      C -4 10 -3
      C -10 0 5
      Q -9 -1
      C -9 -5 8
      C -7 4 3
      Q -2 7
      C -10 -3 2
      C -4 -1 -6
      Q 7 10

      Output 2:

      1
      10
      4

      (In the first example, after the two operations, the sequences are become to,
      {-4, -3, -2, -1, 0, 11, 12, 13, 14, 15}, so there are no elements whose value are in range [1, 10]. )

      Warning: large input/output data,be careful with certain languages

      Added by:xiaodao
      Date:2011-08-16
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.0.0-8
      Resource:Own problem, 2011 Multi-University Training Contest 11 - Host by HIT









      SPOJ Problem Set (classical)

      9430. The game of 31

      Problem code: GAME31

       

      is played with a deck of 24 cards: four labelled each of 1, 2, 3, 4, 5, 6. The cards in the deck are
      visible to both players, who alternately withdraw one card from the deck and place it on a pile.
      The object of the game is to be the last player to lay a card such that the sum of the cards in
      the pile does not exceed 31. Your task is to determine the eventual winner of a partially played
      game, assuming each player plays the remainder of the game using a perfect strategy.
      For example, in the following game player B wins:
      Player A plays 3
      Player B plays 5
      Player A plays 6
      Player B plays 6
      Player A plays 5
      Player B plays 6
      Input:
      The input will consist of several lines; each line consists of a sequence of zero or more digits
      representing a partially completed game. The rst digit is player A's move; the second player
      B's move; and so on. You are to complete the game using a perfect strategy for both players
      and to determine who wins.
      Output:
      For each game, print a line consisting of the input, followed by a space, followed by A or B to
      indicate the eventual winner of the game.
      Example Input:
      356656
      35665
      3566
      111126666
      552525
      Example Output:
      356656 B
      35665 B
      3566 A
      111126666 A
      552525 A

      The game of 31 was a favourite of con artists who rode the railroads in days of yore. The game

      is played with a deck of 24 cards: four labelled each of 1, 2, 3, 4, 5, 6. The cards in the deck are

      visible to both players, who alternately withdraw one card from the deck and place it on a pile.

      The object of the game is to be the last player to lay a card such that the sum of the cards in

      the pile does not exceed 31. Your task is to determine the eventual winner of a partially played

      game, assuming each player plays the remainder of the game using a perfect strategy.

      For example, in the following game player B wins:

      Player A plays 3

      Player B plays 5

      Player A plays 6

      Player B plays 6

      Player A plays 5

      Player B plays 6

      Input:

      The input will consist of several lines; each line consists of a sequence of zero or more digits

      representing a partially completed game. The rst digit is player A's move; the second player

      B's move; and so on. You are to complete the game using a perfect strategy for both players

      and to determine who wins.

      Output:

      For each game, print a line consisting of the input, followed by a space, followed by A or B to

      indicate the eventual winner of the game.

      Example Input:

      356656

      35665

      3566

      111126666

      552525

      Example Output:

      356656 B

      35665 B

      3566 A

      111126666 A

      552525 A

       

       


      Added by:Andres Tellez
      Date:2011-08-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9433. Buzzwords

      Problem code: BUZZW

       

      Question C - Buzzwords
      The word the is the most common three-letter word. It even shows up inside other words, such as "other" and "mathematics". Sometimes it hides, split between two words, such as "not here". Have you ever wondered what the most common words of lengths other than three are?
      Your task is the following. You will be given a text. In this text, find the most common word of length one. If there are multiple such words, any one will do. Then count how many times this most common word appears in the text. If it appears more than once, output how many times it appears. Then repeat the process with words of length 2, 3, and so on, until you reach such a length that there is no longer any repeated word of that length in the text.
      Input:
      The input consists of a sequence of lines. The last line of input is empty and should not be processed. Each line of input other than the last contains at least one but no more than one thousand uppercase letters and spaces. The spaces are irrelevant and should be ignored.
      Output:
      For each line of input, output a sequence of lines, giving the number of repetitions of words of length 1, 2, 3, and so on. When you reach a length such that there are no repeated words of that length, output one blank line, do not output anything further for that input line, and move on to the next line of input.
      Example Input:
      OTHER MATHEMATICS NOT HERE
      AA
      Note that the last line of the sample input is a blank line.
      Example Output:
      5
      4
      4
      2
      2
      2
      Note that the last line of the sample output is a blank line.

       

      The word the is the most common three-letter word. It even shows up inside other words, such as "other" and "mathematics". Sometimes it hides, split between two words, such as "not here". Have you ever wondered what the most common words of lengths other than three are?

      Your task is the following. You will be given a text. In this text, find the most common word of length one. If there are multiple such words, any one will do. Then count how many times this most common word appears in the text. If it appears more than once, output how many times it appears. Then repeat the process with words of length 2, 3, and so on, until you reach such a length that there is no longer any repeated word of that length in the text.

      Input:

      The input consists of a sequence of lines. The last line of input is empty and should not be processed. Each line of input other than the last contains at least one but no more than one thousand uppercase letters and spaces. The spaces are irrelevant and should be ignored.

      Output:

      For each line of input, output a sequence of lines, giving the number of repetitions of words of length 1, 2, 3, and so on. When you reach a length such that there are no repeated words of that length, output one blank line, do not output anything further for that input line, and move on to the next line of input.

      Example Input:

      OTHER MATHEMATICS NOT HERE

      AA

      Note that the last line of the sample input is a blank line.

      Example Output:

      5

      4

      4

      2

      2

      2

      Note that the last line of the sample output is a blank line.

       

       


      Added by:Andres Tellez
      Date:2011-08-23
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9434. New Horizons

      Problem code: NEWH

       

      Question E - New Horizons
      I’m king of a house! And, what’s more, beyond that,
      I’m king of a blueberry bush and a cat!
      I’m Yertle the Turtle! Oh, marvelous me!
      For I am the ruler of all that I see!"
      Yertle has determined that the number of objects he can see, and hence rule, depends on the height of his throne. Your task, as Minister of Computing and Vertigo (a new combined Super Ministry), is to determine which objects Yertle would see should he build his throne to a particular height.
      Input:
      Standard input consists of:
       A floating point number on a line by itself, specifying the diameter of Yertle’s planet in "flipper lengths".
       A line containing three floating point numbers: the height of Yertle’s throne (in flipper lengths), the latitude of Yertle’s throne (between -90 and +90 degrees), the longitude of Yertle’s throne (between 0 and 360 degrees).
       Several lines, each containing three floating point numbers and a string of alphabetic and space characters. Each line indicates the height, latitude, longitude and name of an object on the surface of Yertle’s planet. The last line is indicated by the end of standard input.
      All distances are in flipper lengths, and all latitudes and longitudes are in degrees. Floating point values are formatted as a string of decimal digits with an optional decimal point and sign. The fields in the input are separated by exactly one space character. You may assume that no object hides another; only the horizon limits Yertle’s view.
      Output:
      Standard output consists of the list of objects whose tops are visible to Yertle, in alphabetical order.
      Example Input:
      20000.0
      100.0 45.0 100.0
      2.0 46.0 99.0 Cat
      20.0 -45.0 260.0 House
      5.0 45.1 100.2 Blueberry Bush
      Example Output:
      Blueberry Bush
      Cat

       

       

      I’m king of a house! And, what’s more, beyond that,

      I’m king of a blueberry bush and a cat!

      I’m Yertle the Turtle! Oh, marvelous me!

      For I am the ruler of all that I see!"

      Yertle has determined that the number of objects he can see, and hence rule, depends on the height of his throne. Your task, as Minister of Computing and Vertigo (a new combined Super Ministry), is to determine which objects Yertle would see should he build his throne to a particular height.

      Input:

      Standard input consists of:

       A floating point number on a line by itself, specifying the diameter of Yertle’s planet in "flipper lengths".

       A line containing three floating point numbers: the height of Yertle’s throne (in flipper lengths), the latitude of Yertle’s throne (between -90 and +90 degrees), the longitude of Yertle’s throne (between 0 and 360 degrees).

       Several lines, each containing three floating point numbers and a string of alphabetic and space characters. Each line indicates the height, latitude, longitude and name of an object on the surface of Yertle’s planet. The last line is indicated by the end of standard input.

      All distances are in flipper lengths, and all latitudes and longitudes are in degrees. Floating point values are formatted as a string of decimal digits with an optional decimal point and sign. The fields in the input are separated by exactly one space character. You may assume that no object hides another; only the horizon limits Yertle’s view.

      Output:

      Standard output consists of the list of objects whose tops are visible to Yertle, in alphabetical order.

      Example Input:

      20000.0

      100.0 45.0 100.0

      2.0 46.0 99.0 Cat

      20.0 -45.0 260.0 House

      5.0 45.1 100.2 Blueberry Bush

      Example Output:

      Blueberry Bush

      Cat

       

       


      Added by:Andres Tellez
      Date:2011-08-23
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set ()

      9440. To Add or to Multiply

      Problem code: ADDMUL

      The Industrial Computer Processor Company offers very fast, special purpose processing units tailored to customer needs. Processors of the a-C-m family (such as the 1-C-2 and the 5-C-3) have an instruction set with only two different operations:

      A add a

      M multiply by m

      The processor receives an integer, executes a sequence of A and M operations (the program) that modifies the input, and outputs the result. For example, the 1-C-2 processor executing the program AAAM with the input 2 yields the output 10 (the computation is 2 → 3 → 4 → 5 → 10), while the 5-C-3 processor yields 51 with the same program and input (2→ 7 → 12 → 17 → 51).

      You are an a-C-m programmer assigned to a top secret project. This means that you have not been told the precise computation your program should perform. But you are given particular values p, q, r, and s and the following conditions:

      1. The input is guaranteed to be a number between p and q.

      2. The output must be some number between r and s.

      Given an a-C-m processor and the numbers p, q, r, and s, your job is to construct the shortest a-C-m program which, for every input x such that pxq, yields some output y such that rys. If there is more than one program of minimum length, choose the one that come first lexicographically, treating each program as a string of As and Ms.

      Input

      The input contains several test cases. Each test case is given by a line with the six integers a, m, p, q, r, and s as described above (1 ≤ a, m, p, q, r, s ≤ 109, pq and rs).

      The last test case is followed by a line with six zeros.

      Output

      For each test case, display its case number followed by the best program as described above. Display the word “empty” if the best program uses no operations. Display the word “impossible” if there is no program meeting the specifications.

      Display the program as a sequence of space-separated strings, alternating between strings of the form “nA” and strings of the form “nM”, where n > 0. Strings of the former type indicate n consecutive A operations, and strings of the latter type indicate n consecutive M operations.

      Follow the format of the sample output.

      Example

      Input:
      1 2 2 3 10 20
      1 3 2 3 22 33
      3 2 2 3 4 5
      5 3 2 3 2 3
      0 0 0 0 0 0
      Output:
      Case 1: 1A 2M
      Case 2: 1M 2A 1M
      Case 3: impossible
      Case 4: empty

      Added by:John Mario
      Date:2011-08-24
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: BF WSPC
      Resource:ACM ICPC 2011 World Finals









      SPOJ Problem Set (classical)

      9443. Trial of Doom

      Problem code: YALOP

      Johnny has reached the final trial on the Path of Doom. This is the hardest one. He entered a large room. The floor of the room is divided into square cells of the same size. There are n rows and m columns of cells. Each cell can be either red or blue. We can consider that the walls of the room are parallel south-north direction and west-east direction and that Johnny has entered the room in the north-western corner. So now he is standing in the north-western cell of the room. The exit is in the south-eastern corner. Johnny can make steps in each of the eight directions moving to adjacent cells. He has to reach the exit. But when he goes out of the room all the cells in the room should be blue, otherwise he fails the trial (If Johnny goes out he can't step back again). The colors of the cells change after each step Johnny makes. When he steps on the next cell this cell and the cells to its north, south, east and west change color: from blue to red and from red to blue. Johnny can't ever step on two cells at once or he fails the trial. Also just jumping on the cell he is standing on now will have no effect on the color of cells. Currently some cells in the room may be red. Johnny made a look over the room and he wonders if it's even possible to pass the trial at all or the trial master is playing a trick on him. Help him find this out.

      Input

      The first line of input is the number of test cases. Then each of the test cases follows. The test case starts with two number n and m - the sizes of the room. The next line contains number k - the amount of red cells in the room. Next k lines consist of two numbers each x, y - the row number and column number of the following red cell. The rows are numbered from 1 to n from north to south and columns are numbered from 1 to m from west to east. So Johnny starts at cell (1, 1) and have to reach cell (n, m). The coordinates of all of the red cells will be different. The rest of the cells are blue.

      Constraints

      1 <= t <= 50
      1 <= n, m <= 109
      min(n, m) < 40
      0 <= k <= min(m*n, 10000)
      1 <= x <= n
      1 <= y <= m

      Output

      For each test case print "YES" (quotes for clarity) if Johnny can reach the south-eastern cell and go out of the room with all cells being blue and "NO" (quotes for clarity) otherwise.

      Example

      Input:
      3
      2 2
      0
      2 2
      4
      1 1
      1 2
      2 1
      2 2
      4 4
      1
      1 1
      
      Output:
      YES
      YES
      NO
      
      

      Explanation

      In the first test case Johnny can pass the trial making the following steps: South-east, North, West, East, West, South-east, out. In the second test case: East, West, South, East, out. It's impossible to pass the trial in the third test case.


      Added by:Spooky
      Date:2011-08-24
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeChef July 2011 Long contest









      SPOJ Problem Set (classical)

      9444. Block Drop

      Problem code: BLOCKDRO

      There is a square pool divided into NxM cells. In some cells of the pool there stone islands. Each island consists of some number of stones. Let's call this number the height of the island. You can jump from the island with coordinated (x,y) to any island with coordinates (x+1,y), (x+2,y), (x-1,y), (x-2,y), (x,y+1), (x,y+2), (x,y-1), (x,y-2). When you jump off the island its height goes down by one. If the height of any island becomes 0 it goes under water and you can't jump on it any more. You start on island with coordinates (sx, sy). The goal is to make all the islands (except the final one) go under water and finish on the island with coordinates (fx, fy) which should have height equal to 1 when you finish on it. You task is to count the number of different ways to achieve the goal.

      Input

      The first line of input file contains number t - the number of test cases (no more than 5 for each file). Then the description of each test case follows. The first line of each test case contains numbers N and M. The next line contains two coordinates sx and sy of the start cell. After that there are two coordinates fx and fy of the finishing cell. Then N lines follow each consisting of M integers denoting the heights of the islands in each cell of the pool. The height 0 means that there is no island in the cell. Note also that each test case in the official tests will be generated by the following procedure. The dimensions of the pool will be chosen randomly and uniformly: N and M will be from 3 to 8 inclusive. Then the final cell will be chosen randomly: fx will be from 1 to N and fy will be from 1 to M. The height of island in the cell (fx, fy) will be set to 1. Then the number of jumps will chosen randomly from 15 to 25. Then this many random valid jumps will be performed adding one stone to the cell the jumps lands on. The cell on which we land after performing all the jumps will be proclaimed as the initial cell: (sx, sy).

      Output

      For each test case print the total number of different ways to solve the task.

      Example

      Input:
      1
      3 3
      3 1
      3 1
      1 0 0
      3 1 1
      3 1 1
      
      Output:
      152
      
      

      Added by:Spooky
      Date:2011-08-24
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeChef August 2011 Long Contest









      SPOJ Problem Set (classical)

      9445. Attack of the Clones

      Problem code: CLONES

      A boolean function is a function of the form f: Bn -> B, where B = {0, 1} and n is a non-negative integer called the arity of the function. Some Boolean functions are projections: pnk(x1, ..., xn) = xk. And given an m-ary function f, and n-ary functions g1, ..., gm, we can construct another n-ary function: h(x1, ..., xn) = f(g1(x1, ..., xn), ..., gm(x1, ..., xn)), called their composition. A set of functions closed under composition and containing all projections is called a clone. One trivial clone is a set of all boolean functions. Some of the special clones are:

      • Z is a set of 0-preserving functions: f(0, ..., 0) = 0;
      • P is a set of 1-preserving functions: f(1, ..., 1) = 1;
      • D is a set of self-dual functions: !f(x1, ..., xn) = f(!x1, ..., !xn);
      • A is a set of affine functions: the functions satisfying that if f(a1, ..., c, ..., an) = f(a1, ..., d, ..., an) then f(b1, ..., c, ..., bn) = f(b1, ..., d, ..., bn), where c and d are at some position i. This should hold for every valid i, a1, ..., an, b1, ... bn, c and d.

      Now we are interested how many n-ary functions are there in some combinations of mentioned above sets. For example, for n = 2, there are exactly 8 functions in Z, 4 functions in the intersection of Z and P, 8 function in the complement of A and so on.

      Input

      The first line of the input file contains n - the arity of the boolean functions we are looking at. The second line contains the q - number of queries. Each of the next q lines will describe a query. The query is a set expression. The expression will contain the following characters: 'Z', 'P', 'D', 'A' denoting the sets, described above; 'v' - which is set union; '^' - which is set intersection; '!' which is complement; '\' which is set difference; and also '(' and ')' to define operations priority. Operations in brackets have higher priority. Otherwise the '!' operation has the higher priority and 'v', '^' and '\' are of the same priority. It is guaranteed that the expression will be correct. See samples for some examples of set expressions.

      Constraints

      1 <= n <= 100
      1 <= q <= 100
      The length of each expression won't exceed 100 characters.

      Output

      For each query in the input print how many n-ary function are in the set described by the according set expression modulo 1000003.

      Example

      Input:
      2
      6
      Z
      Z^P
      !A
      !(AvP)^D
      AvZvP\A
      !A^(Z\(Dv!P))
      
      Output:
      8
      4
      8
      0
      6
      2
      
      

      Added by:Spooky
      Date:2011-08-24
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeChef June 2011 Long Contest









      SPOJ Problem Set (classical)

      9446. Shortest Circuit Evaluation

      Problem code: SHORTCIR

      Short circuit evaluation of Boolean expressions denotes the semantic in which the second argument of some Boolean operator is not evaluated if the value of the first argument is enough to have the result. This technique is used in many programming languages to optimize the evaluation of Boolean expressions. Specifically for "A and B", if A is false we know that the whole expression is false and we don't need to evaluate B. For "A or B", if A is true we know the result to be true. Now having that those Boolean operations are commutative we may actually evaluate B first and not evaluate A in case B gives us the result. Moving the idea further if we have "A1 or A2 or...or An" we can evaluate the variables in any order and as soon as we have one of them as true we know that the whole expression is true. We can do similarly for and operation. Now let's consider some complex Boolean expression. We will fix the order in which we will evaluate the variables of the expression. Then we evaluate those variables in that order and we won't evaluate the variables that give us no new information about the value of the whole expression in the process. For example, assume we have "A and B or C" and we fix the order of evaluation B, A, C. First we evaluate B, if it's false we don't have to evaluate A and only evaluate C. However if B is true we will need to evaluate A. If A is true we know the expression is true and won't evaluate C, otherwise we evaluate C to have the value of the expression. Now your task is having some complex Boolean expression containing and, or, not operations and for each variable having the probability that this variable is true, you need to find the order of evaluation for which the expected number of evaluations in the process described above will be minimal.

      Input

      The first line of input file contains number t - the amount of test cases. Then t test cases follow. The first line of each test case will contain the Boolean expression. The expression will be valid and will consist of and, or, not operations, brackets and variable names. All the variable names in one expression will be distinct. Then for each variable present in the expression there will be a line in the input in the format s p, where s - the name of the variable and p - is the probability that the variable will be true. The names of the variables will consist of small Latin letters only.

      Constraints

      1 <= t <= 50
      0 < p < 1
      The length of the expression won't exceed 30000 characters.
      There will be no more than 1000 variable in the expression.
      The length of the variable names won't exceed 5 characters.
      Also the expression will be in the form of either conjunctive or disjunctive normal form.

      Output

      For each test case output the expected number of evaluations for the optimal order of evaluation of variables for short circuit evaluation process described above. Output the answer with 6 digits after the dot.

      Example

      Input:
      3
      (a and b) or c
      a 0.3
      b 0.4
      c 0.5
      (a or b) and (not d or c)
      a 0.5
      b 0.3
      c 0.8
      d 0.25
      ab or bc or cd
      ab 0.3
      bc 0.1
      cd 0.2
      
      Output:
      1.650000
      2.280000
      2.260000
      
      

      Explanation

      In the first test case the best order is c, a, b.


      Added by:Spooky
      Date:2011-08-24
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeChef August 2011 Long Contest









      SPOJ Problem Set (classical)

      9447. Genetics

      Problem code: GENETICS

      Genetic engineering is fun. The scientists have gathered several DNAs and want to create something new out of those. Each DNAs can be represented as a sequence of bases A, G, T, C. Let DNA[a..b] be the subsequence of DNA starting from index a finishing in b inclusive, and DNA[a..] be the subsequence of DNA starting from index a to the end. Scientist can perform the following operations on the DNAs:

      • cross operation – they take DNA1 and DNA2 and numbers k1 and k2. Then two new DNAs are created: DNA3 = DNA1[1..k1]+DNA2[k2+1..] and DNA4 = DNA2[1..k2]+DNA1[k1+1..].
      • mutate operation – they take a DNA, number k and one of the bases. Then they replace the base in position k in DNA with that base.
      • also they need to know certain characteristics of those DNAs. So they can perform count operation – they take DNA and numbers k1 and k2 (k1 <= k2). This operation should return the number of A, G, T, C bases in DNA[k1..k2].

      The initial DNAs are numbered from 1 to n, where n is the amount of those DNAs. The new DNAs created in the cross operations are numbered with consecutive integers. You are to write a program to help scientists perform those operations.

      Input

      The first line of input file contains number n – the amount of initial DNAs. Each of the following n lines contains the description of each DNA. The next line contains number q – the amount of operations to perform. The next q lines contain the description of each operation in the following form:

      • CROSS id1 id2 k1 k2
      • MUTATE id k m
      • COUNT id k1 k2

      Constraints

      1 <= n <= 20
      1 <= q <= 30000
      The length of each initial DNA does not exceed 30000. The length of any DNA formed in cross operation won’t exceed 2000000000. Total amount of different DNAs won’t exceed 10000. It is guaranteed that all operations are correct.

      Output

      For each count operation print four integers: the number of each of the bases in the given subsequence of the given DNA.

      Example

      Input:
      2
      CTCGC
      TGCGG
      5
      MUTATE 1 2 A
      COUNT 2 2 4
      MUTATE 2 1 G
      CROSS 2 1 1 5
      COUNT 4 3 6
      
      Output:
      0 2 0 1
      0 2 0 2
      
      

      Added by:Spooky
      Date:2011-08-24
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeChef August 2010 Long Contest









      SPOJ Problem Set (classical)

      9448. Swarm of Polygons

      Problem code: SWARM

      There is a regular n-gon. Some points are marked on each of its sides. There are x1 point marked on the first side, x2 – on the second, …, xn – on the nth. The marked points do not coincide with the vertices of the n-gon. You can choose no more than one of the marked points from each side and form a convex non-degenerate polygon by connecting all those points with lines. Now your task is to find the number of different k-gons that can be formed that way.

      Input

      The first line of input file contains positive integer t – the amount of test cases. Next t lines contain six integers each: n, k, a, b, c, m. Here n is the number of sides of the initial n-gon. The amount of marked points on the first side of this n-gon is x1 = a, the amount of the marked points on the following sides is xi = (b*xi-1 + c) mod m, for i > 1.

      Constraints

      1 <= t <= 30
      3 <= n <= 109
      3 <= k <= 20
      1 <= b, c, m <= 106
      0 <= a < m

      Output

      For each test case output the number of k-gons that can be formed modulo 1000000007.

      Example

      Input:
      2
      4 3 1 2 2 191
      10 5 1 113 157 999991
      
      Output:
      1228
      328836201
      
      
      

      Added by:Spooky
      Date:2011-08-24
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeChef August 2010 Long Contest









      SPOJ Problem Set (classical)

      9458. Ghosts having fun

      Problem code: GHOSTS


      Ghost are living in big castle with K rooms.

      As they have around few hundred years and very tired, they decided to buy teleports. Every teleport can work only in one way ( to prevent collision ). Ghosts have decided which teleports they want to build and in which order they should be built.

      King of ghosts, Bob, asked you to check list of teleports and decide which of them do not build. He don't want ghosts having fun in infinite ride with teleports.

      Input

      In first line - number K<=1000, amount of rooms in castle.

      In next line - number T<=300000 of teleports.

      In next T lines a,b<=K

      Rooms are numbered 1..K

      Output

      Print teleports which should not be built. End test case with 0 0

      Example

      Input:
      
      4
      5
      2 4
      4 3
      3 2
      1 2
      3 1
      Output:
      3 2
      3 1
      0 0

      Added by:Krzysztof Lewko
      Date:2011-08-25
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9459. Connecting three towns (variation)

      Problem code: THREETW1

      Given three towns find the point for which the summary distance to all towns is minimal. Wanted are the accurate coordinates ±10-6.

      Input

      In the first line the number T (T<100) of test cases. Then T lines with the space separated coordinates (integer 0<=x,y<=100) of the three towns.

      Output

      For each test case the coordinates of the above specified point.

      Example

      Input:
      2
      2 2 1 1 2 1
      1 0 0 0 2 1 Output: 1.788675 1.211324
      1 0

      Added by:HWK
      Date:2011-08-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9489. Johny Hates Math

      Problem code: ANARC07J

      Johnny is on probation! He has failed so many math courses and the Department has forced him to register in a remedial math course. He must pass the course or he'd be expelled from the University. In an attempt to impress his professor, Johnny is typing all his assignments on the computer. The latest assignment is rather simple, Johnny was given a set of problems to solve. Each problem had a list of one or more numbers that Johnny was supposed to add. Johnny has worked all night on the assignment, neatly typing his solution to each problem using a word processor as seen here:

      4+12+3=19

      As usual, Johnny woke up late, he hardly had the time to print the assignment and rush to class. Only in the classroom did he discover that, due to a printer driver problem, non of the plus signs were printed. The above line was printed as:

      4123=19

      Write a program to figure out where the pluses are supposed to be. All what Johnny remembers is that all the numbers were positive; None of the numbers, other than possibly the sum, had more than 5 digits; And none of the numbers had a zero as the left-most digit.

      Input

      The input consists of N ( N <= 100 ) test cases. The number of them (N) is given on the first line of the input file. N lines follows each have an expression. No line will be longer than 256 characters.

      Output  

      For each expression in the input, your program must print a line of result. result is the expression with the necessary plus signs in place. There are no spaces in result . If there are more than one possible solution, print a solution that requires the least number of plus signs. Knowing how bad Johnny is in arithmetic, it is possible that there is no solution, in which case your program should print ``IMPOSSIBLE" as the result.

      Example

      Input:

      3
      4123=19
      15442147612367219875=472
      111=8

      Output:

      4+12+3=19
      15+44+21+47+61+23+67+21+98+75=472
      IMPOSSIBLE

       

      
      

      Added by:Amr Mesbah
      Date:2011-09-02
      Time limit:1s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ANARC 2007









      SPOJ Problem Set (classical)

      9493. Advanced Fruits

      Problem code: ADFRUITS

      The company "21st Century Fruits" has specialized in creating new sorts of fruits by transferring genes from one fruit into the genome of another one. Most times this method doesn't work, but sometimes, in very rare cases, a new fruit emerges that tastes like a mixture between both of them.

      A big topic of discussion inside the company is "How should the new creations be called?" A mixture between an apple and a pear could be called an apple-pear, of course, but this doesn't sound very interesting. The boss finally decides to use the shortest string that contains both names of the original fruits as sub-strings as the new name. For instance, "applear" contains "apple" and "pear" (APPLEar and apPlEAR), and there is no shorter string that has the same property.
      A combination of a cranberry and a boysenberry would therefore be called a "boysecranberry" or a "craboysenberry", for example.

      Your job is to write a program that computes such a shortest name for a combination of two given fruits. Your algorithm should be efficient, otherwise it is unlikely that it will execute in the alloted time for long fruit names.

      Input Specification

      Each line of the input file contains two strings that represent the names of the fruits that should be combined. All names have a maximum length of 100 and only consist of alphabetic characters.
      Input is terminated by end of file.

      Output Specification

      For each test case, output the shortest name of the resulting fruit on one line. If more than one shortest name is possible, any one is acceptable.

      Sample Input

      apple peach
      ananas banana
      pear peach
      

      Sample Output

      appleach
      bananas
      pearch
      

      Added by:Vincenzo Bonifaci
      Date:2011-09-03
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:University of Ulm Local Contest 1999









      SPOJ Problem Set ()

      9494. Just Add It

      Problem code: ZSUM

      For two given integers n and k find (Zn+Zn-1-2Zn-2)mod 10000007 , where Zn=Sn+Pn and Sn=1k+2k+3k+…..+nk and Pn=11+22+33+……+nn.

      Input

      There are several test cases [ ≤10000 ].In each case two space separated positive integers n and k are given.
      For last test case n and k are given  as 0  0 ,which is  not to be processed.
      1<n<200000000 , 0<k<1000000.

      Output

      For each case print the asked value in separate line.

      Example

      Input:
      10 3
      9 31
      83 17
      5 2
      0 0 
      Output:
      4835897
      2118762
      2285275
      3694

      Added by:Manohar Singh
      Date:2011-09-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Manohar Singh









      SPOJ Problem Set (classical)

      9503. Working in Beijing

      Problem code: WORKB

      Mr. M is an undergraduate student of FDU. He finds an intern position in Beijing, so that he cannot attend all the college activities. But in some conditions, he must come back to Shanghai on certain date. We can assume the important activities that Mr. M must attend are occupy a whole day. Mr. M must take flight to Shanghai before that day and leave after that day. On the other hand, Mr. M is absent in Beijing and he will lose his salary for his absent.

      Sometimes the cost of flight is much higher than the loss of salary, so to save the cost on the travel, Mr. M can stay in Shanghai to wait for another important date before he back to Beijing.

      Now, Mr. M knows all of the important date in the next year. Help him schedule his travel to optimize the cost.

      Input

      The input contains several test cases. The first line of single integer indicates the number of test cases.

      For each test case, the first line contains three integers: n, a and b, denoting the number of important events, the cost of a single flight from Beijing to Shanghai or Shanghai to Beijing and the salary for a single day stay in Beijing. (1 <= n <= 100000, 1 <= a <= 1000000000, 1 <= b <=100)

      Next line contains n integers ti, denoting the time of the important events. You can assume the ti are in increasing order and they are different from each other. (0 <= ti <= 10000000)

      Output

      For each test case, output a single integer indicating the minimum cost for this year.

      Example

      Input:
      2
      1 10 10
      5
      5 10 2
      5 10 15 65 70
      
      Output:
      Case #1: 30
      Case #2: 74
      
      Warning: large input/output data, be careful with certain languages

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #3, by lcosvse









      SPOJ Problem Set (classical)

      9504. Paint on a Wall

      Problem code: PAINTWAL

      Annie wants to paint her wall to an expected pattern. The wall can be represented as a 2*n grid and each grid will be painted only one color. Annie has a brush which could paint a rectangular area of the wall at a single step. The paint could be overlap and the newly painted color will replace the older one.

      For a given pattern of the wall, your task is to help Annie find out the minimum possible number of painting steps. You can assume that the wall remains unpainted until Annie paint some colors on it.

      Input

      There are multiple test cases in the input. The first line contains the number of test cases.

      For each test case, the first line contains the only integer n indicating the length of the wall. (1 <= n <= 8)

      Two lines follow, denoting the expected pattern of the wall. The color is represented by a single capital letter.

      See the sample input for further details.

      Output

      For each test case, output only one integer denoting the minimum number of steps.

      Example

      Input:
      3
      3
      ABA
      CBC
      3
      BAA
      CCB
      3
      BBB
      BAB
      
      Output:
      Case #1: 3
      Case #2: 3
      Case #3: 2
      
      The time limit is somewhat tight for this problem.
      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:23s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #3, by g201513









      SPOJ Problem Set (classical)

      9505. Distinct Subtrees

      Problem code: DSUBTREE

      Given an unrooted tree, the subtree is defined as a connected component of the given tree. Two subtrees are considered the same if there exists a map from nodes of one tree to another so that the edges of both trees are corresponding the same pair of nodes after mapping.

      Your task is to find out how many distinct subtrees for a given unrooted tree.

      Input

      The input consists of multiple test cases. The first line of input contains an integer denoting the number of test cases.

      For each test case, the first line contains one integer n denoting the number of nodes of the given tree. (1 <= n <= 15)

      Then n-1 lines follow, each line contains two integers denoting an edge of the tree. The index of the node counts from 1.

      Output

      For each test case, output the number of distinct subtrees for the given tree.

      Example

      Input:
      2
      3
      1 2
      1 3
      9
      9 4
      4 3
      1 3
      7 4
      1 6
      5 7
      2 4
      6 8
      
      Output:
      Case #1: 3
      Case #2: 21
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #3, by g201513









      SPOJ Problem Set (classical)

      9506. Jimmy´s Travel Plan

      Problem code: DIST2

      Jimmy lives in a huge kingdom which contains lots of beautiful cities. He also loves traveling very much, and even would like to visit each city in the country. Jaddy, his secretary, is now helping him to plan the routes, however, Jaddy suddenly find that is quite a tough task because it is possible for Jimmy to ask route’s information toward any city. What was worse is that Jaddy has to response for queries about the distance information nearly between any pair of cities due to the undeterminable starting city which Jimmy is living in when he raises a query. Because of the large scale of the whole country, Jaddy feels hopeless to archive such an impossible job, however, in order to gratify his manager, Jaddy is now looking forward to your assistance.

      There might be good news about Jaddy’s work: since Jimmy is very lazy and would not like to travel to a destination whose distance between the original city is larger than TWO. That means only one intermediate city among the route is acceptable (Apparently, all the connecting paths between any two cities, if exists, have the same length as ONE). But don’t be fooled: Jimmy also needs to know that how many alternative different routes are available so that he can have more options. In particular two routes were named as different if and only if there is at least one path in the two routes is distinguishable, moreover, if more than one paths exist between a particular pair of cities, they are considered as distinct.

      Input

      Input has multiple test cases. The first line of the input has a single integer indicating the number of test cases, then each test case follows. For each test case, the first line contains two integers N and M indicating the number of cities and paths in the country. Then M lines are following, each line contains a pair of integers A and B, separated by space, denoting an undirected path between city A and city B. All the cities are numbered from 1 to N. Then a new line contains a single integer Q, which means there are Q queries following. Each query contains a couple of integers A and B which means querying the distance and number of shortest routes between city A and B, each query occupies a single line separately.

      All the test cases are separated by a single blank line.

      You can assume that N, Q <= 100000, M <= 200000.

      Output

      For each test case, firstly output a single line contains the case number, then Q lines for the response to queries with the same order in the input. For each query, if there exists at least one routes with length no longer than TWO, then output two integer separated by a single space, the former is the distance (shortest) of routes and the later means how many different shortest routes Jimmy can choose; otherwise, output a single line contains “The pair of cities are not connected or too far away.” (quotes for clarifying). See the sample data carefully for further details.

      Example

      Input:
      2
      5 7
      1 2
      2 3
      3 4
      4 5
      2 5
      2 4
      1 2
      4
      1 4
      1 2
      5 3
      5 4
      
      2 0
      2
      1 1
      1 2
      
      Output:
      Case #1:
      2 2
      1 2
      2 2
      1 1
      Case #2:
      0 1
      The pair of cities are not connected or too far away.
      
      Warning: large input/output data, be careful with certain languages

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #3, by lcosvse









      SPOJ Problem Set (classical)

      9507. Mario and Mushrooms

      Problem code: MARIO2


      Mario usually relaxes himself by walking along the shady track near the Mushroom Kingdom. The evil King Koopa noticed that and placed a lot of mushroom on the road. There are two types of mushrooms, max mushrooms and bad mushrooms. The bad mushrooms will decrease Mario's HP by m points, on the other hand, max mushrooms will increase Mario's HP by one point. The mushrooms are randomly placed on the track and Mario will receive them one by one. Once Mario's HP becomes zero or below after he received a mushroom, he will die.

      Notice that Mario begins with HP zero, so if the first mushroom is bad, Mario will die immediately. Fortunately, if Mario receives all the mushrooms, he will be alive with HP 1. In the other words, if there are k bad mushrooms on the way, there will also be m*k+1 max mushrooms.

      Princess Peach wants to know the possibility for Mario staying alive. Please help her to calculate it out.

      Input

      There are several test cases. The first line contains only one integer denoting the number of test cases.

      For each test case, there is only one line including two integers: m and k, denoting the amount of points of HP the Mario will decrease if he receives a bad mushroom, and the number of bad mushrooms on the track. (1 <= m <= 1000, 1 <= k <= 1000)

      Output

      For each test case, output only real number denoting the possibility that Mario will survive if he receives all the randomly placed mushrooms one by one. The answer should be rounded to eight digits after the decimal point.

      The judge is "ignoring extra white spaces".

      Example

      Input:
      2
      1 1
      60 80
      
      Output:
      Case #1: 0.33333333
      Case #2: 0.00020488
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #3, by g201513









      SPOJ Problem Set (classical)

      9508. Magic Bitwise AND Operation

      Problem code: AND


      Given n integers, your task is to pick k out of them so that the picked number are minimum when do bitwise AND among all of them.

      Input

      There are multiple test cases for this problem. The first line of the input contains an integer denoting the number of test cases.

      For each test case, there are two integers in the first line: n and k, denoting the number of given integers and the number of integers you are asked to pick out. (1<= n <=40, 1<= k <= n)

      The second line contains the n integers. You may assume that all integers are smaller than 260.

      Note: There are about one thousand randomly generated test cases. Fortunately 90% of them are relatively small.

      Output

      For each test case, output only one integer - the smallest possible value.

      Example

      Input:
      2
      3 2
      5 6 7
      8 2
      238 153 223 247 111 252 253 247
      
      Output:
      Case #1: 4
      Case #2: 9
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:23s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #3, by g201513









      SPOJ Problem Set (classical)

      9509. Shortest Path on a Cylinder

      Problem code: CYLINDES


      Ant Smart is on a surface of cylinder now. He wants to move to another position of the cylinder’s surface. Like many other animals named Smart, he wants to find out the shortest path from one point to another.

      Unfortunately, Ant Smart is not enough smart to solve this question now. It is your task to find out the answer.

      Input

      There are several test cases in this problem. The number of them is about 1000. The first line of input contains a single integer denoting the number of test cases.

      For each test case, the first line contains two integers - the radius and height of the cylinder, separated by spaces.

      For the next two lines, each line contains three integers: h, a and r (0 <= h <= height, 0 <= a < 360, 0 <= r <= radius), denoting one point on the surface of cylinder, respectively. h indicates a circle on the surface of cylinder which apart h from the bottom. And the polar angle a and radius r indicates the position of the point on the circle. In the other words, if the cylinder is (0,0,0) - (0,0,height) on the 3D grid coordinate. The point can be represented as (cos(a)*r, sin(a)*r, h).

      You may assume that the given points must be on the surface of the given cylinder.

      Output

      For each test case, output only one line contains the length of the shortest path on the surface of cylinder. We accept solutions with absolute error less than 10-2 in at least 99% of the test cases.

      Example

      Input:
      2
      5 10
      10 0 3
      5 0 5
      90 49
      49 312 39
      0 52 65
      
      Output:
      7.00
      171.02
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:99s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #3, by g201513









      SPOJ Problem Set (classical)

      9510. Ads Proposal

      Problem code: ADSPROP

      There are N customers set their M different advertisements on Baidu. Each advertisement is owned by single customer. The ads system of Baidu records the number of clicks of each advertisement this year. The proposal system wants to analysis the advertisements about the relativity of the description length and the number of clicks of the advertisements. During the analysis, it is very important to do such a query to ask the total length of the advertisements with top K clicking times for each customer. You may assume the clicks of all advertisements are distinct.

      Your task is to help Baidu to design this little toolkit.

      Input

      The input consist multiple test cases. The number of test cases is given in the first line of the input.

      For each test case, the first line contains three integers N, M and Q, denoting the number customer, the number of advertisement instances and the number of queries. (N <= 100000, M <= 500000, Q <= 100000)

      Then M lines follow, each line contains three numbers, U, C and L, indicating the owner of this advertisement, the clicks for this advertisement and the length.

      Finally Q lines come. Each line contains only one integer K, representing the query for top K clicking advertisements for each customer.

      All input numbers will be positive and less than 1000000000.

      Output

      For each test case, output Q lines, each line contains only one integer, denoting the sum of total length of the top K number of clicks for each customer.

      Example

      Input:
      2
      2 4 3
      1 12 13
      2 23 41
      1 21 46
      1 22 31
      1
      2
      3
      6 15 3
      5 2677139 731358928
      2 347112028 239095183
      6 27407970 85994789
      6 767687908 734935764
      6 255454855 110193353
      3 39860954 813158671
      5 617524049 55413590
      3 338773814 7907652
      6 810348880 736644178
      2 777664288 63811422
      6 590330120 616490361
      5 552407488 136492190
      1 416295130 448298060
      5 811513162 232437061
      4 43273262 874901209
      4
      9
      13
      
      Output:
      Case #1:
      72
      118
      131
      Case #2:
      5801137622
      5887132411
      5887132411
      
      Warning: large input/output data, be careful with certain languages

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Fudan University Local Contest #3, by Blue Mary









      SPOJ Problem Set (classical)

      9511. 24-Puzzle

      Problem code: PUZZLE24

      Daniel likes to play a special board game, called 24 puzzle. 24 puzzle is such a game that there are tiles with the number 1 to 23 in a play board like the follows:

       #  #
      ######
       ####
       ####
      ######
       #  #
      

      The ‘#’ denotes the positions that the tiles may be placed on. There are 24 possible positions in total, so one of them is not occupied with the tile. We denote the empty position by zero.

      Daniel could move the tiles adjacent to the empty position to it. In this way Daniel can reorder the number tiles of the game. He plays with this game by setting up a target states initially, and then trying to do some move to achieve the target. Soon he finds that not all target states can be achieved by the move.

      He asks for your help, to determine whether he set up an impossible target or not.

      Input

      The first line of input contains an integer denoting the number of test cases.

      For each test case, the first line contains 24 integers denoting the initial states of the game board. The numbers describes the tiles from top to bottom, left to right. And the empty position is indicated by zero. You can assume that the number of each tiles are different, and there must be exactly one empty position. The second line of test case also contains 24 integers denoting the target states.

      Output

      For each test case, if the target is impossible to achieve, output Y in a single line, otherwise, output N.

      Example

      Input:
      2
      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
      3 1 2 0 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
      3 0 2 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
      
      Output:
      N
      Y
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regionals, Shanghai 2011 Preliminary, by Blue Mary









      SPOJ Problem Set (classical)

      9512. Bombing

      Problem code: BOMB2


      It's a cruel war which kills millions of people and series of cities were ruined. In order to stop it, let's bomb the opponent's base.

      It seems to be not a hard work in circumstances of street battles, however, you'll be encountered a much more difficult instance: recounting exploits of the military. In the bombing action, the commander will dispatch a group of bombers with weapons having the huge destructive power to destroy all the targets in a line. Thanks to the outstanding work of our spy, the positions of all opponents' bases had been detected and marked on the map, consequently, the bombing plan will be sent to you.

      Specifically, the map is expressed as a 2D-plane with some positions of enemy's bases marked on. The bombers are dispatched orderly and each of them will bomb a vertical or horizontal line on the map. Then your commanded wants you to report that how many bases will be destroyed by each bomber. Notice that a ruined base will not be taken into account when calculating the exploits of later bombers.

      Input

      Multiple test cases. Each test cases starts with two non-negative integer N (N <= 100,000) and M (M <= 100,000) denoting the number of target bases and the number of scheduled bombers respectively. In the following N line, there is a pair of integers separated by single space indicating the coordinate of position of each opponent's base. The following M lines describe the bombers, each of them contains two integers c and d (0<= c <=1 , -1,000,000,000 <= d <= 1,000,000,000). c = 0 means this bomber will bomb the line x = d, c = 1 means this bomber will bomb the line y = d.

      The input ends with N = M = 0.

      Output

      For each test case, output M lines, the i-th line contains a single integer denoting the number of bases that were destroyed by the corresponding bomber in the input. Output a blank line after each test case.

      Example

      Input:
      3 2
      1 2
      1 3
      2 3
      0 1
      1 3
      0 0
      
      Output:
      2
      1
      
      Warning: large input/output data, be careful with certain languages
      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regionals, Shanghai 2011 Preliminary









      SPOJ Problem Set (classical)

      9513. Game

      Problem code: TETRISGM

      Alice and Bob are playing game with each other. They play the game on a 2D board. Alice has many vertical 1*2 tiles while Bob has many horizontal 2*1 tiles. They take turn to place their own tiles on the board. Considering about that the tiles cannot overlap each other, the player cannot do the placement any more loses. Since this is such a complex game that they could not find optimal method to play that, Alice decide to simplify this game by replace the large 2D board by some small ones. Alice set up a lot of Tetris tiles instead of the original 2D board. In the other words, the player can only place their own vertical or horizontal tiles on the Tetris-like board. Each player can choose one possible place on any Tetris tiles to place its own tiles. In fact, there are following 15 types of Tetris playground.

      The playground cannot be transformed in any ways, including reflection and rotation.

      Given the number of each type of tiles, you are asked to determine who will win the game if Alice plays first and both players are playing optimal.

      Input

      There are multiple test cases; the first line of input contains a single integer denoting the number of test cases.

      For each test case, there are only one line contains 15 integers denoting the number of Tetris tiles of the above 15 types. All the numbers are no greater than 100.

      Output

      For each test cases, output Alice if Alice will win the game and both player plays optimally, Bob otherwise.

      Example

      Input:
      3
      5 4 0 0 0 0 0 0 0 0 0 0 0 0 0
      5 5 0 0 0 0 0 0 0 0 0 0 0 0 0
      100 100 0 0 0 0 0 0 0 0 0 2 1 0 0
      
      Output:
      Case #1: Alice
      Case #2: Bob
      Case #3: Alice
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regionals, Shanghai 2011 Preliminary, by g201513









      SPOJ Problem Set (classical)

      9515. Dwarven Sniper´s Hunting

      Problem code: HUNT1


      Now the hunting starts in the world named DOTA, a stupid PC game which cannot play with others together.

      Among the individuals in the game, there are two heroes named Dwarven Sniper and Lycanthrope. Lycanthrope wants to escape from being captured; however, our Dwarven Sniper won't let him go! He will use the Silver Bullet to kill the Lycanthrope by only one shot! Yes, that's enough.

      Lycanthrope is running on a line in the map with a constant speed. The weapon range of the Silver Bullet is limited by L meters. Dwarven Sniper can run for a while freely, and then shoot Lycanthrope. In order to show his excellent shooting skill, Dwarven Sniper wants the Silver Bullet flying as far as possible. But don't forget the flying time of the Silver Bullet due to considerable weight of the bullet. And Dwarven Sniper wants to stop the hunting as quickly as possible. So if there is more than one way to show his excellent skill, he would choose the fastest way. In this problem we consider the Silver Bullet and Lycanthrope as two points.

      Now Dwarven Sniper wants to know the maximum length that the Silver Bullet can fly, and (under this condition) the shortest time that the hunting lasts. Specifically, the total hunting time is defined as the time interval from the start of hunting to the moment that the bullet hit Lycanthrope. Can you help him?

      Input

      There are several test cases. Each of them contains only one line which consist of 9 real numbers, that are X1, Y1, X2, Y2, Lx, Ly, vD , vB and L (-10000 <= X1 , Y1 , X2 , Y2 , Lx , Ly <= 10000 , 0 <= vD , vB , L <=100000). The pair (X1, Y1) is the starting position of the Lycanthrope while (X2, Y2) is the starting position of Dwarven Sniper, while (Lx, Ly) is the moving vector per second of the Lycanthrope, vD is the speed of the Dwarven Sniper, vB is the speed of the Silver Bullet, L is the maximum possible flying distance of the bullet.

      All units are meters/second.

      It is guaranteed that (Lx*Lx+Ly*Ly) < vD*vD < vB*vB , and Dwarven Sniper's starting position is different from Lycanthrope's position. The input ends with a line containing all zeros.

      Output

      For each test case, output two real numbers S and T in a line separated by a single space denoting that the Silver bullet flies S meters before hitting Lycanthrope and the hunting lasts for T seconds, both with 3 numbers after the decimal point.

      You may assume that Dwarven Sniper can finish his hunting within no more than 1e+9 seconds.

      Note: The judge is "ignoring extra white spaces".

      Example

      Input:
      -1 0 0 10 1 0 2 10 10
      0 0 0 5 0 1 2 6 6
      0 0 0 0 0 0 0 0 0
      
      Output:
      10.000 1.000
      6.000 3.000
      


      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regionals, Shanghai 2011 Preliminary









      SPOJ Problem Set (classical)

      9516. XOR Equations

      Problem code: XOREQ

      Recently, Jimmy is learning about linear algebra from Blue Mary while having the course of Boolean algebra in class offered by Prof. Z. Since Jimmy has been thoroughly bored by the boring homework assigned by two teachers, evil Jimmy plans to set a hard question to baffle them as revenge for their heavy tasks. As a result, Jimmy comes up with an idea that merging the knowledge from both the two classes and constructs a complicate problem: the XOR equation system.

      Let's consider the following equations:

      which satisfies the following conditions:

      In the system of equations, operation . denotes the multiplication operation while ^ is for bitwise XOR. Moreover, the bitwise XOR takes two bit patterns of equal length and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if the two bits are different, and 0 if they are the same.

      Rather than expecting a solution of a specified equation system, Jimmy would like to ask the teachers to calculate that how many distinct solutions can satisfy a given equation system. What a confusing puzzle! Help Jimmy's teachers please!

      Input

      There are several test cases. The first line of input is a single positive integer (<= 15) indicating the number of test cases, the test cases follow.

      For each test case, the first line contains two integers N and M giving the two dimensions of the equation system respectively where N is the number of rows and M for columns. Then N lines are following, each line contains M integers. Item at line i and column j represents aij. The next M lines are descriptions of Si that the leading integer K denotes the number of elements in Si and the following K integers represent elements.

      Output

      For each test case, output one line containing a single integer which represents the answer of this case.

      Example

      Input:
      1
      1 2
      1 1
      3 0 1 2
      2 3 1
      
      Output:
      1
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regionals, Shanghai 2011 Preliminary









      SPOJ Problem Set (classical)

      9517. Unlock the Cellphone

      Problem code: UNLOCK


      Modern high-tech cell phones use unlock patterns to unlock the system. The pattern is usually a 3*3 dot array. By moving your finger over there dots, you can generate your personal unlock pattern. More specifically, press your finger over any starting dot, then slide all the way to the next dot, touch it, and so on. Jumping is not allowed. For example, starting from dot 1, you can slide to touch dot 2, dot 4 and dot 5, but sliding directly to dot 3, dot 7 or dot 9 are not allowed. Note that sliding from 1 to 6 and 8 is also allowed because they are not considered as jumping over any dot. However, you can jump a dot if it has been touched before. For example, staring with 1-5-9-6, you can slide directly to dot 4.

      Here is a very particular cell phone. It has a dot array of size n*m. Some of the dots are ordinary ones: you can touch, and slide over them when touched before; some are forbidden ones: you cannot touch or slide over them; some are inactive ones: you cannot touch them, but can slide over them. Each dot can only be touched once. You are required to calculate how many different unlock patterns passing through all the ordinary dots.

      Input

      The input contains several test cases. Each test case begins with a line containing two integers n and m (1 <= n, m <= 5), indicating the row and column number of the lock keypad. The following n lines each contains m integers Ki,j indicating the properties of each key, Ki,j=0 stands for an ordinary key, Ki,j=1 stands for a forbidden key; and Ki,j=2 stands for an inactive key. The number of ordinary keys is greater than zero and no more than 16.

      Input terminates by EOF.

      Output

      For each test, output an integer indicating the number of different lock patterns.

      Example

      Input:
      2 2
      0 0
      0 0
      3 3
      0 0 0
      0 2 1
      0 0 0
      
      Output:
      24
      2140
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regionals, Shanghai 2011 Preliminary, by cuiaoxiang









      SPOJ Problem Set (classical)

      9518. The Time of Day

      Problem code: LCM

      There are no days and nights on byte island, so the residents here can hardly determine the length of a single day. Fortunately, they have invented a clock with several pointers. They have N pointers which can move round the clock. Every pointer ticks per second, and the i-th pointer move to the start position after i times of ticks. The wise of the byte island decide to define a day as the time interval between the start time and the first time when all the pointers moves to the position exactly the same as the start time. The wise of the island decide to choose some of the N pointers to make the length of the day are greater than or equal to a given seconds M. They want to know how many different ways to make it possible.

      Input

      There are a lot of test cases, the number of test cases are in the first line of input.

      For each test cases, there are only one line contains two integers N and M, indicating the number of pointers and the lower bound for seconds of a day. (1 <= N <= 40, 1 <= M <= 263-1)

      Output

      For each test case, output a single integer denoting the number of ways.

      Example

      Input:
      3
      5 5
      10 1
      10 128
      
      Output:
      Case #1: 22
      Case #2: 1023
      Case #3: 586
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regionals, Shanghai 2011 Preliminary, by g201513









      SPOJ Problem Set (classical)

      9519. Distinct Submatrices

      Problem code: DSUBMTR


      Consider an matrix of capital letters. By selecting consecutive columns and rows, we can define the sub-matrix as the elements on chosen columns and rows.

      Two sub-matrices should be regarded the same if and only if they have the same detentions and characters (which, of course, are capital letters) on corresponding position. It is your task to find the number of distinct sub-matrices of a given letter matrix.

      Input

      The input contains a lot of test cases. The first line of input contains exactly one integer, indicating the number of test cases.

      For each of the test case, the first line contains two integers N and M, denoting the number of rows and columns of the given matrix. (1 <= N, M <= 128)

      The next N lines contain only capital letters, indicating the given matrix.

      Output

      For each test case, output a single integer denoting the number of distinct sub-matrices.

      Example

      Input:
      2
      2 2
      AB
      BA
      3 3
      ABA
      BAA
      AAA
      
      Output:
      Case #1: 7
      Case #2: 22
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regionals, Shanghai 2011 Preliminary, by g201513









      SPOJ Problem Set (classical)

      9520. Tanks

      Problem code: TANKS


      Surprisingly, the king of the Quadruple Island Kingdom suddenly declares war on its neighbor country, the Utopia Land. After that, the King dispatches a large number of tanks for first attack. You, as the Defense Minister of Utopia Land, are certainly under mass of pressure. In order to defense the enemy, you decide to use the new secret weapon: laser cannon. This kind of weapon is so powerful that can easily destroy any thing at a line in a moment, or course, including tanks.

      However, Because of some designing flaw, you can use such weapon just once during the war. The only hope is that you can choose a good moment and right way to use it so that as many tanks as possible can be destroyed.

      A tank can be described as a point whose coordinate is (Xi, Yi) on a 2D-plain with speed vector (VXi, VYi) per second. Starting at time 0, you can use your laser cannon at any position and in any direction at any INTEGER number of seconds after time 0. It is possible that some tanks will meet at the same point while moving, and they will not influence each other anyway.

      Input

      Multiple test cases. The number of test cases is no more than 10. For each test cases, The first line contains a single integer N (1 <= N <= 100) indicating the number of tanks. Then N lines are following that describing the tanks respectively. Each of them consists of four nonzero integer Xi, Yi, VXi, VYi separated by single spaces where |Xi|,|Yi| <= 100,000,000 and |VXi|,|VYi| <= 100 denoting the initial position of a tank and the speed vector. Input ends with N = 0.

      Output

      For each test case, output one line with a single integer indicating the largest number of tanks which can be destroyed by the laser cannon.

      Note: Be careful when handling floating point errors.

      Example

      Input:
      4
      10 10 -1 -1
      3 1 4 6
      2 8 5 -1
      1 3 1 4
      0
      
      Output:
      3
      

      Added by:[Trichromatic] XilinX
      Date:2011-09-08
      Time limit:9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regionals, Shanghai 2011 Preliminary









      SPOJ Problem Set (classical)

      9525. Cipher

      Problem code: CIPHERJ



      Bob and Alice started to use a brand-new encoding scheme. Surprisingly it is not a Public Key Cryptosystem, but their encoding and decoding is based on secret keys. They chose the secret key at their last meeting in Philadelphia on February 16th, 1996. They chose as a secret key a sequence of n distinct integers, tex2html_wrap_inline27 , greater than zero and less or equal to n. The encoding is based on the following principle. The message is written down below the key, so that characters in the message and numbers in the key are correspondingly aligned. Character in the message at the position i is written in the encoded message at the position tex2html_wrap_inline33 , where tex2html_wrap_inline33 is the corresponding number in the key. And then the encoded message is encoded in the same way. This process is repeated k times. After kth encoding they exchange their message.

      The length of the message is always less or equal than n. If the message is shorter than n, then spaces are added to the end of the message to get the message with the length n.

       

      Help Alice and Bob and write program which reads the key and then a sequence of pairs consisting of k and message to be encoded k times and produces a list of encoded messages.

      Input

      The input file consists of several blocks. Each block has a number tex2html_wrap_inline51 in the first line. The next line contains a sequence of n numbers pairwise distinct and each greater than zero and less or equal than n. Next lines contain integer number k and one message of ascii characters separated by one space. The lines are ended with eol, this eol does not belong to the message. The block ends with the separate line with the number 0. After the last block there is in separate line the number 0.

      Output 

      Output is divided into blocks corresponding to the input blocks. Each block contains the encoded input messages in the same order as in input file. Each encoded message in the output file has the lenght n. After each block there is one empty line.

      Sample Input

      10
      4 5 3 7 2 8 1 6 10 9
      1 Hello Bob
      1995 CERC
      0
      0
      

      Sample Output

      BolHeol  b
      C RCE     

      Added by:Andres Tellez
      Date:2011-09-12
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9527. Department

      Problem code: DEPARTJ

      The Department of Security has a new headquarters building. The building has several floors, and on each floor there are rooms numbered xxyywhere yy stands for the room number and xx for the floor number, 0 < xxyy < 10.

      The building has "pater-noster" elevator, i.e. elevator build up from several cabins running all around.From time to time the agents must visit the headquarters.During their visit they want to visit several rooms and in each room they want to stay for some time. Due to the security reasons, there can be only one agent in the same room at the same time, The same rule applies to the elevators.

      The visits are planned in the way ensuring they can be accomplished within one day. Each agent visits the headquarters at most once a day.

      Each agent enters the building at the 1st floor, passes the reception and then starts to visit the rooms according to his/her list. Agents always visit the rooms by the increasing room numbers. The agents form a linear hierarchy according to which they have assigned their one letter personal codes. The agents with higher seniority have lexicographically smaller codes. No two agents have the same code.

      If more then one agent want to enter a room, or an elevator, the agents have to form a queue. In each queue, they always stand according to their codes. The higher the seniority of the agent, the closer to the top of the queue he stands. Every 5 s (seconds) the first agent in the queue in front of the elevator enters the elevator. After visiting the last room in the headquarters each agent uses if necessary elevator to the first floor and exits the building.

      The times necessary to move from a certain point in the headquarters to another are set as follows: Entering the building, i.e. passing the reception and reaching the elevator, or a room on the first floor takes 30 s. Exiting the building, i.e. stepping out of the elevator or a room on the first floor and passing the reception takes also 30 s. On the same floor, the transfer from the elevator to the room (or to the queue in front of the room), or from the room to the elevator (or to the queue in front of the elevator), or from one room to another (or to the queue in front of the room) takes 10 s. The transfer from one floor to the next floor above or below in an elevator takes 30 s. Write a program that determines time course of agent's visits in the headquarters.

       

      Input

      The input file contains the descriptions of tex2html_wrap_inline49 visits of different agents. The first line of the description of each visit consists of agent's one character code CC = A, ..., Z, and the time when the agent enters the headquarters. The time is in the format HH:MM:SS (hours, minutes, seconds). The next lines (there will be at least one) contain the room number, and the length of time intended to stay in the room, time is in seconds. Each room is in a separate line. The list of rooms is sorted according to the increasing room number. The list of rooms ends by the line containing 0. The list of the descriptions of visits ends by the line containing the character dot.

       

      Output

      The output contains detailed records of each agent's visit in the headquarters. For each agent, there will be a block. Blocks are ordered in the order of increasing agent's codes. The first line of a block contains the code of agent. Next lines contain the starting and ending time (in format HH:MM:SS) and the descriptions of his/her activity. Time data will be separated by one blank character. Description will be separated from time by one blank character. Description will have a form Entry, Exit or Message. The Message can be one of the following: Waiting in elevator queue, Waiting in front of room RoomNumberTransfer from room RoomNumber to room RoomNumber,Transfer from elevator to room RoomNumbertransfer from RoomNumber to elevatorStay in room RoomNumberStay in elevator.
      Print a blank line after each block.

       

      Sample Input

      A 10:00:00
      0101 100
      0110 50
      0202 90
      0205 50
      0
      B 10:01:00
      0105 100
      0201 5
      0205 200
      0
      .

       

      Sample Output

      A
      10:00:00 10:00:30 Entry
      10:00:30 10:02:10 Stay in room 0101
      10:02:10 10:02:20 Transfer from room 0101 to room 0110
      10:02:20 10:03:10 Stay in room 0110
      10:03:10 10:03:20 Transfer from room 0110 to elevator
      10:03:20 10:03:50 Stay in elevator
      10:03:50 10:04:00 Transfer from elevator to room 0202
      10:04:00 10:05:30 Stay in room 0202
      10:05:30 10:05:40 Transfer from room 0202 to room 0205
      10:05:40 10:07:40 Waiting in front of room 0205
      10:07:40 10:08:30 Stay in room 0205
      10:08:30 10:08:40 Transfer from room 0205 to elevator
      10:08:40 10:09:10 Stay in elevator
      10:09:10 10:09:40 Exit
      
      B
      10:01:00 10:01:30 Entry
      10:01:30 10:03:10 Stay in room 0105
      10:03:10 10:03:20 Transfer from room 0105 to elevator
      10:03:20 10:03:25 Waiting in elevator queue
      10:03:25 10:03:55 Stay in elevator
      10:03:55 10:04:05 Transfer from elevator to room 0201
      10:04:05 10:04:10 Stay in room 0201
      10:04:10 10:04:20 Transfer from room 0201 to room 0205
      10:04:20 10:07:40 Stay in room 0205
      10:07:40 10:07:50 Transfer from room 0205 to elevator
      10:07:50 10:08:20 Stay in elevator
      10:08:20 10:08:50 Exit

      Added by:Andres Tellez
      Date:2011-09-12
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9528. Johns Trip

      Problem code: JTRIP


      Little Johnny has got a new car. He decided to drive around the town to visit his friends. Johnny wanted to visit all his friends, but there was many of them. In each street he had one friend. He started thinking how to make his trip as short as possible. Very soon he realized that the best way to do it was to travel through each street of town only once. Naturally, he wanted to finish his trip at the same place he started, at his parents' house.

      The streets in Johnny's town were named by integer numbers from 1 to nn < 1995. The junctions were independently named by integer numbers from 1 to mtex2html_wrap_inline32 . All junctions in the town had different numbers. Each street was connecting exactly two (not necessarily different) junctions. No two streets in the town had the same number. He immediately started to plan his round trip. If there was more than one such round trip, he would have chosen the one which, when written down as a sequence of street numbers is lexicographically the smallest.

      But Johnny was not able to find even one such round trip. Help Johnny and write a program which finds the desired shortest round trip. If the round trip does not exist the program should write a message. Assume that Johnny lives at the junction ending the 1st street input with smaller number. All streets in the town are two way. There exists a way from each street to another street in the town. The streets in the town are very narrow and there is no possibility to turn back the car once he is in the street.

       

      Input

      Input file consists of several blocks. Each block describes one town. Each line in the block contains three integers xyz, where x > 0 and y > 0 are the numbers of junctions which are connected by the street number z. The end of the block is marked by the line containing x = y = 0. At the end of the input file there is an empty block, x = y = 0.

       

      Output

      The output file consists of 2 line blocks corresponding to the blocks of the input file. The first line of each block contains the sequence of street numbers (single members of the sequence are separated by space) describing Johnny's round trip. If the round trip cannot be found the corresponding output block contains the message ``Round trip does not exist.''. The second line of each block is empty.

       

      Sample Input

      1 2 1
      2 3 2
      3 1 6
      1 2 5
      2 3 3
      3 1 4
      0 0
      1 2 1
      2 3 2
      1 3 3
      2 4 4
      0 0
      0 0

       

      Sample Output

      1 2 3 5 4 6
      
      Round trip does not exist.

      Added by:Andres Tellez
      Date:2011-09-12
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9529. Maya Calendar

      Problem code: MAYCA


      During his last sabbatical, professor M. A. Ya made a surprising discovery about the old Maya calendar. From an old knotted message, professor discovered that the Maya civilization used a 365 day long year, called Haab, which had 19 months. Each of the first 18 months was 20 days long, and the names of the months were pop, no, zip, zotz, tzec, xul, yoxkin, mol, chen, yax, zac, ceh, mac, kankin, muan, pax, koyab, cumhu. Instead of having names, the days of the months were denoted by numbers starting from 0 to 19. The last month of Haab was called uayet and had 5 days denoted by numbers 0, 1, 2, 3, 4. The Maya believed that this month was unlucky, the court of justice was not in session, the trade stopped, people did not even sweep the floor.

      For religious purposes, the Maya used another calendar in which the year was called Tzolkin (holly year). The year was divided into thirteen periods, each 20 days long. Each day was denoted by a pair consisting of a number and the name of the day. They used 20 names: imix, ik, akbal, kan, chicchan, cimi, manik, lamat, muluk, ok, chuen, eb, ben, ix, mem, cib, caban, eznab, canac, ahau and 13 numbers; both in cycles.

      Notice that each day has an unambiguous description. For example, at the beginning of the year the days were described as follows:

      1 imix, 2 ik, 3 akbal, 4 kan, 5 chicchan, 6 cimi, 7 manik, 8 lamat, 9 muluk, 10 ok, 11 chuen, 12 eb, 13 ben, 1 ix, 2 mem, 3 cib, 4 caban, 5 eznab, 6 canac, 7 ahau, and again in the next period 8 imix, 9 ik, 10 akbal...

       

      Years (both Haab and Tzolkin) were denoted by numbers 0, 1, ..., where the number 0 was the beginning of the world. Thus, the first day was:

      Haab: 0. pop 0

      Tzolkin: 1 imix 0

      Help professor M. A. Ya and write a program for him to convert the dates from the Haab calendar to the Tzolkin calendar.

       

      Input

      The date in Haab is given in the following format:

      NumberOfTheDay. Month Year 

      The first line of the input file contains the number of the input dates in the file. The next n lines contain n dates in the Haab calendar format, each in separate line. The year is smaller then 5000.

       

      Output

      The date in Tzolkin should be in the following format:

      Number NameOfTheDay Year

      The first line of the output file contains the number of the output dates. In the next n lines, there are dates in the Tzolkin calendar format, in the order corresponding to the input dates.

      Sample Input

      3
      10. zac 0
      0. pop 0
      10. zac 1995

      Sample Output

      3
      3 chuen 0
      1 imix 0
      9 cimi 2801

      Added by:Andres Tellez
      Date:2011-09-12
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9532. Transportation

      Problem code: TRANSJ

      Ruratania is just entering capitalism and is establishing new enterprising activities in many fields including transport. The transportation company TransRuratania is starting a new express train from city A to city B with several stops in the stations on the way. The stations are successively numbered, city A station has number 0, city B station number m. The company runs an experiment in order to improve passenger transportation capacity and thus to increase its earnings. The train has a maximum capacity n passengers. The price of the train ticket is equal to the number of stops (stations) between the starting station and the destination station (including the destination station). Before the train starts its route from the city A, ticket orders are collected from all onroute stations. The ticket order from the station S means all reservations of tickets from S to a fixed destination station. In case the company cannot accept all orders because of the passenger capacity limitations, its rejection policy is that it either completely accept or completely reject single orders from single stations.

       

      Write a program which for the given list of orders from single stations on the way from A to B determines the biggest possible total earning of the TransRuratania company. The earning from one accepted order is the product of the number of passengers included in the order and the price of their train tickets. The total earning is the sum of the earnings from all accepted orders.

       

      Input

      The input file is divided into blocks. The first line in each block contains three integers: passenger capacity n of the train, the number of the city B station and the number of ticket orders from all stations. The next lines contain the ticket orders. Each ticket order consists of three integers: starting station, destination station, number of passengers. In one block there can be maximum 22 orders. The number of the city B station will be at most 7. The block where all three numbers in the first line are equal to zero denotes the end of the input file.

       

      Output

      The output file consists of lines corresponding to the blocks of the input file except the terminating block. Each such line contains the biggest possible total earning.

       

      Sample Input

      10 3 4
      0 2 1
      1 3 5
      1 2 7
      2 3 10
      10 5 4
      3 5 10
      2 4 9
      0 2 5
      2 5 8
      0 0 0

       

      Sample Output

      19
      34

      Added by:Andres Tellez
      Date:2011-09-12
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9534. Turn on the lights

      Problem code: JZPLIT


      Recently Zippy received a puzzle. It is an n*m matrix. In each cell of the matrix, there is a switch and a light. Once he flips the switch in a cell, lights in the same column or the same row as the cell (including itself) change to its opposite state (which means: on->off off->on). Zippy wants to turn on all the lights. Please help him to solve the puzzle.

      Input

      First line, n, m.

      The following n lines, each line is a m-length string, represting the original state. (0 means on and 1 means off)

      1<=n,m<=1000

      First line, n, m.
      The following n lines, each line is a m-length string, represting the original state. (0 means on and 1 means off)
      1<=n,m<=100

      Output

      n lines, each line is a m-length string. It's obvious that if a valid solution exists, there exists a solution that every switch is flipped no more than once. So 1 means the switch is flipped once and 0 means the swtich remains unflipped. 

      It's guaranteed that there always exists a solution. If there are multiple solutions, output any of them. 

      Example

      Input:
      2 3
      010
      010
      
      Output:
      010
      101
      

      Added by:sevenkplus
      Date:2011-09-12
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9535. Turn on the lights 2

      Problem code: JZPLIT2


      Recently Zippy received a puzzle. It is an n*m matrix. In most cells of the matrix, there is a light with a switch. However, some cells do not contain a light with a switch, and they are called "blocks". Once he flips the switch in a cell, lights in visible cells from it(including itself) change to its opposite state (which means: on->off off->on). One cell is visible from another, iff they are in the same row or the same column, and there aren't any blocks between them (and of course the two cells should not be blocks). Zippy wants to turn on all the lights. Please help him to solve the puzzle.

      Input

      First line, n, m.

      The following n lines, each line is a m-length string, represting the original state. (0 means on, 1 means off and 2 means a block)

      1<=n,m<=300

      number of blocks<=max(n,m)

      Output

      n lines, each line is a m-length string. It's obvious that if a valid solution exists, there exists a solution that every switch is flipped no more than once. So 1 means the switch is flipped once and 0 means the swtich remains unflipped. Of course, a block do not contain a swtich, so for the cell, you should always output 0. 

      It's guaranteed that there always exists a solution. If there are multiple solutions, output any of them. 

      Firsline, n, m.
      The following n lines, each line is a m-length string, represting the original state. (0 means on, 1 means off and 2 means a block

      Example

      Input:
      2 3
      011
      121
      
      Output:
      001
      100
      

      Added by:sevenkplus
      Date:2011-09-12
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9543. Dynamic Congruence Equation System

      Problem code: DCES


      Consider the congruence equation system as the following form:

      x[1] = k1 x[p1] + b1 (mod 10007)
      x[2] = k2 x[p2] + b2 (mod 10007)
      ...
      x[n] = kn x[pn] + bn (mod 10007)

      We will ask you to achieve some instructions as the following form:

      • A i: Ask the current x[i]'s value. (or "-1" for no solution, "-2" for multiply solution.)
      • C i k p b: Modify the ith congruence equation to a new one.

      Input

      The first two lines are N and Q.
      Than following Q lines are the query above.

      (.. N ≤ 30, 000, Q ≤ 100, 000 .. .)

      Output

      For each query, print the result.

      Example

      Input 1:
      5
      2 2 1
      2 3 2
      2 4 3
      2 5 4
      2 3 5
      5
      A 1
      A 2
      C 5 3 1 1
      A 4
      A 5
      Output 1:
      4276
      7141
      4256
      2126

      Input 2:

      4
      0 1 0
      1 3 0
      1 4 0
      1 2 0
      6
      A 1
      A 2
      A 3
      A 4
      C 1 1 5 1
      A 1

      Output 2:

      0
      -2
      -2
      -2
      -1


      Added by:xiaodao
      Date:2011-09-14
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.0.0-8
      Resource:FHQ's query









      SPOJ Problem Set (classical)

      9547. Counting d-pairs

      Problem code: DPAIR

      You're given a sequence A of N non-negative integers. Answer Q queries, where each query consists of two integers: a, b. The answer is number of pairs of integers i and j that satisfy these conditions:

      (1) 1 <= i <= j <= N

      (2) a <= j-i+1 <= b

      (3) all elements of A with indices from range [i, j] are mutually distinct. (indexing starts with 1)

      Constraints :

      1 <= N <= 8*10^5
      1 <= Q <= 2*10^5
      0 <= A[k] <= 10^6, for every integer k between 1 and N, inclusive

      1 <= a <= b <= N

      Input

      First line of input contains integer N. Second line contains N integers representing sequence A. Third line is integer Q, number of queries. Next Q lines has 2 integers, a and b.

      Output

      In the i-th line output the answer for i-th query.

      Example

      Input:
      5
      1 2 3 4 5
      1
      1 1

      Output:

      5

      NOTE: IO is huge

      Added by:Buda IM
      Date:2011-09-16
      Time limit:0.800s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem, thanks to lpp









      SPOJ Problem Set (classical)

      9569. Sum of Pairwise Products

      Problem code: PAIRSUM

      Given N non negative numbers, the task is to answer M queries.

      Each query is as follows: 

      Given u,v you need to find the pairwise product sum (u and v are zero indexed)

      auau + au+1au+1 + au+1au + au+2au+2 + au+2au+1 + au+2au + ... + avav + avav-1 + ... + avau

      Input

      <N>

      <a0> <a1> ... <aN-1>

      <M>

      <u1> <v1>

      <u2> <v2>

      ...

      <uM> <vM>

       

      Output

      Print the answer for each query in a seperate line.

      Example

      Input:
      5
      2 0 1 3 3
      3
      0 2
      1 2
      3 4
      Output:
      7
      1
      27

      Constraints
      u>=0, u<N
      v>=0, v<N
      u<=v
      N<=100000
      M<=100000
      0 <= ai <= 1000000


      Added by:Manukranth
      Date:2011-09-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9570. Counting binary strings

      Problem code: STRCOUNT

      Let f(n,k) is the number of length n binary strings for which the length of the longest substring of ones is equal to k. You have to build a table of these values.

      Input

      None.

      Output

      63 lines - the n-th of them consists of n+1 values: f(n,0) f(n,1) ... f(n,n).

      Example

      1 1
      1 2 1
      1 4 2 1
      1 7 5 2 1

      ...



      Added by:Noszály Csaba
      Date:2011-09-20
      Time limit:1s
      Source limit:3333B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:folklore









      SPOJ Problem Set (classical)

      9576. Dynamic Graph Connectivity

      Problem code: DYNACON2


       

      A graph initially consists of N (1 ≤ N ≤ 100,000) unconnected vertices. The vertices are numbered from 1 to N.

      Your task is to maintain that graph and answer connectivity queries.

      All edges in the problem are undirected.

      You will receive the following queries, where (1 ≤ A, B ≤ N) :

      • add A B : add an edge between vertices A and B, where initially there is no path between A and B.
      • rem A B : remove edge between vertices A and B, where initially there is an edge between A and B.
      • conn A B : print YES if there is a path between A and B and NO otherwise, where A and B are different.

      Input

      The first line of input contains the number of vertices N and the number of queries M (1 ≤ M ≤ 100,000). The following M lines contain queries.

      Output

      For each conn query output YES or NO. Pay attention to letter case.

      Example

      Input:
      4 11
      add 1 2
      add 2 3
      add 3 4
      add 1 4
      conn 4 2
      rem 1 2
      conn 2 4
      rem 3 4
      conn 4 2
      add 2 4
      conn 4 2

      Output:
      YES
      YES
      NO
      YES

      This example will be the first test case.

      Added by:Andrey Naumenko
      Date:2011-09-22
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9577. Dynamic Tree Connectivity

      Problem code: DYNACON1

       

      A forest of unrooted trees initially consists of N (1 ≤ N ≤ 100,000) single-vertex trees. The vertices are numbered from 1 to N.

      Your task is to maintain that forest and answer connectivity queries.

      All edges in the problem are undirected.

      You will receive the following queries, where (1 ≤ A, B ≤ N) :

      • add A B : add an edge between vertices A and B, where initially there is no path between A and B.
      • rem A B : remove edge between vertices A and B, where initially there is an edge between A and B.
      • conn A B : print YES if there is a path between A and B and NO otherwise, where A and B are different.

      Input

      The first line of input contains the number of initial single-vertex trees N and the number of queries M (1 ≤ M ≤ 100,000). The following M lines contain queries.

      Output

      For each conn query output YES or NO. Pay attention to letter case.

      Example

      Input:
      5 11
      conn 1 5
      add 1 2
      add 1 3
      add 3 4
      add 5 4
      conn 1 5
      rem 4 5
      conn 1 5
      rem 3 4
      add 3 5
      conn 1 5

      Output:
      NO
      YES
      NO
      YES

      This example will be the first test case.

      Added by:Andrey Naumenko
      Date:2011-09-23
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9587. The Prime conjecture

      Problem code: PRIMEZUK

      Euclid may have been the first to prove that there are infinitely many primes. Let's walk through his proof, as even today, it's regarded as an excellent model of reasoning.

      Let us assume the converse, that there only a finite number of primes: p1, p2, ..., pn. Let m = 1 + i=1Πpi, i.e. the product of all of these primes plus one. Since this number is bigger than any of the primes on our list, m must be composite. Therefore, some prime must divide it. But which prime? In fact, m leaves a reminder of 1 when divided by any prime pi, for 1 <= i <= n. Thus, p1, p2, ..., pn cannot be the complete list of primes, because if so m must also be a prime. Since this contradicts the assumption it means there cannot exist such a complete list of primes; therefore the number of primes must be infinite!

      Your mathematician friend Wannabe_Fermat has come up with a conjecture which he keeps telling to anyone who is willing to lend an ear: "The number m that we come up with when multiplying any n distinct prime numbers and adding 1 to this result is also a prime". You as Wannabe_Zuckerburg, are becoming jealous as your friend's conjecture is gaining popularity and decide to come up with a program that finds counter-examples to shut him up forever.

      Input

      The first line contains T, the number of test-cases. Each test-case consists of two lines, the first line containing the number n - the number of primes in our list, and second line containing n space-separated prime numbers. Moreover, following things can be safely assumed:

      1 <= T <= 10

      n will be atmost 9 and m can be contained in 32-bits.

      Output

      For each input case x, the output is of the format "Case #x: y", where y = m if m is a prime, else y is the largest prime factor of m.

      Example

      Input:
      2
      3
      2 3 5
      4
      2 7 5 11 
      Output:
      Case #1: 31
      Case #2: 257
      Explanation:
      Case #1 - 31 is a prime number
      Case #2 - 2*5*7*11 + 1 = 771, which can be written as 3*257.

      Added by:Siddharth Kothari
      Date:2011-09-25
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      9636. A Canvas Building

      Problem code: ACANVAS

      Original statement in spanish at http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

      The International Canvas Preparation Committee (ICPC) has a peculiar procedure for setting up its canvases. The procedure depends on a bidimensional view of the canvases.

      A given canvas is set up using N poles of different heights. To set up the canvases, the ICPC uses the following procedure. First, N+2 points are marked on the floor, all on the same line, so that two consecutive points are always separated by a distance of exactly two feet. Afterwards, a pole is placed vertically over each of the N central points. Finally, the canvas is extended over the poles, joining the upper end of each pole with the upper end of neighboring poles. The first and last poles are joined with the free points on the floor.

      The next figure shows 3 possible ways of setting up a canvas using the instructions mentioned before, with pole heights of 4, 5, 7, 8 and 9.

      After years of hard work, the ICPC came to the conclusion that in order to obtain useful and sturdy canvases, it is necessary that the angle formed by two consecutive patches of canvas at the end of a pole, measured towards the inside, is strictly less than 180 degrees. In the figure shown, only the canvas on the left satisfies this condition. The canvas in the middle has an angle greater than 180 degrees at poles of heights 4 and 7, while the canvas on the right has an angle of exactly 180 degrees at the pole of height 8. We say a canvas is valid when it adheres to the ICPC recommendation.

      Of course, given the number of poles and their heights, there are a lot of different ways of placing them, some of which will produce valid canvases and some of which will not. The task at hand is to, given this data, count the number of different valid canvases which can be set up. Two valid canvases are considered different if the sequence of heights of the poles in one of them, read from left to right, is different from the sequence of heights of the other one, read in the same way.

      Input

      The input contains several test cases. Each test case is described on two consecutive lines. The first line contains one integer N which indicates the number of poles (1 <= N <= 60). The second line contains N integers H_i representing the heights of the poles in feet (1 <= H_i <= 109 for 1 <= i <= N). The last line of the input contains a single -1 and should not be processed as a test case.

      Output

      For each test case output a single line with an integer representing the number of different valid canvases which can be set up using the given poles.

      Example

      Input:

      5
      4 5 7 8 9
      7
      33 65 57 64 63 61 49
      1
      1000000000
      3
      2 2 3
      3
      1 3 1
      4
      2 2 2 2
      -1
      

      Output:

      2
      16
      1
      1
      0
      0
      

      Added by:Pablo Ariel Heiber
      Date:2011-10-04
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2011









      SPOJ Problem Set (classical)

      9637. Black and White

      Problem code: BANDW

      Original statement in spanish at http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

      The famous game Black and White is a solitaire which is played using a set of identical chips. Each chip has two faces with different colors. Surprisingly enough, those colors are black and white.

      The game starts by placing N chips forming a single line. There exists an objective pattern which is a given sequence of N colors black or white. In a single move, the player can choose a group of consecutive chips and invert their color, in other words, for each chip in the group, the color which was facing up, is facing down and the one which was facing down is facing up. The game finishes when the facing up colors of the chips are equal to the objective pattern.

      Barby has just discovered this game and soon she realized that you can always won by inverting each chip individually if needed. To make this game more challenging to her, she wanted to win in the least possible number of moves. Note that Barby just cares about how many moves she makes, and it doesn't matter how many chips are inverted in each move. To know how well is Barby playing, she asked you to make a program that given the chip's initial position and the objective pattern, shows the least possible number of moves to win the game. Are you going to say no?

      Input

      The input contains several test cases. Each test case is described in a single line that contains two non-empty words S and T of equal size and at most 500 letters each. S indicates the chip's initial position while T represents the objective pattern. Both words only contain uppercase letters "B" and "N", representing respectively White and Black. The last line of the input contains two asterisks separated by a single space and should not be processed as a test case.

      Output

      For each test case output a single line with an integer representing the least possible number of moves such that you can change the chip's which are initially positioned as described in S to form the pattern given by T.

      Example

      Input:

      BBNBBNBBBB NNNNNBBNNB
      BNBNB NBNBN
      BNBN NBNB
      B B
      * *
      

      Output:

      3
      1
      1
      0
      

      Added by:Pablo Ariel Heiber
      Date:2011-10-04
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2011









      SPOJ Problem Set (classical)

      9638. Circuits

      Problem code: CIRCUITS


      Original statement in spanish at http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

      Everyone is aware of the existence of the well known Nordenskjold Archipelago, located in the Arctic Ocean and belonging to the Krasnoyarsk Krai of Russia. This archipelago consists of a groups of N islands and M aquatic routes between some pairs of islands. Each route connects a pair of islands and for each pair there is at most one route connecting them.

      Considering the popularity of Nordenskjold Archipelago, Krasnoyarsk's authorities are concerned about its touristic value. The touristic value of the archipelago is given by the total number of islands that belong to at least one “touristic circuit”. A touristic circuit is a path starting and ending in the same island that visits at least three different islands, never visits the same island more than once and uses just aquatic routes to go from one island to the next one.

      Krasnoyarsk's authorities want to know the minimum number of additional aquatic routes that must be built so that every island belongs to at least one touristic circuit. Your task is to write a program that answers this question.

      Input

      The input contains several test cases. Each test case is described in several lines. The first line contains two integer numbers N and M (3 <= N <= 100, 1 <= M <= 1000) which indicate the number of islands and the number of aquatic routes, respectively. Each island is identified by a number between 1 and N. Each of the next M lines contains two integers U and V (1 <= U < V <= N), indicating that there is an aquatic route connecting islands U and V. You may assume that in each test case there is at most one aquatic route connecting the same pair of islands. The last line of the input contains the number -1 twice and should not be processed as a test case.

      Output

      For each test case output a single line with an integer representing the minimum number of additional aquatic routes that must be built so that every island belongs to at least one touristic circuit.

      Example

      Input:

      3 1
      1 3
      9 10
      1 2
      2 3
      1 3
      7 9
      5 9
      5 7
      6 8
      4 6
      4 8
      8 9
      4 4
      1 2
      1 4
      1 3
      2 3
      12 9
      1 7
      2 6
      4 9
      9 10
      8 12
      1 5
      1 8
      8 11
      4 10
      -1 -1

      Output:

      2
      0
      1
      4

      Added by:Pablo Ariel Heiber
      Date:2011-10-04
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2011









      SPOJ Problem Set (classical)

      9640. Equilibrium

      Problem code: EQUI


      Original statement in spanish at http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

      The mean and the median usually confuse the students because of their similar spelling, but they are quite different concepts. In this problem we are going to work with the mean and the median of a set consisting of N pairwise distinct integers, where N is odd. The mean of such set is defined, as usual, as the sum of the numbers divided by N, while the median is the unique element in the set that is greater than (N-1)/2 of its elements, and less than the other (N-1)/2 elements in the set. For instance, if the set is {0, 2, 6, 4, 13}, then the mean is 5 while the median is 4.

      We aim to make student's lives easier by generating "balanced" sets, that is, sets consisting of an odd number of pairwise distinct integers where the mean and the median coincide. For example, the set {0, 2, 6, 4, -2} is balanced, since it has N=5 different integers, and the mean and the median are both equal to 2.

      The following procedure has been suggested in order to obtain balanced sets. A set with an even number of distinct integers is chosen, and an extra integer distinct from every element in the set is added to it, in such a way that the resulting set is balanced. We want you to check if the given procedure works. Therefore your task is, given N-1 distinct integers, with odd N, count the number of balanced sets that can be formed by following the described procedure.

      Input

      The input contains several test cases. Each test case is described with two lines. The first line contains a single odd positive integer N that indicates the number of elements the balanced set must have (3 <= N <= 499). The second line contains N-1 distinct integers Z_i that represent the given elements of the set (-1014 <= Z_i <= 1014 for 1 <= i <= N-1). The last line of the input contains the number -1, and should not be processed as a test case.

      Output

      For each test case, output a single line with an integer representing the total number of different balanced sets that can be obtained by adding an integer to the given set, as explained in the problem description.

      Example

      Input:

      5
      0 2 6 4
      7
      1 2 3 4 5 8
      3
      -100000000000000 100000000000000
      -1
      

      Output:

      3
      1
      3
      

      Added by:Pablo Ariel Heiber
      Date:2011-10-04
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2011









      SPOJ Problem Set (classical)

      9641. Factory of Bridges

      Problem code: FBRIDGES

      Original statement in spanish at http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

      In the Central Area of Macedonia there is a river following the East-West direction. The region's inhabitants want to build a bridge that crosses the river in the North-South direction, a task for which they have contracted the cheapest bridge factory they know, the Short Bridge Construction Company. As shown by its name, this construction company specializes in building the shortest possible bridges for each river.

      The first thing that the company does is to model the river's shores (Northern and Southern). Each of these is considered as being formed by semicircles of varying radii, alternatively oriented to one side or the other, with all their centers collinear. The two lines that are defined by the centers of the semicircles of each shore have the East-West direction, and are separated by a distance A one from the other. The value A is called the width of the river. Note that both shores are aligned, that is, the Northern shore neither begins nor ends further to the West or to the East than the Southern shore.

      In the following figure you can see the model of a certain river. In the Northern shore the semicircle furthest to the West is oriented to the North, whereas in the Southern shore the semicircle furthest to the West is oriented to the South. In each shore the orientations of the following semicircles alternate. The shortest possible bridge in the North-South direction is the one shown.

      Your task is to help the construction company finding the length of the shortest possible bridge connecting both shores of the river in the North-South direction.

      Input

      The input contains several test cases. Each test case is described by three lines. The first line contains an integer number A, denoting the width of the river in meters (3 <= A <= 104). The second line describes the Northern shore of the river, while the third line describes its Southern shore.

      The description of each shore begins with an integer number C giving the number of semicircles that are used to model that shore (1 <= C <= 1000). This is followed by a character "N" or "S", meaning that the semicircle furthest to the West in this shore is oriented to the North or to the South, respectively. The description ends with C integer numbers R_i, representing the radii in meters of the semicircles that form the shore (1 <= R_i < A/2 for 1 <= i <= C). The semicircles are given in order, from the one furthest to the West (radius R_1) to the one furthest to the East (radius R_C). The orientations of the semicircles alternate between North and South after the first semicircle, whose orientation is given as described above. Assume that in each test case both shores are aligned, which implies that the sum of the radii of the semicircles forming each shore is the same.

      The end of the input is denoted by a line containing the number -1.

      Output

      For each test case, print a single line containing a rational number representing the length in meters of the shortest bridge that connects both shores of the given river in the North-South direction. Round the result to the nearest rational number with 2 decimal digits. In case of ties, round up. Note that you should always print 2 digits after the dot, even if this means ending with a zero.

      Example

      Input:

      5
      3 N 1 2 1
      2 S 2 2
      3
      1 N 1
      1 S 1
      3
      1 S 1
      1 N 1
      -1
      

      Output:

      1.54
      3.00
      1.00
      

      Added by:Pablo Ariel Heiber
      Date:2011-10-04
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2011









      SPOJ Problem Set (classical)

      9642. Getting There Fast

      Problem code: GETFAST


      Original statement in spanish at http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

      Gabriela drives a school bus. Being one of the few women who have that job, she is always mocked by the male drivers. To improve her status, she decided that besides driving responsibly she is going to drive more efficiently. Her idea is to finish her route spending as little time as possible, without violating any traffic rule.

      The bus Gabriela drives has a very modern driving system that allows her to adjust the acceleration to any real number instantly. Hence, the acceleration is constant by intervals, jumping to another acceleration whenever Gabriela decides so. If v is the bus' speed at a given instant of time, and a its acceleration that remains constant over a period of time t, then the speed at the end of that period will be v + at. Moreover, the bus will move a distance of at2/2 + vt during that period of time.

      The traffic rules prevent vehicles from using an acceleration greater than A, or a deceleration less than D, i.e. the acceleration a at any time must satisfy -D <= a <= A. Moreover, there are check points along the route of the bus where the speed must lie within a certain given interval.

      Gabriela knows in advance the location of the check points, the total length of the route, and the constants A and D. At the beginning of the route the speed and acceleration of the bus are both 0. There are no additional restrictions regarding the speed or the acceleration the bus must have at the end of the route (in particular, it is not necessary to stop in the end). Your job is to use this data to determine the minimum time that Gabriela needs in order to finish the route without violating the rules.

      Input

      The input contains several test cases. Each test case is described using several lines. The first line of each test case contains four integers N, L, A and D. N represents the total number of check points that are present in Gabriela's route (1 <= N <= 105). L indicates the length of the route in meters (2 <= L <= 107). A and D represent, respectively, the maximum allowed acceleration and deceleration for the bus (1 <= A, D <= 100). Each of the following N lines describe a different check point using three integers X, V and W that represent, respectively, the distance between the check point and the starting point of the route (1 <= X <= L-1), the minimum speed, and the maximum speed allowed for the bus at the time it passes by that check point (1 <= V, W <= 100). Assume that in each test case the check points are given in ascending order of distance from the start point of the route, and no two check points are at the same distance from the start point. In this problem, the length is expressed in m (meters), the speed in m/s, and the acceleration in m/s2. The end of the input is indicated by a line containing the number -1 four times, and should not be processed as a test case.

      Output

      For each test case, output a single line containing a rational that represents the minimum time (in seconds) needed for Gabriela to finish her route without violating any traffic rule, or an asterisk if it is impossible to do that. Round the answer to the nearest rational with two decimal digits. In case of a tie, round up. Print exactly two digits after the decimal point, even if that means ending the number with 0's.

      Example

      Input:

      1 40 10 1
      20 21 21
      1 40 10 5
      20 20 20
      1 20 10 50
      10 14 15
      5 1000 2 5
      400 30 80
      600 35 50
      700 10 30
      900 30 40
      950 10 30
      -1 -1 -1 -1
      

      Output:

      *
      2.83
      2.00
      35.96
      

      Added by:Pablo Ariel Heiber
      Date:2011-10-04
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2011









      SPOJ Problem Set (classical)

      9643. He is Lazy

      Problem code: HEISLAZY

      Original statement in spanish at http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

      As we all know, Humberto is really lazy. He is so lazy that he sticks his nose out of the window so that the wind will blow it for him. Obviously, he hasn't worked at all in his whole life. However, he got lucky and won a lot of money in the lottery. With some of that money he bought an empty field, and made build several houses inside of it, where he moved with his family and friends. Thus, Humberto can go in a straight line from any point in his field to any other, without having to make detours because of urban design (for the sake of simplicity, we consider the objects in Humberto's field as dots, so they don't interfere in Humberto's way).

      Sadly, that was not enough for Humberto, so in order to walk even less he decided to have installed some catapults in strategic points of his field. Each catapult can send him from the point where it is installed, to any point at a certain fixed distance (that depends on the range of the catapult).

      But, in spite of simplifying his life, the catapults made the task of choosing a way in the field a real headache, because Humberto wants to walk as less as possible. As tired as he is of all his problems, he decided to use the rest of his money to hire you to tell him the minimum distance he has to walk to move from a given point in the field to another.

      Input

      The input contains several test cases. Each test case is described in several lines. The first line contains five integers N, P_X, P_Y, L_X and L_Y. N represents the number of catapults in the field (1 <= N <= 100). The pair (P_X, P_Y) indicates the coordinates in the XY plane ot the starting point for Humberto, while the pair (L_X, L_Y) indicates analogously the destination point (1 <= P_X, P_Y, L_X, L_Y <= 109). Each of the next N lines describes a different catapult, using three integers C_X, C_Y and F, that indicate the point (C_X, C_Y) where the catapult of strength F is installed. This means that Humberto may move, without walking, from the point (C_X, C_Y) to any point in the plane that is at a distance of exactly F from (C_X, C_Y). Assume that in each test case all the points given in the plane are different. The end of the input is indicated by a single line containing the number -1 five times, and it should not be processed as a test case.

      Output

      For each test case, output a single line containing a rational number that represents the minimum distance Humberto has to walk in order to get from the starting point to the destination point, using some or none of the catapults. Round the answer to the nearest rational with two decimal digits. In case of a tie, round up. Print exactly two digits after the decimal point, even if that means ending the number with 0's.

      Example

      Input:

      1 10 10 20 10
      11 10 9
      1 20 10 10 10
      11 10 9
      2 1 1 12 1
      3 1 6
      8 1 5
      1 12 12 1 1
      6 6 9
      5 10 10 1 1
      3 3 7
      8 3 7
      8 8 7
      3 8 7
      5 5 5
      -1 -1 -1 -1 -1
      

      Output:

      1.00
      10.00
      4.00
      10.41
      5.11
      

      Added by:Pablo Ariel Heiber
      Date:2011-10-04
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2011









      SPOJ Problem Set (classical)

      9644. Imperialism

      Problem code: IMPER

      Original statement in spanish at http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

      The ambition of conquest and expansion is a very well known disease in planet Earth... and also in the entire universe.

      In planet “Imperius” several fortresses have been built one at a time and each one of them but the first was connected at the moment of its construction to a previously built fortress by a direct path, for commercial purposes.

      Imperius was becoming one of the most peaceful and prosperous planet in the universe, until they built no more fortresses. At that moment, N different empires emerged (numbered from 1 to N), each one of them dominating a different fortress. And the thirst of conquest took Imperius. Thus, every year, exactly one of the living empires conquers every neighbor empire, and dominates every fortress belonging to them. Two empires are considered neighbors if there exist two fortresses joined by a path, each one dominated by one different empire of these two.

      Eventually a single empire will dominate every fortress. Your task is to find the minimum number of years such that this can happen.

      As an example, on the left side of the figure below a possible scenario in which six fortresses are initially dominated by six different empires is shown. Each fortress is tagged with the identification number of the empire dominating it. If empire 2 conquered every neighbor on the first year, the the situation would be as in the central figure. Finally, if empire 5 conquered his neighbor empires, it would end up dominating every fortress, as seen on the right side of the figure.

                         

      Input

      The input contains several test cases. Each test case is described in two lines. The first line contains an integer N (2 <= N <= 104) representing the number of fortresses in planet Imperius. The next line contains N-1 integers P_i indicating that the fortress i+1 was connected to fortress P_i (1 <= P_i <= i for 1 <= i <= N-1). The last line of the input contains a single -1 and should not be processed as a test case.

      Output

      For each test case output a single line with an integer representing the minimum number of years such that a single empire may dominate every fortress.

      Example

      Input:

      6
      1 2 2 4 5
      7
      1 1 3 3 4 4
      6
      1 2 2 2 2
      -1

      Output:

      2
      2
      1

      Added by:Pablo Ariel Heiber
      Date:2011-10-04
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2011









      SPOJ Problem Set (classical)

      9645. Joy of CompuTenis

      Problem code: JOCTENIS


      Original statement in spanish at http://www.dc.uba.ar/events/icpc/download/problems/taip2011-problems.pdf

      The Modern Club Association organizes every year a tournament of CompuTenis, which is a sport specially adapted to a public without any mensurable physical qualities. The rules of CompuTenis are very complex (suffices to say that they involve coding with your elbow glued to your ear), but fortunately it is not necessary to know them in detail to solve this problem. You just need to know that in a CompuTenis match two players oppose each other, and the match is won by the player that first wins S sets; in turn, each set is composed of several games, and to win a set a player must win at least J games, with a difference of at least D more games won than the opponent.

       

      The tournament has K rounds, and there are N = 2K players in it, who all participate in the first round. In each round each of the remaining participating players is paired with another participating player, in order to play a single match. The winning player of each of these matches advances to the next round, whereas the losing player is automatically disqualified from the tournament. The winner of the only match of round K is thus the winner of the tournament.

       

      It is desirable to make the tournament as long as possible, considering that the matches are broadcast on television and the Association is paid for every minute on air. Given any pair of different players, the Association knows the probability for one of them to win a game against the other. You are a member of the organizing committee, and your task is to prepare the fixture for the matches of each round in order to maximize the expected number of games played in the tournament. Doing this involves deciding which pairs of players will play a match in the first round, and then for each of the following rounds deciding which pair of matches from the previous round will provide the winning players for each match in that round. Note that this can only depend on the identification of the matches in the previous round. The following figure shows a possible fixture for K = 3 rounds and N = 23 = 8 players.

      For the moment, the Association only wants to estimate their earnings, so it is sufficient to tell them the maximum expected number of games that can be played in the tournament.

      Input

      The input contains several test cases. Each test case is described using several lines. The first line contains four integer numbers, K, S, J and D. The value K denotes the number of rounds in the tournament (1 <= K <= 3). The value S denotes the number of sets that a player must win to win a match (1 <= S <= 10). The value J denotes the minimum number of games that a player must win in order to win a set, whereas D indicates that a player should win D more games than its opponent for him to win the set (1 <= D <= J <= 100). The players are identified by different integer numbers from 1 to N = 2K. Each of the following N lines contains N values. In the i-th line, the j-th value is an integer number P_ij such that p_ij = P_ij/100 is the probability that player number i wins a game against player number j (0 <= P_ij <= 100 for 1 <= i, j <= N). You may assume that P_ii = 0 (no player opposes himself) and that P_ij + P_ji = 100 for i and j different.

      The end of the input is denoted by a line containing four times the number -1.

      Output

      For each test case, you should print a line containing a rational number representing the maximum expected number of games that the given tournament can have. The result should be rounded to the nearest rational number with 2 decimal digits. In case of ties, round up. Note that you should always print 2 digits after the dot, even if this means ending with a zero.

      Example

      Input:

      1 1 2 2
      0 50
      50 0
      3 3 6 2
      0 88 2 76 71 24 50 4
      12 0 54 37 84 95 88 98
      98 46 0 66 36 13 33 33
      24 63 34 0 29 21 96 63
      29 16 64 71 0 0 47 13
      76 5 87 79 100 0 56 89
      50 12 67 4 53 44 0 23
      96 2 67 37 87 11 77 0
      -1 -1 -1 -1
      

      Output:

      4.00
      224.08
      

      Added by:Pablo Ariel Heiber
      Date:2011-10-04
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2011









      SPOJ Problem Set (classical)

      9650. Mega Inversions

      Problem code: TRIPINV

      The n^2 upper bound for any sorting algorithm
      is easy to obtain: just take two elements
      that are misplaced with respect to each other
      and swap them. Conrad conceived an algorithm
      that proceeds by taking not two, but three misplaced
      elements. That is, take three elements
      ai > aj > ak with i < j < k and place them in
      order ak; aj ; ai. Now if for the original algorithm
      the steps are bounded by the maximum number
      of inversions n(n-1)/2, Conrad is at his wits' end as
      to the upper bound for such triples in a given sequence. He asks you to write a program
      that counts the number of such triples.

      Input

      The rst line of the input is the length of the sequence, 1 <= n <= 10^5.
      The next line contains the integer sequence a1; a2..an.
      You can assume that all ai belongs [1; n].

      Output

      Output the number of inverted triples.

      Example

      Input:
      4
      3 3 2 1 Output: 2

      Added by:Krzysztof Lewko
      Date:2011-10-05
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Nordic programming contest









      SPOJ Problem Set (classical)

      9652. Robots on a grid

      Problem code: ROBOTGRI

      You have recently made a grid traversing robot that can
      nd its way from the top left corner of a grid to the
      bottom right corner. However, you had forgotten all your
      AI programming skills, so you only programmed your robot
      to go rightwards and downwards (that's after all where the
      goal is). You have placed your robot on a grid with some
      obstacles, and you sit and observe. However, after a while
      you get tired of observing it getting stuck, and ask yourself
      \How many paths are there from the start position to the
      goal position?", and \If there are none, could the robot have
      made it to the goal if it could walk upwards and leftwards?"
      So you decide to write a program that, given a grid of
      size n x n with some obstacles marked on it where the robot
      cannot walk, counts the di erent ways the robot could go
      from the top left corner s to the bottom right t, and if none,
      tests if it were possible if it could walk up and left as well.
      However, your program does not handle very large numbers, so the answer should be
      given modulo 2^31 - 1.

      Input

      On the rst line is one integer, 1 < n <= 1000. Then follows n lines, each with n characters,
      where each character is one of '.' and '#', where '.' is to be interpreted as a walkable
      tile and '#' as a non-walkable tile. There will never be a wall at s, and there will never
      be a wall at t.

      Output

      Output one line with the number of di erent paths starting in s and ending in t (modulo
      2^31 - 1) or THE GAME IS A LIE if you cannot go from s to t going only rightwards and
      downwards but you can if you are allowed to go left and up as well, or INCONCEIVABLE if
      there simply is no path from s to t.

      Example

      Input:
      5
      .....
      #..#.
      #..#.
      ...#.
      ..... Output: 6

      Added by:Krzysztof Lewko
      Date:2011-10-05
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Nordic programming contest









      SPOJ Problem Set (classical)

      9655. Elevator Trouble

      Problem code: ELEVTRBL


      You are on your way to your rst job interview as a program tester, and you are already
      late. The interview is in a skyscraper and you are currently in
      oor s, where you see an
      elevator. Upon entering the elvator, you learn that it has only two buttons, marked UP
      u" and DOWN d". You conclude that the UP-button takes the elevator u
      floors up
      (if there aren't enough
      oors, pressing the UP-botton does nothing, or at least so you
      assume), whereas the DOWN-button takes you d stories down (or none if there aren't
      enough). Knowing that the interview is at
      floor g, and that there are only f
      floors in
      the building, you quickly decide to write a program that gives you the amount of button
      pushes you need to perform. If you simply cannot reach the correct
      floor, your program
      halts with the message "use the stairs".
      Given input f, s, g, u and d (
      floors, start, goal, up, down), nd the shortest sequence
      of button presses you must press in order to get from s to g, given a building of floors,
      or output "use the stairs" if you cannot get from s to g by the given elevator.

      Input

      The input will consist of one line, namely f s g u d, where 1 <= s; g <= f <= 1000000 and
      0 <= u; d <= 1000000. The
      floors are one-indexed, i.e. if there are 10 stories, s and g be in
      [1; 10].

      Output

      You must reply with the minimum numbers of pushes you must make in order to get from
      s to g, or output use the stairs if it is impossible given the con guration of the elvator.

      Example

      Input:
      10 1 10 2 1
      Output:
      6
      

      Added by:Krzysztof Lewko
      Date:2011-10-06
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Nordic programming contest









      SPOJ Problem Set (classical)

      9685. Zombie’s Treasure Chest

      Problem code: ZTC

      Some brave warriors come to a lost village. They are very lucky and find a lot of treasures and a big treasure chest, but with angry zombies.

      The warriors are so brave that they decide to defeat the zombies and then bring all the treasures back. A brutal long-drawn-out battle lasts from morning to night and the warriors find the zombies are undead and invincible.

      Of course, the treasures should not be left here. Unfortunately, the warriors cannot carry all the treasures by the treasure chest due to the limitation of the capacity of the chest. Indeed, there are only two types of treasures: emerald and sapphire. All of the emeralds are equal in size and value, and with infinite quantities. So are sapphires.

      Being the priest of the warriors with the magic artifact: computer, and given the size of the chest, the value and size of each types of gem, you should compute the maximum value of treasures our warriors could bring back.

      Input

      There are multiple test cases. The number of test cases T (T <= 200) is given in the first line of the input file. For each test case, there is only one line containing five integers N, S1, V1, S2, V2.It means the size of the treasure chest is N and the size and value of an emerald is S1 and V1, size and value of a sapphire is S2, V2. All integers are positive and fit in 32-bit signed integers.

      Output

      For each test case, output a single line containing the case number and the maximum total value of all items that the warriors can carry with the chest.

      Example

      Input:
      2
      100 1 1 2 2
      100 34 34 5 3
      
      Output:
      Case #1: 100
      Case #2: 86
      

      This problem is first solved by team Windrunner (Tsinghua University) at 32 minutes after the onsite contest starts. (They have 1 wrong try before they get Accepted.)


      Added by:[Trichromatic] XilinX
      Date:2011-10-10
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Shanghai 2011; Problem Setter: g201513









      SPOJ Problem Set (classical)

      9686. Yummy Triangular Pizza

      Problem code: YUMMY

      Pizzahat has released a new pizza with triangular shaped pieces. This pizza is composed of some equal-sized equilateral triangle. Moreover, all the triangles are connected. Also, if two triangles are directly connected, they must share a common edge.

      How many different shapes of this kind of N-pieces pizza are there? Two patterns are considered as same if they can completely overlap after rotation and shifting (note that flipping is not included).

      Input

      There are multiple test cases. The first line of input contains a single integer denoting the number of test cases.

      For each test case, there is only one line with only one integer N denoting the number of pieces that can be used. (1 <= N <= 16)

      Output

      For each test case, output a single integer denoting the number of possible different shapes of the pizza.

      Example

      Input:
      3
      2
      4
      10
      
      Output:
      Case #1: 1
      Case #2: 4
      Case #3: 866
      

      This problem is first (and only) solved by team Cabbage (Zhongnan University) at 225 minutes after the onsite contest starts. (They have 1 wrong try before they get Accepted.)


      Added by:[Trichromatic] XilinX
      Date:2011-10-10
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Shanghai 2011; Problem Setter: g201513









      SPOJ Problem Set (classical)

      9687. Xavier is Learning to Count

      Problem code: XC

      Xavier, a 9-year-old student, loves playing many kinds of puzzles. One of his favourites is the following:

      Xerier, his classmate, has made many cards. She writes down a single positive number on each of them. No numbers written on different cards are the same. After that she writes down an equation, whose right side is a single positive number chosen by her, and the left side is the sum of p integers:

      Then she asks Xavier put p cards on the corresponding Xi's position to make this equation correct, with an additional condition that Xi should be ordered from smaller to bigger, i.e.

      Every time Xavier immediately comes up with many solutions. Now he wants to know how many solutions in total are there for any n given by Xerier.

      Input

      There are multiple test cases. The number of them is given in the beginning of the input. Then a series of input block comes one by one.

      For each test case:

      The first line contains two space-separated integers m and p (1<=p<=5). The second line contains m distinct positive integers - the numbers written on each of the cards. None of these integers exceeds 13000.

      There are about 120 test cases in total, but 90% of them are relatively small. More precisely, all numbers are less than or equal to 100 in 90% of the test cases.

      Output

      For each test case:

      For each positive integer, output the number of ways in a single line. To keep the output finite, only numbers with positive ways should be outputted.

      Output a blank line after each test case. See sample for more format details.

      Example

      Input:
      3
      3 3
      1 2 3
      5 4
      1 3 5 6 7
      10 3
      1 2 3 4 5 6 7 8 9 10
      
      Output:
      Case #1:
      6: 1
      
      Case #2:
      15: 1
      16: 1
      17: 1
      19: 1
      21: 1
      
      Case #3:
      6: 1
      7: 1
      8: 2
      9: 3
      10: 4
      11: 5
      12: 7
      13: 8
      14: 9
      15: 10
      16: 10
      17: 10
      18: 10
      19: 9
      20: 8
      21: 7
      22: 5
      23: 4
      24: 3
      25: 2
      26: 1
      27: 1
      
      

      This problem has 82 submissions during the onsite contest, but none of them gets Accepted.


      Added by:[Trichromatic] XilinX
      Date:2011-10-10
      Time limit:99s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Shanghai 2011; Problem Setter: Blue Mary; Special Thanks: Gustav Matula









      SPOJ Problem Set (classical)

      9689. Very Boring Homework

      Problem code: VBWORK

      Prof. Z thinks his homework is very hard for most of his students to solve (do you remember the task "Boring Homework"?) To his surprise, many students hand in correct solutions. He thinks the reason is actually the small size of the data set he used to test students' programs rather than the low difficulty of the homework task. He decides to give his students the same homework again, but with enormous test cases. Of course, his students think his homework becomes even more boring this time. They need your help again.

      For the ones who don't know what homework Prof. Z. had given to his students last time:

       

      You're asked to draw a graph of a binary search tree (BST).

       

      A binary search tree, which may sometimes also be called ordered or sorted binary tree, is a node-based binary tree data structure which has the following properties:

      1. The left subtree of a node contains only nodes with keys less than the node's key.
      2. The right subtree of a node contains only nodes with keys greater than the node's key.
      3. Both the left and right subtrees must also be binary search trees.

      --from Wikipedia

       

      Given a list of integer keys that should be inserted into the BST one by one orderly, we can form a unique BST. Moreover, Prof. Z wants the students to draw the graph of this BST.

      The rules to draw a graph of a BST are listed below:

      1. The graph of a 1-node BST is a single 'o' (15th small Latin letter).
      2. If a BST has a non-empty subtree, draw a single '|' just above the subtree's root, and a single '+' just above the previous drawn '|'. Finally, in the row of '+', use the least number (including 0) of '-'s to connect '+' (corresponding to the left or right subtree) and 'o' (denoting the parent node of the subtrees).
      3. The left subtree (if exists) must be drawn on the left side of its parent. Similarly, the right subtree (if exists) must be drawn on the right side of its parent.
      4. The column of the BST's root must not contain any characters belonging to left or right subtree.
      5. For each node of the BST, the graph of its left subtree and the graph of its right subtree do not share common columns in the picture of the whole tree.

      After the whole BST has been drawn, we number the rows from top to bottom, counting from 1, and so do the columns from left to right, counting from 1.

      Due to the large scale of the tree, the graph will become so large that it is impossible for Prof. Z to check every detail of the graph this time. So you are only asked to hand in m fragments of that graph to Prof. Z instead of the whole one.

      Input

      The first line contains T, the number of test cases. T test cases follow.

      For each test case:

      The first line contains a positive integer N (N <= 100000).

      The second line contains N distinct integers, each of which can be represented by a 32-bit signed integer. These numbers should be inserted into an empty BST one by one in the given order.

      The third line contains an integer M (M <= 5).

      M lines follow, each contains four integers, which are the row and column number of the top left corner, and the number of rows Ri and columns Ci of the required graph fragment, respectively. All the input integers will be positive and fit into a 32-bit signed integer, except Ri and Ci, which will be less than or equal to 200 and greater than 0.

      Output

      For each test case:

      Output the case number counting from 1 in the first line.

      Then M blocks follow, each contains Ri (or less, see next) lines. Each line should contain exactly Ci characters. Use space (ASCII 32) to fill in the blank. But if a line contains only whitespaces, this line should not be outputted.

      Output a blank line after each graph fragment.

      Be careful with space characters in your output, any extra whitespace will cause Wrong Answer.

      Example

      Input:
      3
      3
      3 1 2
      2
      1 1 5 3
      1 2 5 2
      6 4 5 6 1 3 2
      1
      1 1 8 10
      10
      2 6 7 4 5 3 1 9 10 8
      2
      1 1 5 5
      3 6 5 5
      
      Output:
      Case #1:
      +-o
      |  
      o+ 
       | 
       o 
      
      -o
      + 
      | 
      o 
      
      Case #2:
      +--o+     
      |   |     
      o-+ o+    
        |  |    
       +o  o    
       |        
       o        
      
      Case #3:
      +o---
      |    
      o  +-
         | 
        +o+
      
      o+   
       |   
       o-+ 
         | 
        +o+
      
      

      This problem is first solved by team Seraphim (Shanghai Jiao Tong University) at 234 minutes after the onsite contest starts.

       


      Added by:[Trichromatic] XilinX
      Date:2011-10-10
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Shanghai 2011; Problem Setter: Blue Mary









      SPOJ Problem Set (classical)

      9690. Universal Question Answering System

      Problem code: UQAS

      Every student needs help from getting new knowledge by asking questions. Surveys are suggesting that some similar questions are repeated frequently. So it will be nice to develop an automatic question-answering system to answer these questions. Your algorithm should not have any prior knowledge, but it must be able to read sentences and remember the mentioned facts. Whenever the question is asked about such a fact, the system has to answer it properly.

      Input

      The input consists of many dialogues.

      There is a single positive integer T on the first line of input, which denotes the number of following dialogues.(T <= 500, but note that 95% of them are relatively small.) Each dialogue includes one or more lines. Each line contains one sentence: either a statement or a question. Statements end with a dot character (.) while questions end with a question mark (?). There is one extra line after each dialogue. That line ends with an exclamation mark (!). The definitions of the statements and questions will be discussed later.

      Sentences can contain words, spaces and punctuation characters. All words contain only Latin letters and are case-sensitive. Unlike the normal English writing rules, the first letter of a sentence should keep lowercase unless the first word itself should begin with a capital letter. There are no extra spaces between words. No word will have more than 10 characters. There will be at most 1000 lines per dialogue.

      Statements

      Each statement has one of the following forms:

      
      noun_phrase are noun_phrase.
      noun_phrase can verb_phrase.
      everything which can verb_phrase can verb_phrase.
      everything which can verb_phrase are noun_phrase.
      

      noun_phrase and verb_phrase are both single word. The meanings of the four forms are:

      A are B: If X is A, then X is B.
      A can B: If X is A, then X has the ability to B.
      everything which can A can B: If X has the ability to A, X has the ability to B.
      everything which can A are B: If X has the ability to A, X is B.
      

      Questions

      Each question has one of the following forms:

      
      are noun_phrase noun_phrase?
      can noun_phrase verb_phrase?
      can everything which can verb_phrase verb_phrase?
      are everything which can verb_phrase noun_phrase?
      

      They are the question forms of the statements.

      In each test case, the number of different noun phrases will not exceed 100; the number of different verb phrases will not exceed 100.

      Output

      For each test case, output two lines. The first line describes the test case number counting from 1, while the second line contains the same number of characters as the number of questions in this test case. Each character is either Y(denoting you can get that fact logically) or M(otherwise), without quotes. See the example.

      Example

      Input:
      1
      flies can fly.
      flies are insects.
      everything which can fly are animals.
      are everything which can fly insects?
      are flies animals?
      can flies eat?
      everything which can fly can eat.
      can flies eat?
      Bye!
      
      Output:
      Case #1:
      MYMY
      

      This problem is first solved by team Seraphim (Shanghai Jiao Tong University) at 66 minutes after the onsite contest starts.


      Added by:[Trichromatic] XilinX
      Date:2011-10-10
      Time limit:13s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Shanghai 2011; Problem Setter: Blue Mary









      SPOJ Problem Set (classical)

      9691. Triangles and Quadrangle

      Problem code: TQ

      Little Yuan is two years old and she is learning about some triangles and quadrangles. She is such a smart girl that she soon realizes two triangles can form a quadrangle without overlapping each other. She picks up a lot of triangles and uses them to form some quadrangles. Unfortunately, she is not good at this kind of jigsaw game and makes some mistakes.

      As her brother, you are curious about whether she has made a mistake when forming two triangles into a quadrangle. You are thinking about to write a program to determine it.

      Notice that the quadrangle in this problem is defined as a simple polygon with four vertexes. And you may also assume that all triangles and quadrangle have positive area.

      Note that two graphs are considered as the same if and only if they can overlap completely by shifting, rotation and flipping.

      Input

      There are multiple test cases. The first line of input contains a single integer T denoting the number of test cases. (T < 1000)

      For each test case, there are 10 lines in total.The first 3*2 lines describe the two triangles. Each line with two numbers denotes the coordinates of a point.The next 4 lines describe the quadrangle in clockwise order or counter-clockwise order.

      All coordinates are integers and less than 15000 in absolute value.

      Output

      For each test case, output Yes if the given triangles can form the given quadrangle without overlapping, No otherwise. See the example for more output format details.

      Example

      Input:
      2
      0 0
      0 1
      1 0
      0 0
      0 1
      1 0
      -1 0
      0 0
      1 0
      0 1
      0 0
      -1 1
      1 0
      0 0
      0 1
      1 0
      -1 0
      0 0
      1 0
      0 1
      
      Output:
      Case #1: Yes
      Case #2: No
      

      This problem is first solved by team FreeJourney (Wuhan University) at 83 minutes after the onsite contest starts.

      The test set of this problem is not the same as that of the onsite contest.


      Added by:[Trichromatic] XilinX
      Date:2011-10-10
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Shanghai 2011; Problem Setter: g201513









      SPOJ Problem Set (classical)

      9692. Share the Cakes

      Problem code: CAKE4

      Lunar Rose is a pure and kind girl who was born in a serene town on, with surprising coincidence, the Mid-autumn Festival that year. Therefore, on each of her birthday, she enjoys two cakes: for the birthday, and for the festival.

      This year, Lunar would like to share the cakes with Jaddy, her boyfriend, on the nice day, isn't it so romantic? What is the tragedy, Jaddy screwed up, again:

      When Lunar placed two cakes on the table, she wanted Jaddy to cut the cakes for her so that they can both have half of the moon cake and so do the birthday cake. But Jaddy, as a lazy and impetuous guy, he just used a knife to cut them together easily, hence although the two cakes had been cut into two pieces each, they were not really uniform. What was worth? Lunar is a pretty perfectionist and suddenly quite angry with Jaddy due to his arbitrariness. Finally, Lunar chose to leave him. Stupid Jaddy!

      Jaddy became extremely regretful and distressing. Lunar, a softhearted girl, does not have the heart to make him so painful so that she'd like to give Jaddy a chance to do it again. However, she set a strict limit for this task: Jaddy can only use one cut to separate the two cakes into equivalent halves. Evil Ms. Rose!

      Both two cakes are convex polygons; the table and knife are both big enough and long enough thus can be considered as infinite planar and line. This way, tell Jaddy a strategy, which means a line, satisfying Lunar's condition to cut cakes so that he can get her back.

      Input

      The first line of the input data is a positive integer T (T <= 100) indicating the number of test cases. Then T cases follow. Each test case contains description of two cakes (polygons): each polygon begins with an integer n which denotes the number of vertices, and then n pairs of integers (x, y) follows describing the coordinates of vertices in clockwise or counterclockwise order. You may assume that each polygon has no more than 20 vertices and all the coordinates are in range of [-1000, 1000]. Besides, no point is in the two polygons (including their boudary) simultaneously.

      Output

      For each test case, output two real numbers k and b, leading by the case number, which means that Jaddy should cut the cakes along the line y=k*x+b. It is guaranteed that both k and b among the answers are in range of [-10000, 10000]. See sample output for further details.

      We accept answers within 10-4 relative or absolute error.

      Example

      Input:
      2
      3
      0 0
      1 1
      0 2
      3
      2 1
      3 0
      3 2
      4
      0 0
      1 0
      1 1
      0 1
      4
      2 2
      3 2
      3 3
      2 3
      
      Output:
      Case #1: 0 1
      Case #2: 1 0
      

      This problem is first (and only) solved by team Y.E.S (Tsinghua University) at 201 minutes after the onsite contest starts. (They have 1 wrong try before they get Accepted.)

       


      Added by:[Trichromatic] XilinX
      Date:2011-10-10
      Time limit:13s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Shanghai 2011; Problem Setter: lcosvse









      SPOJ Problem Set (classical)

      9693. Revenge of Fibonacci

      Problem code: REVFIB

      The well-known Fibonacci sequence is defined as following:

      Here we regard n as the index of the Fibonacci number F(n).

      This sequence has been studied since the publication of Fibonacci's book Liber Abaci. So far, many properties of this sequence have been introduced.

      You had been interested in this sequence, while after reading lots of papers about it. You think there's no need to research in it anymore because of the lack of its unrevealed properties. Yesterday, you decided to study some other sequences like Lucas sequence instead.

      Fibonacci came into your dream last night. "Stupid human beings. Lots of important properties of Fibonacci sequence have not been studied by anyone, for example, from the Fibonacci number 347746739…"

      You woke up and couldn't remember the whole number except the first few digits Fibonacci told you. You decided to write a program to find this number out in order to continue your research on Fibonacci sequence.

      Input

      There are multiple test cases. The first line of input contains a single integer T denoting the number of test cases (T<=50000).

      For each test case, there is a single line containing one non-empty string made up of at most 40 digits. And there won't be any unnecessary leading zeroes.

      Output

      For each test case, output the smallest index of the smallest Fibonacci number whose decimal notation begins with the given digits. If no Fibonacci number with index smaller than 100000 satisfy that condition, output -1 instead – you think what Fibonacci wants to told you beyonds your ability.

      Example

      Input:
      15
      1
      12
      123
      1234
      12345
      9
      98
      987
      9876
      98765
      89
      32
      51075176167176176176
      347746739
      5610
      
      Output:
      Case #1: 0
      Case #2: 25
      Case #3: 226
      Case #4: 1628
      Case #5: 49516
      Case #6: 15
      Case #7: 15
      Case #8: 15
      Case #9: 43764
      Case #10: 49750
      Case #11: 10
      Case #12: 51
      Case #13: -1
      Case #14: 1233
      Case #15: 22374
      

      This problem is first solved by team Y.E.S (Tsinghua University) at 77 minutes after the onsite contest starts. (They have 2 wrong tries before they get Accepted.)

       


      Added by:[Trichromatic] XilinX
      Date:2011-10-10
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Shanghai 2011; Problem Setter: Blue Mary









      SPOJ Problem Set (classical)

      9694. Quelling Blade

      Problem code: QB

      Mr. Sheep lost himself in a computer game. In this game, he plays the part of a super hero and fight with the evil. The equipment is very important in this game and Mr. Sheep thinks the Quelling Blade is the most powerful weapon.

      In this game, each type of weapon costs hero some money, and brings the hero benefits. If the hero buys two weapons (no matter they have the same type or not), the benefit values are accumulated. That is to say, if the hero buys two weapons with benefit 3 and 5, the hero will get total benefit value 8=3+5.

      There are some requirements for each weapon. If the hero wants to buy a certain weapon, he may need some other weapons first. For example, if hero wants to buy a Divine Rapier, he needs a Demon Edge and a Scared Relic. Of course, if he wants to buy the second Devine Rapier, he must buy another Demon Edge and another Scared Relic first. Notice that the existing weapon will not disappear after the trade. Note that a weapon may need multiple weapons with same type. And you may assume that a type of weapon is required by at most one other type of weapon.

      The hero is busy with combat and has no time to earn money. Fortunately, the game will give the hero 1 coin per second. So if the hero wants to buy a Quelling Blade, the minimum total time for him to achieve his goal can be easily calculated.

      Mr. Sheep is a perfectionist. He not only wants to get the Quelling Blade as soon as possible, but also wants to optimize every second during the game. He defines the utility of the game as the sum of the benefit value of the hero in each second. He calculates the utility from the start of the game until the second he gets Quelling Blade, exclusively. You may refer to the samples for further clarification. In the other words, you should define a way of process to buy the weapons for the hero, which minimize the total time to get Quelling Blade and optimize the utility of the game.

      Input

      There are hundreds of test cases, the number of test case are in the first line of the input. Notice that most of the test cases are relatively small.

      For each test case, the first line contains a single integer N denoting the number of different types of weapons. (1 <= N <= 1000)

      The next lines are describing the weapons. For each weapon, the first line contains two integers B and C, denoting the benefit value and the cost of this kind of weapon. (1 <= B, C <= 231-1) Then a single integer P in the next line describes the number of requirements of this weapon. Next P lines, each line contains two integers I and A, means that this weapon needs A weapons of index I.The indexes of weapons are start from 1 to N. The Quelling Blade is the first type of weapon.

      You may assume that the total numbers of weapons which are needed by the Quelling Blade is less than 1000000. Also notice that Quelling Blade can be brought in a finite game time and a type of weapon can be required by at most one other type of weapon.

      Output

      For each test case, output a single integer denoting the optimal utility. You may assume that the answer fits into 64-bit signed integer.

      Example

      Input:
      2
      3
      1 1
      1
      2 2
      2 1
      1
      3 1
      1 1
      0
      3
      1 1
      1
      2 2
      1 1
      1
      3 1
      2 1
      0
      
      Output:
      Case #1: 14
      Case #2: 17
      

      This problem has no submissions during the onsite contest.


      Added by:[Trichromatic] XilinX
      Date:2011-10-10
      Time limit:13s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Shanghai 2011; Problem Setter: g201513









      SPOJ Problem Set (classical)

      9721. 2s Complement

      Problem code: CODESPTA

       

      One of the basics of Computer Science is knowing how numbers are represented in 2's complement. Imagine that you write down all numbers between A and B in 2's complement representation using 32 bits. How many 1's will you write down in all ?
      Input:
      The first line contains the number of test cases T. Each of the next T lines contains two integers A and B.
      Output:
      Output T lines, one corresponding to each test case.
      Constraints:
      -2^31 <= A <= B <= 2^31 - 1
      Sample Input:
      3
      -2 0
      -3 4
      -1 4
      Sample Output:
      63
      99
      37
      Sample Output:
      For the first case, -2 contains 31 1's followed by a 0 whereas -1 contains 32 1's. Thus the total is 63.
      For the second case, the answer is 31 + 31 + 32 + 0 + 1 + 1 + 2 + 1 = 99

      One of the basics of Computer Science is knowing how numbers are represented in 2's complement. Imagine that you write down all numbers between A and B in 2's complement representation using 32 bits. How many 1's will you write down in all ?

       

      Input:

      The first line contains the number of test cases T. Each of the next T lines contains two integers A and B.

       

      Output:

      Output T lines, one corresponding to each test case.

       

      Constraints:

      -2^31 <= A <= B <= 2^31 - 1

       

      Sample Input:

      3

      -2 0

      -3 4

      -1 4

       

      Sample Output:

      63

      99

      37

       

      Explanation:

      For the first case, -2 contains 31 1's followed by a 0 whereas -1 contains 32 1's. Thus the total is 63.

      For the second case, the answer is 31 + 31 + 32 + 0 + 1 + 1 + 2 + 1 = 99

       


      Added by:Varun Jalan
      Date:2011-10-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint - InterviewStreet Contest









      SPOJ Problem Set (classical)

      9722. Insertion Sort

      Problem code: CODESPTB

       

      Insertion Sort is a classical sorting technique. One variant of insertion sort works as follows when sorting an array a[1..N] in non-descending order:
      for i <- 2 to N
          j <- i
          while j > 1 and a[j] < a[j - 1]
             swap a[j] and a[j - 1]
             j <- j - 1
      The pseudocode is simple to follow. In the ith step, element a[i] is inserted in the sorted sequence a[1..i - 1]. This is done by moving a[i] backward by swapping it with the previous element until it ends up in it's right position.
      As you probably already know, the algorithm can be really slow. To study this more, you want to find out the number of times the swap operation is performed when sorting an array.
      Input:
      The first line contains the number of test cases T. T test cases follow. The first line for each case contains N, the number of elements to be sorted. The next line contains N integers a[1],a[2]...,a[N].
      Output:
      Output T lines, containing the required answer for each test case.
      Constraints:
      1 <= T <= 5
      1 <= N <= 100000
      1 <= a[i] <= 1000000
      Sample Input:
      2
      5
      1 1 1 2 2
      5
      2 1 3 1 2
      Sample Output:
      0
      4

       

      Insertion Sort is a classical sorting technique. One variant of insertion sort works as follows when sorting an array a[1..N] in non-descending order:

       

      for i <- 2 to N

          j <- i

          while j > 1 and a[j] < a[j - 1]

             swap a[j] and a[j - 1]

             j <- j - 1

       

      The pseudocode is simple to follow. In the ith step, element a[i] is inserted in the sorted sequence a[1..i - 1]. This is done by moving a[i] backward by swapping it with the previous element until it ends up in it's right position.

      As you probably already know, the algorithm can be really slow. To study this more, you want to find out the number of times the swap operation is performed when sorting an array.

       

      Input:

      The first line contains the number of test cases T. T test cases follow. The first line for each case contains N, the number of elements to be sorted. The next line contains N integers a[1],a[2]...,a[N].

       

      Output:

      Output T lines, containing the required answer for each test case.

       

      Constraints:

      1 <= T <= 5

      1 <= N <= 100000

      1 <= a[i] <= 1000000

       

      Sample Input:

      2

      5

      1 1 1 2 2

      5

      2 1 3 1 2

       

      Sample Output:

      0

      4


      Added by:Varun Jalan
      Date:2011-10-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint - InterviewStreet Contest









      SPOJ Problem Set ()

      9723. Card Shuffling

      Problem code: CODESPTC

       

      Here is an algorithm for shuffling N cards:
      1) The cards are divided into K equal piles, where K is a factor of N.
      2) The bottom N / K cards belong to pile 1 in the same order (so the bottom card of the initial pile is the bottom card of pile 1).
      3) The next N / K cards from the bottom belong to pile 2, and so on.
      4) Now the top card of the shuffled pile is the top card of pile 1. The next card is the top card of pile 2,..., the Kth card of the shuffled pile is the top card of pile K. Then (K + 1)th card is the card which is now at the top of pile 1, the (K + 2)nd is the card which is now at the top of pile 2 and so on.
      For example, if N = 6 and K = 3, the order of a deck of cards "ABCDEF" (top to bottom) when shuffled once would change to "ECAFDB".
      Given N and K, what is the least number of shuffles needed after which the pile is restored to its original order?
      Input:
      The first line contains the number of test cases T. The next T lines contain two integers each N and K.
      Output:
      Output T lines, one for each test case containing the minimum number of shuffles needed. If the deck never comes back to its original order, output -1.
      Constraints:
      T <= 10000
      2 <= K <= N <= 10^9
      K will be a factor of N.
      Sample Input:
      3
      6 3
      4 2
      5 5
      Sample Output:
      6
      4
      2

       

      Here is an algorithm for shuffling N cards:

      1) The cards are divided into K equal piles, where K is a factor of N.

      2) The bottom N / K cards belong to pile 1 in the same order (so the bottom card of the initial pile is the bottom card of pile 1).

      3) The next N / K cards from the bottom belong to pile 2, and so on.

      4) Now the top card of the shuffled pile is the top card of pile 1. The next card is the top card of pile 2,..., the Kth card of the shuffled pile is the top card of pile K. Then (K + 1)th card is the card which is now at the top of pile 1, the (K + 2)nd is the card which is now at the top of pile 2 and so on.

       

      For example, if N = 6 and K = 3, the order of a deck of cards "ABCDEF" (top to bottom) when shuffled once would change to "ECAFDB".

       

      Given N and K, what is the least number of shuffles needed after which the pile is restored to its original order?

       

      Input:

      The first line contains the number of test cases T. The next T lines contain two integers each N and K.

       

      Output:

      Output T lines, one for each test case containing the minimum number of shuffles needed. If the deck never comes back to its original order, output -1.

       

      Constraints:

      T <= 10000

      2 <= K <= N <= 10^9

      K will be a factor of N.

       

      Sample Input:

      3

      6 3

      4 2

      5 5

       

      Sample Output:

      6

      4

      2

       

       


      Added by:Varun Jalan
      Date:2011-10-15
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint - InterviewStreet Contest









      SPOJ Problem Set (classical)

      9725. Queens on a Board

      Problem code: CODESPTD

       

      You have an N * M chessboard on which some squares are blocked out. In how many ways can you place one or more queens on the board such that no two queens attack each other? Two queens attack each other if one can reach the other by moving horizontally, vertically or diagonally without passing over any blocked square. At most one queen can be placed on a square. A queen cannot be placed on a blocked square.
      Input:
      The first line contains the number of test cases T. T test cases follow. Each test case contains integers N and M on the first line. The following N lines contain M characters each representing the board. A '#' represents a blocked square and a '.' represents an unblocked square.
      Output:
      Output T lines containing the required answer for each test case. As the answers can be really large, output them modulo 1000000007.
      Constraints:
      1 <= T <= 100
      1 <= N <= 50
      1 <= M <= 5
      Sample Input:
      4
      3 3
      ...
      ...
      ...
      3 3
      .#.
      .#.
      ...
      2 4
      .#..
      ....
      1 1
      #
      Sample Output:
      17
      18
      14
      0

       

      You have an N * M chessboard on which some squares are blocked out. In how many ways can you place one or more queens on the board such that no two queens attack each other? Two queens attack each other if one can reach the other by moving horizontally, vertically or diagonally without passing over any blocked square. At most one queen can be placed on a square. A queen cannot be placed on a blocked square.

       

      Input:

      The first line contains the number of test cases T. T test cases follow. Each test case contains integers N and M on the first line. The following N lines contain M characters each representing the board. A '#' represents a blocked square and a '.' represents an unblocked square.

       

      Output:

      Output T lines containing the required answer for each test case. As the answers can be really large, output them modulo 1000000007.

       

      Constraints:

      1 <= T <= 100

      1 <= N <= 50

      1 <= M <= 5

       

      Sample Input:

      4

      3 3

      ...

      ...

      ...

      3 3

      .#.

      .#.

      ...

      2 4

      .#..

      ....

      1 1

      #

       

      Sample Output:

      17

      18

      14

      0

       


      Added by:Varun Jalan
      Date:2011-10-15
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint - InterviewStreet Contest









      SPOJ Problem Set ()

      9734. Hacking the random number generator

      Problem code: HACKRNDM

      You recently wrote a random number generator code for a web application and now you notice that some cracker has cracked it. It now gives numbers at a difference of some given value k more predominantly. You being a hacker decide to write a code that will take in n numbers as input and a value k and find the total number of pairs of numbers whose absolute difference is equal to k, in order to assist you in your random number generator testing.

      NOTE: All values fit in the range of a signed integer, n,k>=1

      Input

      1st line contains n & k.
      2nd line contains n numbers of the set. All the n numbers are assured to be distinct.

      Output

      One integer saying the no of pairs of numbers that have a diff k.

      Example

      Input:
      5 2
      1 5 3 4 2 Output: 3

      Added by:vijay
      Date:2011-10-15
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:Own Problem









      SPOJ Problem Set (classical)

      9746. Bytelandian Tours

      Problem code: CODESPTE

       

      The country of Byteland contains of N cities and N - 1 bidirectional roads between them such that there a path between any two cities. The cities are numbered 0,...,N - 1. The people were very unhappy about the time it took to commute, especially salesmen who had to go about every city selling goods. So it was decided that new roads would be built. A new road was built between every two cities which could be reached from each other by travelling on exactly two old roads.
      Now a salesman situated in city 0, just like any other typical salesman, has to visit all cities exactly once and return back to city 0 in the end. In how many ways can he do this?
      Input:
      The first line contains the number of test cases T. T test cases follow. The first line contains N, the number of cities in Byteland. The following N - 1 lines contain the description of the roads. The ith line contains two integers a_i and b_i, meaning that there was originally a road connecting cities with numbers a_i and b_i.
      Output:
      Output T lines, one corresponding to each test case containing the required answer for that test case. Since the answers can be huge, output them modulo 1000000007.
      Constraints:
      1 <= T <= 20
      1 <= N <= 10000
      0 <= a_i,b_i < N
      Sample Input:
      2
      3
      0 1
      1 2
      5
      0 1
      1 2
      2 3
      2 4
      Sample Output:
      2
      4
      Explanation: For the first case, a new road was build between cities 0 and 2. Now, the salesman has two tour possibilities: 0-1-2-0 or 0-2-1-0.

       

      The country of Byteland contains of N cities and N - 1 bidirectional roads between them such that there a path between any two cities. The cities are numbered 0,...,N - 1. The people were very unhappy about the time it took to commute, especially salesmen who had to go about every city selling goods. So it was decided that new roads would be built. A new road was built between every two cities which could be reached from each other by travelling on exactly two old roads.

      Now a salesman situated in city 0, just like any other typical salesman, has to visit all cities exactly once and return back to city 0 in the end. In how many ways can he do this?

      Input:

      The first line contains the number of test cases T. T test cases follow. The first line contains N, the number of cities in Byteland. The following N - 1 lines contain the description of the roads. The ith line contains two integers a_i and b_i, meaning that there was originally a road connecting cities with numbers a_i and b_i.

       

      Output:

      Output T lines, one corresponding to each test case containing the required answer for that test case. Since the answers can be huge, output them modulo 1000000007.

       

      Constraints:

      1 <= T <= 20

      1 <= N <= 10000

      0 <= a_i,b_i < N

       

      Sample Input:

      2

      3

      0 1

      1 2

      5

      0 1

      1 2

      2 3

      2 4

       

      Sample Output:

      2

      4

       

      Explanation: For the first case, a new road was build between cities 0 and 2. Now, the salesman has two tour possibilities: 0-1-2-0 or 0-2-1-0.

       

       


      Added by:Varun Jalan
      Date:2011-10-18
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint - InterviewStreet Contest









      SPOJ Problem Set (classical)

      9748. Palindromes

      Problem code: CODESPTF

       

      Given a string, you keep swapping any two characters in the string randomly till the string becomes a palindrome. What is the expected number of swaps you will make?
      Input:
      The first line contains the number of test cases T. Each of the next T lines contains a string each.
      Output:
      Output T lines containing the answer for the corresponding test case. Print the answer rounded to exactly 4 decimal places.
      Constraints:
      T <= 10000
      The length of the string will be at most 8 characters.
      The string will consist of only lower-case letters 'a'-'z'.
      There will always be at least one palindrome which can be formed with the letters of the given string.
      Sample Input:
      4
      b
      bb
      abb
      cbaabbb
      Sample Output:
      0.0000
      0.0000
      3.0000
      59.3380
      Explanation:
      For the first two cases, the string is already a palindrome so no swaps are needed.
      For the third case, there are 3 possible swaps. The string will become "bab","bba" or remain "abb" with 1/3rd probability each. It's easy to see that the expected number of swaps needed is 3.0000
      For the last case, the answer is 59.337962..., which should be printed as 55.338

      Given a string, you keep swapping any two characters in the string randomly till the string becomes a palindrome. What is the expected number of swaps you will make?

       

      Input:

      The first line contains the number of test cases T. Each of the next T lines contains a string each.

       

      Output:

      Output T lines containing the answer for the corresponding test case. Print the answer rounded to exactly 4 decimal places.

       

      Constraints:

      T <= 10000

      The length of the string will be at most 8 characters.

      The string will consist of only lower-case letters 'a'-'z'.

      There will always be at least one palindrome which can be formed with the letters of the given string.

       

      Sample Input:

      4

      b

      bb

      abb

      cbaabbb

       

      Sample Output:

      0.0000

      0.0000

      3.0000

      59.3380

       

      Explanation:

      For the first two cases, the string is already a palindrome so no swaps are needed.

      For the third case, there are 3 possible swaps. The string will become "bab","bba" or remain "abb" with 1/3rd probability each. It's easy to see that the expected number of swaps needed is 3.0000

      For the last case, the answer is 59.337962..., which should be printed as 55.3380


      Added by:Varun Jalan
      Date:2011-10-18
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint - InterviewStreet Contest









      SPOJ Problem Set (classical)

      9749. Cliques

      Problem code: CODESPTG

       

      A clique in a graph is set of nodes such that there is an edge between any two distinct nodes in the set. It is well known that finding the largest clique in a graph is a computationally tough problem and no polynomial time algorithm is known for it. However, you wonder what is is the mininum size of the largest clique in any graph with N nodes and M edges. Of course, the graph should have at most one edge between any two nodes and no edges connecting a node to itself.
      Input :
      The first line contains T the number of test cases. Each of the next T lines contain 2 integers : N, M
      Output :
      Output T lines, one for each test case, containing the desired answer for the corresponding test case.
      Sample Input :
      3
      3 2
      4 6
      5 7
      Sample Output :
      2
      4
      3
      Constraints :
      1 <= T <= 100000
      2 <= N <= 10000
      1 <= M <= N*(N-1)/2
      Explanation:
      For the second test case, the only valid graph having 4 nodes and 6 edges is one where each pair of nodes is connected. So the size of the largest clique cannot be smaller than 4.
      For the third test case, it is easy to verify that any graph with 5 nodes and 7 edges will surely have a clique of size 3 or more.

       

      A clique in a graph is set of nodes such that there is an edge between any two distinct nodes in the set. It is well known that finding the largest clique in a graph is a computationally tough problem and no polynomial time algorithm is known for it. However, you wonder what is is the mininum size of the largest clique in any graph with N nodes and M edges. Of course, the graph should have at most one edge between any two nodes and no edges connecting a node to itself.

       

      Input :

      The first line contains T the number of test cases. Each of the next T lines contain 2 integers : N, M

       

      Output :

      Output T lines, one for each test case, containing the desired answer for the corresponding test case.

       

      Sample Input :

      3

      3 2

      4 6

      5 7

       

      Sample Output :

      2

      4

      3

       

      Constraints :

      1 <= T <= 100000

      2 <= N <= 10000

      1 <= M <= N*(N-1)/2

       

      Explanation:

      For the second test case, the only valid graph having 4 nodes and 6 edges is one where each pair of nodes is connected. So the size of the largest clique cannot be smaller than 4.

      For the third test case, it is easy to verify that any graph with 5 nodes and 7 edges will surely have a clique of size 3 or more.

       

       


      Added by:Varun Jalan
      Date:2011-10-18
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint - InterviewStreet Contest









      SPOJ Problem Set (classical)

      9750. Polygon Diagonals

      Problem code: CODESPTH

       

      Consider a regular polygon with N vertices labelled 1..N. In how many ways can you draw K diagonals such that no two diagonals intersect at a point strictly inside the polygon? A diagonal is a line segment joining two non adjacent vertices of the polygon.
      Input:
      The first line contains the number of test cases T. Each of the next T lines contain two integers N and K.
      Output:
      Output T lines, one corresponding to each test case. Since the answer can be really huge, output it modulo 1000003.
      Constraints:
      1 <= T <= 10000
      4 <= N <= 10^9
      1 <= K <= N
      Sample Input:
      3
      4 1
      5 2
      5 3
      Sample Output:
      2
      5
      0
      Explanation:
      For the first case, there are clearly 2 ways to draw 1 diagonal - 1 to 3, or 2 to 4. (Assuming the vertices are labelled 1..N in cyclic order).
      For the third case, at most 2 non-intersecting diagonals can be drawn in a 5-gon, and so the answer is 0.

       

      Consider a regular polygon with N vertices labelled 1..N. In how many ways can you draw K diagonals such that no two diagonals intersect at a point strictly inside the polygon? A diagonal is a line segment joining two non adjacent vertices of the polygon.

       

      Input:

      The first line contains the number of test cases T. Each of the next T lines contain two integers N and K.

       

      Output:

      Output T lines, one corresponding to each test case. Since the answer can be really huge, output it modulo 1000003.

       

      Constraints:

      1 <= T <= 10000

      4 <= N <= 10^9

      1 <= K <= N

       

      Sample Input:

      3

      4 1

      5 2

      5 3

       

      Sample Output:

      2

      5

      0

       

      Explanation:

      For the first case, there are clearly 2 ways to draw 1 diagonal - 1 to 3, or 2 to 4. (Assuming the vertices are labelled 1..N in cyclic order).

      For the third case, at most 2 non-intersecting diagonals can be drawn in a 5-gon, and so the answer is 0.

       

       


      Added by:Varun Jalan
      Date:2011-10-18
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint - InterviewStreet Contest









      SPOJ Problem Set (classical)

      9751. Repairing Roads

      Problem code: CODESPTI

       

      The country of Byteland contains of N cities and N - 1 bidirectional roads between them such that there a path between any two cities. The roads in Byteland were built long ago and now they are in need of repair. You have been hired to repair all the roads. You intend to do this by dispatching robots on some of the roads. Each robot will repair the road he is currently on and then move to one of the adjacent unrepaired roads. After repairing that, he will move to another adjacent unrepaired road, repair that and so on. Two roads are adjacent if they have the same city at one of their endpoints. For the process to be efficient, no two robots will can ever repair the same road, and no road can be visited twice. What is the least number of robots needed to accomplish the task?
      Input:
      The first line contains the number of test cases T. T test cases follow. The first line contains N, the number of cities in Byteland. The cities are numbered 0..N - 1. The following N - 1 lines contain the description of the roads. The ith line contains two integers a_i and b_i, meaning that there is a road connecting cities with numbers a_i and b_i.
      Output:
      Output T lines, one corresponding to each test case containing the required answer for that test case.
      Constraints:
      1 <= T <= 20
      1 <= N <= 10000
      0 <= a_i,b_i < N
      Sample Input:
      3
      4
      0 1
      0 2
      0 3
      6
      0 1
      1 2
      2 3
      2 4
      4 5
      7
      0 1
      1 2
      2 3
      2 4
      4 5
      3 6
      Sample Output:
      1
      1
      2
      Explanation:
      For the first case, one robot is enough to repair all roads: (0,1) -> (0,2) -> (0,3)
      For the second case, one robot is again enough: (0,1) -> (1,2) -> (2,3) -> (2,4) -> (4,5)
      The the third case, there is no way to repair all the roads with one robot and at least two are needed.

       

      The country of Byteland contains of N cities and N - 1 bidirectional roads between them such that there a path between any two cities. The roads in Byteland were built long ago and now they are in need of repair. You have been hired to repair all the roads. You intend to do this by dispatching robots on some of the roads. Each robot will repair the road he is currently on and then move to one of the adjacent unrepaired roads. After repairing that, he will move to another adjacent unrepaired road, repair that and so on. Two roads are adjacent if they have the same city at one of their endpoints. For the process to be efficient, no two robots will can ever repair the same road, and no road can be visited twice. What is the least number of robots needed to accomplish the task?

       

      Input:

      The first line contains the number of test cases T. T test cases follow. The first line contains N, the number of cities in Byteland. The cities are numbered 0..N - 1. The following N - 1 lines contain the description of the roads. The ith line contains two integers a_i and b_i, meaning that there is a road connecting cities with numbers a_i and b_i.

       

      Output:

      Output T lines, one corresponding to each test case containing the required answer for that test case.

       

      Constraints:

      1 <= T <= 20

      1 <= N <= 10000

      0 <= a_i,b_i < N

       

      Sample Input:

      3

      4

      0 1

      0 2

      0 3

      6

      0 1

      1 2

      2 3

      2 4

      4 5

      7

      0 1

      1 2

      2 3

      2 4

      4 5

      3 6

       

      Sample Output:

      1

      1

      2

       

      Explanation:

      For the first case, one robot is enough to repair all roads: (0,1) -> (0,2) -> (0,3)

      For the second case, one robot is again enough: (0,1) -> (1,2) -> (2,3) -> (2,4) -> (4,5)

      The the third case, there is no way to repair all the roads with one robot and at least two are needed.

       

       


      Added by:Varun Jalan
      Date:2011-10-18
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint - InterviewStreet Contest









      SPOJ Problem Set (classical)

      9753. Tuple Division

      Problem code: TUPLEDIV

      Description

      You are given N tuples with M dimensions. You need to choose some tuples and divide them into M groups. Each tuple can be used for only once and the size of the ith group is Ci. We define the score of the ith group is the sum of value in the ith dimension of the tuples in the ith group. Your target is to firstly maximize the score of 1th group, then maximize the score 2th group and so on. 

      Input

      The first line of the input contains an integer T(T≤50), indicating the number of cases. Each case begins with two integer N(1≤N≤10000) and M(1≤M≤10), the number of tuples and the number of groups. Then there is one line contain M integers. The ith integer Ci (Ci >=0, sigma Ci <= N) represents the size of the ith group. Then N lines with M integers follow. Each of them describes a tuple. The jth integer on the ith line Tij (0 <=Tij <= 10000) denotes the value of the jth dimension of the ith tuple.

      Output

      For each test case, print one line with M score of some optimal division.

      Sample Input

      2

      4 2

      2 1

      3 2

      2 1

      2 2

      1 1

      4 3

      1 1 2

      8 7 1

      8 7 2

      8 7 4

      8 2 3

      Sample Output

      5 2

      8 7 7

      Hint

      In case 2, we can dive the group like:

      Group 1: (8, 7, 2)  score = 8

      Group 2: (8, 7, 1)  score = 7

      Group 3: (8, 7, 4), (8, 2, 3) score = 4 + 3 = 7

       


      Added by:3xian
      Date:2011-10-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:code6









      SPOJ Problem Set (classical)

      9755. Grey Area

      Problem code: SCPC11A

      Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the

      world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator.

      histogram

      Figure 1 is an example of histogram automatically produced by his histogram generator. A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0–9 occur five times, those in the interval 10–19 occur three times, and 20–29 and 30–39 once each.

      Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white,

      respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively.

      In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness.

       

       

      Input

       

      The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format:

      n w

      v1

      v2

      ...

      vn

      n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times.

      w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v<w, the second one if w ≤ v< 2w, and so on. Note that the interval from 0 (inclusive) to w (exclusive) should be regarded as the leftmost even if no values occur in this interval. The last (i.e. rightmost) interval is the one that includes the largest value in the dataset.

      You may assume the following:

      1 ≤ n ≤ 100

      10 ≤ w ≤ 50

      0 ≤ vi ≤ 100 for 1 ≤ i ≤ n

      You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval.

      The end of the input is indicated by a line containing two zeros.

       

      Output

       

      For each dataset, output a line containing the amount of ink consumed in printing the histogram.

      One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is:

      example

      Each output value should be a 6 decimal fraction.

      Example

      Input:
      3 50
      100
      0
      100
      3 50
      100
      100
      50
      10 10
      1
      2
      3
      4
      5
      16
      17
      18
      29
      30
      0 0
      
      Output:
      0.510000
      0.260000
      1.476667
      

      Added by:Ali Arous
      Date:2011-10-18
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Syrian Collegiate Programming Contest 2011









      SPOJ Problem Set (classical)

      9756. Alaska

      Problem code: SCPC11B

       

      The Alaska Highway runs 1422 miles from Dawson Creek, British Columbia to Delta Junction, Alaska. 
      Brenda would like to be the first person to drive her new electric car the length of the highway. Her car can travel up to 200 miles once charged at a special charging station. There is a charging station in Dawson Creek, where she begins her journey, and also several charging stations along the way. Can Brenda drive her car from Dawson City to Delta Juntion and back?

       

      The Alaska Highway runs 1422 miles from Dawson Creek, British Columbia to Delta Junction, Alaska. 

      Brenda would like to be the first person to drive her new electric car the length of the highway. Her car can travel up to 200 miles once charged at a special charging station. There is a charging station in Dawson Creek, where she begins her journey, and also several charging stations along the way. Can Brenda drive her car from Dawson City to Delta Juntion and back?

       

       

      Input

      The input contains several scenario. Each scenario begins with a line containing n, a positive number indicating the number of charging stations. n lines follow, each giving the location of a filling station on the highway, including the one in Dawson City. The location is an integer between 0 and 1422, inclusive, indicating the distance in miles from Dawson Creek. No two filling stations are at the same location. A line containing 0 follows the last scenario.

      Output

       

      For each scenario, output a line containing POSSIBLE if Brenda can make the trip.

      Otherwise, output a line containing the word IMPOSSIBLE.

       

      Example

      Input:
      2
      0
      900
      8
      1400
      1200
      1000
      800
      600
      400
      200
      0
      0
      
      Output:
      IMPOSSIBLE
      POSSIBLE
      

      Added by:Ali Arous
      Date:2011-10-19
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Syrian Collegiate Programming Contest 2011









      SPOJ Problem Set (classical)

      9759. GO

      Problem code: SCPC11F

       

      In the game of Go, two players alternate placing black and white stones on lattice points of an n × n grid, each attempting to surround as much territory (i.e., regions of unfilled lattice points) as possible. At the end of the game, the score for each player is the total area of the territory surrounded by his or her stones. Given the locations of black and white stones on a Go board at the end of a match, your task is to compute the score of each player in order to
      determine the winner.1
      Formally, two grid lattice points with coordinates (r, c) and (r′, c′) are adjacent if |r − r′| + |c − c′| = 1.
       A connected region of unfilled lattice points belongs to one player’s
      territory if all adjacent filled lattice points contain stones belonging to that player (see Figure 1). Finally, a player’s score consists of the number of unfilled lattice points in his or her territory

       

      In the game of Go, two players alternate placing black and white stones on lattice points of an n × n grid, each attempting to surround as much territory (i.e., regions of unfilled lattice points) as possible. At the end of the game, the score for each player is the total area of the territory surrounded by his or her stones. Given the locations of black and white stones on a Go board at the end of a match, your task is to compute the score of each player in order to

      determine the winner.1

      Formally, two grid lattice points with coordinates (r, c) and (r′, c′) are adjacent if |r − r′| + |c − c′| = 1.

       A connected region of unfilled lattice points belongs to one player’s

      territory if all adjacent filled lattice points contain stones belonging to that player (see Figure 1). Finally, a player’s score consists of the number of unfilled lattice points in his or her territory.

      Figure

       

       

      1 Note that the scoring of Go boards described here does not correspond exactly to the real game of Go: we make the simplifying assumptions that all “disputes” have been settled so that any territories surrounded by stones of both colors are considered neutral, and that all groups on the board are considered “alive.”

      Figure 1: Diagram of a 9 × 9 Go board. Unfilled lattice points belonging to black’s territory are marked with B, and unfilled lattice points belonging to white’s territory are marked with W. Neutral unfilled lattice points are unmarked. In the game above, white wins by 21 − 3 = 18.

      Input

       

      The input test file will contain multiple cases, each consisting of three lines. Each test case begins with a line containing three integers, n (where 1 ≤ n ≤ 19), b, and w (where b ≥ 0,w ≥ 0 and 1 ≤ b + w ≤ n2). Here, n denotes the size of the board, b is the number of black pieces placed, and w is the number of white pieces placed. The second line of each test case contains b pairs of integers r1 c1 . . . rb cb (where 1 ≤ ri , ci ≤ n) indicating the positions of the b black stones. The third line of each test case contains w pairs of integers r'1 c'1 . . . r'w c'w (where 1 ≤ r'i , c'i ≤ n) indicating the positions of the w white stones. No two stones will be located at the same lattice point. Input is terminated by a single line containing only the number 0; do not process this line.

       

      Output

      For each test case, print either “White wins by ”, “Black wins by ”, or “Draw”.

      Example

      Input:
      1 1 0
      1 1
      2 0 1
      1 1
      5 12 4
      1 1 1 2 1 3 2 1 2 3 3 1 3 3 4 1 4 3 5 1 5 2 5 3
      1 4 2 4 3 4 3 5
      0
      
      Output:
      Draw
      White wins by 3
      Black wins by 1
      

      Added by:Ali Arous
      Date:2011-10-19
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Syrian Collegiate Programming Contest 2011









      SPOJ Problem Set (classical)

      9760. Indomie

      Problem code: SCPC11G

       

      During recession, Amjad needs to queue for SembakoPlus. Sembako, as we all know, stands for “Sembilan Bahan Pokok” which consists of 9 kinds of item: Rice, Sugar, Cooking-oil, Meat, Egg, Milk, Corn, Kerosene and Iodized Salt. SembakoPlus consists of Sembako and one more item: Indomie! Amjad’s favorite of all time!! (therefore, no wonder why he could stand for this long queue).

      Each person in the queue is allowed to pick only one item. No need to ask, Amjad wants only Indomie. Unfortunately, they are running out of SembakoPlus stock and currently there are three kinds of item left: Rice, Sugar and Indomie. As he could see from afar, he is quite sure that Rice and Sugar will be enough for everybody.

      Given the number of remaining Indomie and the number of people queuing in front of Amjad, your task is to count the probability that he will get his Indomie. Amjad can’t do programming right now as he is very nervous so he can’t think logically. He needs your help!

       

       

      Input

       

      There will be multiple test cases for this problem. Each test case contains two integers N (1 ≤ N ≤ 50) and S (0 ≤ S ≤ 50), where N is the number of people queuing in front of Amjad and S is the remaining number of Indomie.

      Output

       

       

      For each case, print in a single line the probability in percentage that he will get his Indomie with 5 digits precision (he’s being paranoid)

       

      Example

      Input:
      2 1
      3 2
      4 0
      4 1
      10 10
      14 9
      30 14
      
      
      Output:
      50.00000
      76.92308
      0.00000
      33.33333
      99.99831
      98.65515
      95.16071
      
      Explanation for 1st sample test case:
      There are two peoples queuing in front of Amjad, so those two peoples could pick of the
      following combination {1st people, 2nd people}:
      1. Rice, Rice
      2. Rice, Sugar
      3. Rice, Indomie
      4. Sugar, Rice
      5. Sugar, Sugar
      6. Sugar, Indomie
      7. Indomie, Rice
      8. Indomie, Sugar
      Since there is only one Indomie left, there are only 4 out of 8 combinations that ensure Amjad to get his Indomie (1, 2, 4 and 5), hence the probability is 4/8 = 50%.

      Added by:Ali Arous
      Date:2011-10-19
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Syrian Collegiate Programming Contest 2011









      SPOJ Problem Set ()

      9761. Dolls

      Problem code: SCPC11H

      Do you remember the box of Matryoshka dolls last week? Adam just got another box of dolls from Matryona. This time, the dolls have different shapes and sizes: some are skinny, some are fat, and some look as though they were attened. Specifically, doll i can be represented by three numbers wi, li, and hi, denoting its width, length, and height. Doll i can fit inside another doll j if and only if wi < wj , li < lj , and hi < hj . That is, the dolls cannot be rotated when fitting one inside another. Of course, each doll may contain at most one doll right inside it. Your goal is to fit dolls inside each other so that you minimize the number of outermost dolls.

      Input

       

      The input consists of multiple test cases. Each test case begins with a line with a single integer N, 1 ≤ N ≤ 500, denoting the number of Matryoshka dolls. Then follow N lines, each with three space-separated integers wi, li, and hi (1 ≤ wi; li; hi ≤ 10,000) denoting the size of the ith doll. Input is followed by a single line with N = 0, which should not be processed.

       

      The input consists of multiple test cases. Each test case begins with a line with a single integer N, 1 ≤ N ≤ 500, denoting the number of Matryoshka dolls. Then follow N lines, each with three space-separated integers wi, li, and hi (1 ≤ wi; li; hi ≤ 10,000) denoting the size of the ith doll. Input is followed by a single line with N = 0, which should not be processed.

       

       

      Output

       

      For each test case, print out a single line with an integer denoting the minimum number of outermost dolls that can be obtained by optimally nesting the given dolls.

       

      Example

      Input:
      3
      5 4 8
      27 10 10
      100 32 523
      3
      1 2 1
      2 1 1
      1 1 2
      4
      1 1 1
      2 3 2
      3 2 2
      4 4 4
      0
      
      
      Output:
      1
      3
      2
      

      Added by:Ali Arous
      Date:2011-10-19
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Syrian Collegiate Programming Contest 2011









      SPOJ Problem Set (classical)

      9788. Friends of Friends

      Problem code: FACEFRND

      Bob uses a social networking site almost all the time. He was wondering what are Friends of Friends in that social networking site? If “X” is his friend, and “Y” is X’s friend but “Y” is not his friend, then “Y” is called his friend of friend. You have to find how many friends of friends Bob has. (Each user in that social networking site has a unique 4-digit ID number)

      Input

      First line contains a integer “N” (1<=N<=100) the number of friends in Bob's Profile. Then follow N lines.

      First Integer in each line is the ID number of Bob's friend, then an integer “M” (1<=M<=100) is the number of people in his friend list. Then follow M integers in that line, denoting the ID number of friends in his friend list (excluding Bob). 

      Output

      Output a single integer denoting Bob's number of friends of friends.

      Example

      Input:
      

      3

      2334 5 1256 4323 7687 3244 5678

      1256 2 2334 7687

      4323 5 2334 5678 6547 9766 9543
      Output:
      
      6

      Added by:Ankit Kumar Vats
      Date:2011-10-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      9805. Be Awesome As Barney Stinson

      Problem code: BEHAPPY

      Barney Stinson ;) is way too flirty. He has many girlfriends and he wants to keep all of them happy. He has M girlfriends. He bought N gifts for them. Now he knows that some girlfriends need more gifts and some need less. So he decided that he will give atleast Ai gifts and at most Bi gifts to his ith girlfriend. He has to give away all the N gifts. Tell us in how many different ways he can do this.

      INPUT:

      For each test case, first line contains two integers M and N, then follows M lines each having two integers Ai and Bi (1<=i<=M). Input ends with M and N both equal to 0 and that case should not be processed.

      OUTPUT:

      For each test case, output the number of different ways in which he can distribute those gifts in a single line.

      Example:

      Input:

      3 5

      0 1

      1 3

      1 4

      0 0

       

      Output:

      6

       

      Explanation: He can distribute 5 gifts in his 3 girlfriends in 6 different ways as follows (0 1 4), (0 2 3), (0 3 2), (1 1 3), (1 2 2), (1 3 1).

       

      Constraints: 1<=M<=20, 1<=N<=100, 0<=Ai,Bi,<=100

       


      Added by:Ankit Kumar Vats
      Date:2011-10-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Inspired









      SPOJ Problem Set (classical)

      9817. Shortcut

      Problem code: WPC4C

      Shortcut

      Into the new level, a witch provides an option to Mario, so that he can avoid the intense battle ahead in this level. He needs to perform a task on a sheet of paper provided by the witch. He needs to cut a rectangular area out of them so that the ratio of height to width (i.e. the height/width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2^x for some integer x). If those rules don't indicate the size of the cut area clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, he must choose the answer with the maximal height.

      Input
      The first line contains number of test cases T (T <= 50)
      The next lines contain a pair of integers x and y (1 <= x , y <= 10^9) which are the height and width of the sheet.

      Output
      T lines of two integers which are the height and width of the cut area.

      Sample I/O

      Input
      2
      2 1
      2 2
      
      Output
      1 1
      2 2
      

       

       


      Added by:Walrus
      Date:2011-10-24
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Local Contest: WPC 4









      SPOJ Problem Set ()

      9820. Through the troops

      Problem code: WPC4F

      Having crossed the first hurdle, Mario encounters a long and narrow alleyway, with turtles. Mario can cross it by jumping from one turtle to another. Whenever Mario makes his jump on any given turtle, he can leave it in any of the three possible states, as per his choice. These states are:

      • Active (A)
      • Dormant (D)
      • Bruised (B)

       

      There are n turtles in the street, indexed 0..(n-1)
      Each jump costs some amount of energy, which depends on the index of turtle as well as the state it is left in. However, Mario has to take care that no neighboring turtles are left in the same state, or otherwise they all will reunite and cause a fatal attack on Mario, as he is about to leave the alley.
      The neighbors of turtle i are turtles i-1 and i+1. The first and last turtles are not neighbors.
      You need to find out the minimum amount of energy required to cross the alley.

      Input
      first line contains no. of test cases T (T <= 5)
      T input sets are given in the following manner
      the first line contains n, no. of turtles (n <= 20)
      the next n lines have space separated 3 numbers (a1, a2, a3), the values of energy needed for ith turtle to change into states A D B (0 <= ai <= 1000)
      similarly, the inputs are given for other cases

      Output
      T lines, the minimal energy needed for each set of input

      Sample I/O

      Input
      2
      3
      0 1 2
      1 4 8
      9 2 5
      4
      10 10 10
      2 4 9
      12 7 10
      6 6 6
      
      Output
      4
      25
      

       

       

       


      Added by:Walrus
      Date:2011-10-24
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Local Contest: WPC 4









      SPOJ Problem Set (classical)

      9832. Matrix inverse

      Problem code: MIFF

      Let p a prime number. A set Fp={0,1,...,p-1} equipped with the mod p addition and multiplication is a finite field. In this problem you have to compute the multplicative inverse of some Fp valued (quadratic) matrices.

      The input consists of blocks. The structure of a block is:

      n p

      A11...A1n

      ...

      An1...Ann

      where p is a prime number, 1<n,p<101, and Aij are in Fp. The last block followed by 0 0.

       

      The ouput for each block is either the multiplicative inverse of a given matrix if it exists or the word "singular"

      Example

      Input:

      4 2
      1 1 1 1
      1 1 0 1
      0 0 0 1
      0 1 0 1

      3 7
      3 5 0
      0 5 1
      6 6 6

      2 2
      1 1
      1 0

      3 5
      4 0 0
      2 4 1
      0 2 3

      3 7
      0 1 4
      6 1 2
      2 1 1

      0 0

      Output:

      0 1 0 1
      0 0 1 1
      1 1 0 0
      0 0 1 0

      6 3 3
      5 1 1
      3 3 2

      0 1
      1 1

      singular

      singular

      Added by:Noszály Csaba
      Date:2011-10-26
      Time limit:5s
      Source limit:22222B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:folklore









      SPOJ Problem Set (classical)

      9842. Yet Another Fancy Game

      Problem code: GAME3


      Two girls - Ivica and Marica - play an interesting game.

      First, they randomly choose a natural number N. They also define M = 1.

      Ivica plays first, then Marica, then Ivica, then Marica and so on.

      In each move, a girl has to increase M by 1 or multiply M by 2 (that is, M = M+1 or M = 2*M). The resulting number must not be greater than N.

      The loser of the game is the girl who gets M = N. The other girl is, of course, the winner.

      Write a program to determine the winner, assuming that both girls play optimally.

      Input

      In the first line there is an integer T (1 ≤ T ≤ 5), the number of games.

      T lines follow. In ith line there is an integer N (2 ≤ N ≤ 1015), a chosen number for ith game.

      Output

      For each of the T games print the name of the winner.

      Example

      Input:
      4
      2
      3
      4
      5
      Output:

      Marica
      Ivica
      Marica
      Marica

      Added by:Adrian Satja Kurdija
      Date:2011-10-29
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:originated from a mathematical problem









      SPOJ Problem Set (classical)

      9856. The Glazier

      Problem code: GLASS


      Jozo the glazier has made N square pieces of glass. The dimensions (sides) of these squares are equal to 1, 2, 3, ..., N - therefore, the areas of these squares equal to 12, 22, 32, ..., N2.

      Four customers have arrived. Each of them buys exactly 3 pieces of of glass (Jozo will therefore sell exactly 12 pieces of glass). Each customer has stated that the sum of the dimensions of the squares he gets must be equal to N (for example he could get the pieces with dimensions 1, 2 and N-3).

      Furthermore, since all customers pay the same price, Jozo wants to be fair and ensure that the sum of areas of the 3 squares must be equal for each customer (but this sum is not defined in advance). Help Jozo to choose which pieces to sell.

      Input

      A natural number N (12 ≤ N ≤ 1500).

      Output

      Print -1 if there is no solution. Otherwise, print four lines: in each of these four lines there must be three numbers from the set {1, 2, ..., N} and their sum must be equal to N. Also, the sum of squares of these three numbers must be constant for each row. All 12 numbers must be distinct.

      Example

      Input:
      84
      
      Output:
      18 29 37
      17 33 34 18 29 37 19 27 38 22 23 39
      19 27 38
      22 23 3

      Added by:Adrian Satja Kurdija
      Date:2011-10-30
      Time limit:1s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:that would be me









      SPOJ Problem Set (classical)

      9857. Eight Directions Crossword

      Problem code: EIGHT


      What is an Eight Directions Crossword? It's a filled crossword in which all the words are hidden in eight directions (up, down, left and right and also up-left, down-right etc.) You have to find these hidden words in each crossword.

      Ðuro has made an N x N eight-directions-crossword. His crossword is a bit strange: you are given only one word and you have to find it in a crossword. To make things more difficult, you can skip some letters in the crossword while looking for the given word. More precisely, the given word is the subsequence of not necesarily consecutive letters in a row, column or a diagonal of the crossword in one of the eight directions.

      Now you discover that, under these conditions, you can read the given word in the crossword in multiple ways. How many?

      Input

      In the first line of the input there is an integer N (2 ≤ N ≤ 1000), the crossword dimension, followed by space and the given word you are to find. This word has 2-10 letters.

      N lines follow, representing the crossword. All letters in the crossword and in the given word are small letters of the English alphabet.

      Output

      Print the required number of ways. (This number will fit into int64 in Pascal or long long in C/C++.)

      Example

      input
      2 aa
      aa
      aa

       

      output

      12
      input
      3 aa
      aaa
      aaa
      aaa

       

      output

      56
      input
      8 silba
      siolobba
      oooaoooo
      oooboooo
      aooooooo
      oboloooo
      oolooooo
      oooioooo
      ooossooo

       

      output

      4

      Added by:Adrian Satja Kurdija
      Date:2011-10-30
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:that would be me









      SPOJ Problem Set (classical)

      9858. ©tef and Barica

      Problem code: WALK1

      Štef lives in a house located in (0, 0). His girlfriend Barica lives in a house located in (X, Y).

      Štef likes walking, so he decided to walk for exactly N hours (starting from his house) and finish his route at Barica's house.

      Each hour, Štef moves from his current position to one of the four adjacent positions (north, south, east or west).

      Help Štef and calculate how manny possible routes there are. (If there isn't any, print 0.)

      Input

      In the first line there is an integer N (1 ≤ N ≤ 106).

      In the second line there are integers X, Y separated by a space (-N ≤ X, Y ≤ N).

      Output

      Calculate the number of possible Štef's routes from (0, 0) to (X, Y) that last for exactly N hours. Print the result modulo 500 000 003.

      Example

      Input:
      
      3
      2 1
      Output:
      3
      Input:
      
      2
      0 0
      Output:
      4

      Added by:Adrian Satja Kurdija
      Date:2011-10-30
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:that would be me









      SPOJ Problem Set (classical)

      9860. The Glazier 2

      Problem code: GLASS2

      Jozo the glazier has once again made N square pieces of glass. The dimensions (sides) of these squares are equal to 1, 2, 3, ..., N - therefore, the areas of these squares equal to 12, 22, 32, ..., N2.

      Four customers have arrived once again. This time Jozo will sell all N squares of glass. Again, each of the customers must get the same total area of glass (which equals the total area of all N squares divided by four).

      Help Jozo and divide his N pieces of glass among the four customers. Assume that the solution (not necesarily unique) exists in all of the test data.

      Input

      An integer N (10 ≤ N ≤ 60).

      Output

      In the first line, print four numbers: the number of pieces of glass assigned to the first, to the second, to the third and to the fourth customer (respectively).

      In ith of the next four lines, print the dimensions of the squares of glass assigned to the ith customer. (Each square must be assigned to exactly one customer.)

      Example

      Input:
      15
      
      Output:
      
      4 4 4 3
      3 6 11 12
      4 5 10 13
      1 7 8 14
      2 9 15

      Added by:Adrian Satja Kurdija
      Date:2011-10-30
      Time limit:1s-7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:originated from a mathematical problem









      SPOJ Problem Set (classical)

      9861. Hotels Along the Croatian Coast

      Problem code: HOTELS

      There are N hotels along the beautiful Adriatic coast. Each hotel has its value in Euros.

      Sroljo has won M Euros on the lottery. Now he wants to buy a sequence of consecutive hotels, such that the sum of the values of these consecutive hotels is as great as possible - but not greater than M.

      You are to calculate this greatest possible total value.

      Input

      In the first line of the input there are integers N and M (1 ≤ N ≤ 300 000, 1 ≤ M < 231).

      In the next line there are N natural numbers less than 106, representing the hotel values in the order they lie along the coast.

      Output

      Print the required number (it will be greater than 0 in all of the test data).

      Example

      input
      5 12
      2 1 3 4 5
      output
      12
      input
      4 9
      7 3 5 6
      output
      8

      Added by:Adrian Satja Kurdija
      Date:2011-10-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:that would be me









      SPOJ Problem Set (classical)

      9862. Help the Airline Company

      Problem code: REMOVE


      In a far away country there are N cities, and every two of them are connected by a two-way direct airplane line. Gripped by the crisis, the airline company has decided to remove as many lines as possible.

      The lines will be eliminated one by one. This elimination must not significantly affect the city connections, so when removing a line, it must belong to a cycle of length four. In other words, if the cities A, B, C, D are such that currently there are lines AB, BC, CD and DA, then we can remove any of these lines.

      It is possible to prove that there must remain at least N lines at the end of the elimination process (i.e., that we are unable to remove more lines under the described conditions). You are not required to prove it, but to write a program that helps the airline company to remove a line by line until there are exactly N left.

      Input

      4 ≤ N ≤ 2000.

      Output

      Print one line of data for each airplane line you are removing.

      In each of these lines, print the numbers A, B, C, D which represent the cities forming a cycle. These numbers indicate that you are removing the line AB.

      Example

      input
      4
      output
      2 3 1 4
      3 4 2 1
      input
      5
      output
      3 4 5 2
      2 3 1 5
      3 5 2 1
      2 4 1 5
      4 5 2 1

      Added by:Adrian Satja Kurdija
      Date:2011-10-30
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:originated from a mathematical problem









      SPOJ Problem Set (classical)

      9887. Binomial coefficients

      Problem code: NWERC11A

      Binomial coefficients

      Gunnar is quite an old and forgetful researcher. Right now he is writing a paper on security in social networks and it actually involves some combinatorics. He wrote a program for calculating binomial coefficients to help him check some of his calculations.

      A binomial coefficient is a number

      (n )        n!      =  ----------   k     k!(n - k)!

      where n and k are non-negative integers.

      Gunnar used his program to calculate (n)  k and got a number m as a result. Unfortunately, since he is forgetful, he forgot the numbers n and k he used as input. These two numbers were a result of a long calculation and they are written on one of many papers lying on his desk. Instead of trying to search for the papers, he tried to reconstruct the numbers n,k from the output he got. Can you help him and find all possible candidates?

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • one line with an integer m (2 ≤ m ≤ 1015): the output of Gunnar’s program.

      Output

      Per test case:

      • one line with an integer: the number of ways of expressing m as a binomial coefficient.
      • one line with all pairs (n,k) that satisfy ( )  n  k = m. Order them in increasing order of n and, in case of a tie, order them in increasing order of k. Format them as in the sample output.

      Sample in- and output

      Input

      Output

      2
      2
      15
      1
      (2,1)
      4
      (6,2) (6,4) (15,1) (15,14)

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set (main)

      9888. Bird tree

      Problem code: NWERC11B

      Bird tree

      The Bird tree1 is an infinite binary tree, whose first 5 levels look as follows:

                                         1                                    ∕1                     1∕2                                  2∕1          2∕3                1∕3                3∕1                3∕2    3        3         1        2        5         4        4        5    ∕5       ∕4       ∕4       ∕5        ∕2       ∕1       ∕3        ∕3 5   4    4    5   2    1    3   3    8    7   5    7   7    5    7   8 ∕8   ∕7   ∕5  ∕7   ∕7   ∕5  ∕7   ∕8  ∕3   ∕3   ∕1  ∕2   ∕5   ∕4  ∕4   ∕5

      It can be defined as follows:

      bird =             1∕1          1∕ (bird + 1)  (1∕bird) + 1

      This is a co-recursive definition in which both occurrences of bird refer to the full (infinite) tree. The expression bird + 1 means that 1 is added to every fraction in the tree, and 1∕bird means that every fraction in the tree is inverted (so ab becomes ba).

      Surprisingly, the tree contains every positive rational number exactly once, so every reduced fraction is at a unique place in the tree. Hence, we can also describe a rational number by giving directions (L for left subtree, R for right subtree) in the Bird tree. For example, 25 is represented by LRR. Given a reduced fraction, return a string consisting of L’s and R’s: the directions to locate this fraction from the top of the tree.

       

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • one line with two integers a and b (1 ≤ a,b ≤ 109), separated by a ’/’. These represent the numerator and denominator of a reduced fraction. The integers a and b are not both equal to 1, and they satisfy gcd(a,b) = 1.

      For every test case the length of the string with directions will be at most 10 000.

       

      Output

      Per test case:

      • one line with the string representation of the location of this fraction in the Bird tree.

       

      Sample in- and output

      Input

      Output

      3
      1/2
      2/5
      7/3
      L
      LRR
      RLLR

      1Hinze, R. (2009). The Bird tree. J. Funct. Program., 19:491–508.

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set (main)

      9889. Movie collection

      Problem code: NWERC11C

      Movie collection

      Mr. K. I. has a very big movie collection. He has organized his collection in a big stack. Whenever he wants to watch one of the movies, he locates the movie in this stack and removes it carefully, ensuring that the stack doesn’t fall over. After he finishes watching the movie, he places it at the top of the stack.

      Since the stack of movies is so big, he needs to keep track of the position of each movie. It is sufficient to know for each movie how many movies are placed above it, since, with this information, its position in the stack can be calculated. Each movie is identified by a number printed on the movie box.

      Your task is to implement a program which will keep track of the position of each movie. In particular, each time Mr. K. I. removes a movie box from the stack, your program should print the number of movies that were placed above it before it was removed.

       

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • one line with two integers m and r (1 ≤ m,r ≤ 100 000): the number of movies in the stack and the number of locate requests.
      • one line with r integers a1,,ar (1 ≤ aim) representing the identification numbers of movies that Mr. K. I. wants to watch.

      For simplicity, assume that the initial stack contains the movies with identification numbers 1, 2,,m in increasing order, where the movie box with label 1 is the top-most box.

       

      Output

      Per test case:

      • one line with r integers, where the i-th integer gives the number of movie boxes above the box with label ai, immediately before this box is removed from the stack.

      Note that after each locate request ai, the movie box with label ai is placed at the top of the stack.

       

      Sample in- and output

      Input

      Output

      2
      3 3
      3 1 1
      5 3
      4 4 5
      2 1 0
      3 0 4

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:16s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set (main)

      9890. Piece it together

      Problem code: NWERC11D

      Piece it together

      Tom has developed a special kind of puzzle: it involves a whole bunch of identical puzzle pieces. The pieces have the shape of three adjoint squares in an L-shape. The corner square is black, the two adjacent squares are white.

       


      PIC

      Figure 1: A puzzle piece

       


      The puzzler is given a pattern of black and white squares in a rectangular grid. The challenge is to create that pattern using these pieces. The pieces can be rotated, but must not overlap.

      Tom has already designed a few nice patterns, but he needs to find out if they can be constructed with the pieces at all. Rather than trying to test this for each pattern by hand, he wants to write a computer program to determine this for him. Can you help him?

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • one line with two integers n and m (1 ≤ n,m ≤ 500): the height and width of the grid containing the pattern, respectively.
      • n lines, each containing m characters, denoting the grid. Each character is ‘B’, ‘W’, or ‘.’, indicating a black, white or empty square respectively.

      The grid contains at least one black or white square.

       

      Output

      Per test case:

      • one line with either “YES” or “NO”, indicating whether or not it is possible to construct the pattern with the puzzle pieces. You may assume that there is an infinite supply of pieces.

       

      Sample in- and output

      Input

      Output

      2
      3 4
      BWW.
      WWBW
      ..WB
      3 3
      W..
      BW.
      WBW
      YES
      NO 

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set (main)

      9891. Please, go first

      Problem code: NWERC11E

      Please, go first

      You are currently on a skiing trip with a group of friends. In general, it is going well: you enjoy the skiing during the day and, of course, the après-skiing during the night. However, there is one nuisance: the skiing lift. As always, it is too small, and can only serve one person every 5 seconds. To make matters worse, you and your friends generally don’t arrive simultaneously at the lift, which means that you spend time waiting at the bottom of the mountain for the lift and at the top again for your friends.

      The waiting at the top is especially inefficient. In fact, you realize that if your friends haven’t arrived yet, you might as well let other people pass you in the queue. For you, it makes no difference, since otherwise you’d be waiting at the top. On the other hand, your actions might save them time if their friends have already arrived and are currently waiting for them at the top.

      You are wondering how much time would be saved if everybody adopts this nice attitude. You have carefully observed the queue for a while and noticed which persons form groups of friends. Suppose someone lets another pass if doing this doesn’t change his own total waiting time, but saves time for the other person. Do this over and over again until it can’t be done anymore. How much time will this save, in total?

       

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • one line with an integer n (1 ≤ n ≤ 25 000): the number of people in the line for the lift.
      • one line with n alphanumeric characters (uppercase and lowercase letters and numbers): the queue. The first person in this line corresponds to the person at the head of the queue. Equal characters correspond to persons from the same group of friends.

       

      Output

      Per test case:

      • one line with an integer: the time saved, in seconds.

       

      Sample in- and output

      Input

      Output

      2
      6
      AABABB
      10
      Ab9AAb2bC2
      15
      45

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set (main)

      9892. Pool construction

      Problem code: NWERC11F

      Pool construction

      You are working for the International Company for Pool Construction, a construction company which specializes in building swimming pools. A new client wants to build several new pool areas.

      A pool area is a rectangular grid of w × h square patches, consisting of zero or more (possibly disconnected) pools. A pool consists of one or multiple connected hole patches, which will later be filled with water. In the beginning, you start with a piece of land where each patch is either a hole in the ground (’.’) or flat grass (’#’). In order to transform this land into a pool area, you must adhere to the following:

      • You can leave a patch as it is. This costs nothing.
      • If the patch is grass in the beginning, you can dig a hole there. This costs d EUR.
      • If the patch is a hole in the beginning, you can fill the hole and put grass on top. This costs f EUR.
      • You must place special boundary elements along each edge running between a final grass patch and a final hole patch, to ensure that water does not leak from the pool. This costs b EUR per boundary element.
      • The outermost rows and columns of the pool area must always be grass.

      You are given the task of calculating the cost of the cheapest possible pool area given the layout of the existing piece of land.

       

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • one line with two integers w and h (2 ≤ w,h ≤ 50): the width and height of the building site.
      • one line with three integers d, f and b (1 ≤ d,f,b ≤ 10 000): the costs for digging a new hole, filling an existing hole, and building a boundary element between a pool and grass patch.
      • h lines of w characters each, denoting the layout of the original building site.

       

      Output

      Per test case:

      • one line with an integer: the cost of building the cheapest possible pool area from the original piece of land.

       

      Sample in- and output

      Input

      Output

      3
      3 3
      5 5 1
      #.#
      #.#
      ###
      5 4
      1 8 1
      #..##
      ##.##
      #.#.#
      #####
      2 2
      27 11 11
      #.
      .#
      9
      27
      22 

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set (main)

      9893. Smoking gun

      Problem code: NWERC11G

      Smoking gun

      Andy: ”Billy the Kid fired first!”

      Larry: ”No, I’m sure I heard the first shot coming from John!”

      The arguments went back and forth during the trial after the big shoot-down, somewhere in the old wild west. Miraculously, everybody had survived (although there were serious injuries), but nobody could agree about the exact sequence of shots that had been fired. It was known that everybody had fired at most one shot, but everything had happened very fast. Determining the precise order of the shots was important for assigning guilt and penalties.

      But then the sheriff, Willy the Wise, interrupted: ”Look, I’ve got a satellite image from the time of the shooting, showing exactly where everybody was located. As it turns out, Larry was located much closer to John than to Billy the Kid, while Andy was located just slightly closer to John than to Billy the Kid. Thus, because sound travels with a finite speed of 340 meters per second, Larry may have heard John’s shot first, even if Billy the Kid fired first. But, although Andy was closer to John than to Billy the Kid, he heard Billy the Kid’s shot first – so we know for a fact that Billy the Kid was the one who fired first!

      Your task is to write a program to deduce the exact sequence of shots fired in situations like the above.

       

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • one line with two integers n (2 ≤ n ≤ 100) and m (1 ≤ m ≤ 1 000): the number of people involved and the number of observations.
      • n lines with a string S, consisting of up to 20 lower and upper case letters, and two integers x and y (0 ≤ x,y ≤ 1 000 000): the unique identifier for a person and his/her position in Cartesian coordinates, in metres from the origin.
      • m lines of the form “S1 heard S2 firing before S3”, where S1, S2 and S3 are identifiers among the people involved, and S2S3.

      If a person was never mentioned as S2 or S3, then it can be assumed that this person never fired, and only acted as a witness. No two persons are located in the same position.

      The test cases are constructed so that an error of less than 10-7 in one distance calculation will not affect the output.

       

      Output

      Per test case:

      • one line with the ordering of the shooters that is compatible with all of the observations, formatted as the identifiers separated by single spaces.

      If multiple distinct orderings are possible, output “UNKNOWN” instead. If no ordering is compatible with the observations, output “IMPOSSIBLE” instead.

       

      Sample in- and output

      Input

      Output

      3
      4 2
      BillyTheKid 0 0
      Andy 10 0
      John 19 0
      Larry 20 0
      Andy heard BillyTheKid firing before John
      Larry heard John firing before BillyTheKid
      2 2
      Andy 0 0
      Beate 0 1
      Andy heard Beate firing before Andy
      Beate heard Andy firing before Beate
      3 1
      Andy 0 0
      Beate 0 1
      Charles 1 3
      Beate heard Andy firing before Charles
      BillyTheKid John
      IMPOSSIBLE
      UNKNOWN

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set (classical)

      9894. Tichu

      Problem code: NWERC11H

      Tichu

      Tichu is a card game played by four players. The players sit around a square table, and each player forms a team with the person sitting opposite him or her. The game is played with a standard deck of cards and four additional special cards. The basic rule of the game is as follows: the player who won the last trick can start a new trick with any legal combination of cards. Then, in turn, each next player can either pass or play the same combination of cards, but with a higher value. This continues until everyone passes, and at that point the player who played the last combination wins the trick and can start a new trick. The main goal is to get rid of all of your cards as soon as possible.

      These basic rules make it a good tactic to combine the cards in such a way that they can be played in as few combinations as possible. For simplicity we consider here a slightly modified version of the game. We ignore the special cards, so that leaves a standard deck of 52 cards, ranging over the values 2 to Ace and over the suits hearts, diamonds, clubs, and spades. The suits are indicated by the lowercase letters h, d, c, and s, while the values are indicated in increasing order by 29, T, J, Q, K, A.

      The following list is a complete set of legal combinations:1

      • any single card;
      • a pair of cards of the same value;
      • three cards of the same value;
      • four cards of the same value;
      • a full house, that is, three cards of the same value and two cards of another, same value, for example 444KK;
      • a straight of length at least five, that is, at least five cards of consecutive increasing values, for example 89TJQK.

      In this problem, your task is to determine the minimum number of combinations that your hand of 13 cards can be partitioned into.

       

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • one line that describes your hand of 13 cards. A card is described by two characters: the value followed by the suit. All cards in your hand are different.

       

      Output

      Per test case:

      • one line containing an integer n: the minimum number of combinations that your hand can be partitioned into.
      • n lines that describe a minimal set of combinations of cards from your hand. Each line should contain the cards in one legal combination, in the same format as in the input. All cards from your hand must occur exactly once in one of the combinations. No specific ordering of the combinations or the cards within a combination is required.

       

      Sample in- and output

      Input

      Output

      2
      2h 3c 4d 5d 6s Th Qc Qs Ad Tc Ts 9c 9d
      2h 3h 4h 5h 6d 7s 8h 8d 8c 8s 9c Td Js
      4
      2h 3c 4d 5d 6s
      Th Ts Tc Qc Qs
      9d 9c
      Ad
      2
      2h 3h 4h 5h 6d 7s 8d 9c Td Js
      8h 8s 8c 

      1Those who know the game of Tichu might have noticed that we removed consecutive pairs of cards as a valid combination.

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set (classical)

      9895. Tracking RFIDs

      Problem code: NWERC11I

      Tracking RFIDs

      Jeroen operates a warehouse storage facility for the North Western Electrical Resource Company (NWERC). When a customer places an order with NWERC, this order is conveyed to the warehouse. Jeroen’s task is to then find the products ordered, pack them into a box, and ship them to the customer.

      NWERC has an unusual warehouse policy: the products are not arranged in any particular order, and are strewn all over the place. However, it is possible for Jeroen to do his job because each product is tracked using RFID technology1. Specifically, each product is assigned a wireless RFID chip as soon as it enters the warehouse, and sensors located on the warehouse ceiling are used to automatically track the products.

      By default, each sensor has a range of r units – that is, it can read any RFID chip that is located at most r units from it in a straight line. However, if the line segment between a sensor and a product intersects with or touches x walls, the range of the sensor is reduced by x units in that direction. Furthermore, the sensors may fail to read an RFID chip due to interference from other sensors, so the distance between any pair of sensors in the warehouse is guaranteed to be at least r units. You may further assume that no sensor or product is placed on a wall.

      Jeroen now wants to determine, for each product, which sensors can read its RFID chip. Can you help him?

       


      PIC


      Figure 1: Illustration of sensors, walls and products as in the Sample Input.

       


      Input

      On the first line one positive integer: the number of test cases, at most 100. After that per test case:

      • one line with four integers s (1 ≤ s ≤ 250 000), r (1 ≤ r ≤ 25), w (0 ≤ w ≤ 10) and p (1 ≤ p ≤ 10 000) where s represents the number of sensors, r the range of each sensor, w the number of walls and p the number of products.
      • s lines containing two integers xi and yi (-10 000 ≤ xi,yi ≤ 10 000). Each such line represents a sensor at location (xi, yi). The distance between any pair of sensors is guaranteed to be at least r units.
      • w lines containing four integers bxi, byi, exi and eyi (-10 000 ≤ bxi,byi,exi,eyi ≤ 10 000). Each such line represents a wall, which should be considered as straight line segment from (bxi, byi) to (exi, eyi). The length of this line segment will be positive.
      • p lines, each containing two integers pxi and pyi (-10 000 ≤ pxi,pyi ≤ 10 000). Each such line represents a product at location (pxi, pyi).

       

      Output

      Per test case:

      • p lines, each representing a product in the order they appear in the input. Each line should contain an integer t, the number of sensors that can track the product; this integer should then be followed by a list of t ordered pairs representing the corresponding sensor locations. If there are multiple sensors, they should be sorted in increasing order by x-coordinate. If multiple sensors have the same x-coordinate, they should be sorted in increasing order by y-coordinate.

       

      Sample in- and output

      Input

      Output

      1
      4 3 4 7
      0 0
      -1 3
      2 3
      11 5
      -4 -1 5 -1
      3 5 6 1
      11 4 11 3
      12 5 12 8
      1 1
      0 -2
      4 4
      11 2
      13 5
      13 7
      14 5
      3 (-1,3) (0,0) (2,3)
      1 (0,0)
      0
      0
      1 (11,5)
      0
      0

      1Objects, that have a radio-frequency identification (RFID) tag attached, can be tracked using radio waves.

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:50s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set (classical)

      9896. Train delays

      Problem code: NWERC11J

      Train delays

      Last year, some of the judges tried to travel to NWERC’10 by train. This turned into a big disaster: on the way there, a fire in a control room caused huge delays, while on the return trip, trains in Bremen were delayed due to a terrorist threat in Hamburg. Of course, these huge delays caused other delays in the train schedule, so the big question was which trains to take: would it be better to take this slow regional train now, or wait for that intercity train, which has a big chance of being delayed?

      This year, the judges have planned ahead and carefully analyzed the train schedule. They even kept track of how often trains were delayed and by how much. Now that they have all this information, they want to travel as quickly possible, minimizing the expected duration of the journey. Can you help them?

      For each train connection, the judges know exactly what its scheduled departure time and duration are, as well as the probability that its arrival at the destination will be delayed. You may assume that the probabilities of delays are independent and that the judges can adapt their itinerary as they go, depending on any delays which they might already have incurred. Trains always depart on time, but may arrive late and the judges do not know whether a train’s arrival will be delayed until they have boarded it. It takes judges no time to switch trains, so they can take a connecting train that departs at the same time as they arrive at a place.

      The judges can choose the time of their initial departure as they wish and they want to minimize the expected duration1 of their total trip.

       

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      • one line with the judges’ place of origin and destination, these are different.
      • one line with an integer n (1 ≤ n ≤ 1 000): the number of train connections.
      • n lines, each describing a train connection:
        • the origin and destination of this connection, these are different.
        • an integer m (0 ≤ m ≤ 59), the departure time in minutes after each full hour.
        • an integer t (1 ≤ t ≤ 300), the standard journey time (assuming no delays).
        • an integer p (0 ≤ p ≤ 100), the probability of delays as a percentage.
        • an integer d (1 ≤ d ≤ 120), the maximum delay in minutes.

      All place names are given as strings of upper and lower case alphabetical characters, of length at most 20. If a train is delayed, then the length of the delay will be a whole number of minutes, and will be uniformly distributed in the range [1,d].

       

      Output

      Per test case:

      • one line with a floating point number: the minimum expected duration of the total trip in minutes.

      This number should be accurate up to 10-6 relative or absolute precision. Output IMPOSSIBLE instead if the destination is not reachable.

       

      Sample in- and output

      Input

      Output

      3
      Hamburg Bremen
      3
      Hamburg Bremen 15 68 10 5
      Hamburg Bremen 46 55 50 60
      Bremen Frankfurt 14 226 10 120
      Amsterdam Rotterdam
      1
      Amsterdam Utrecht 10 22 5 10
      BremenVegesack Utrecht
      9
      BremenVegesack BremenHbf 15 10 0 1
      BremenVegesack BremenHbf 45 10 0 1
      BremenVegesack Leer 23 140 10 15
      BremenHbf Osnabruck 44 51 60 70
      Osnabruck Amersfoort 55 147 38 40
      Amersfoort Utrecht 24 15 30 15
      Amersfoort Utrecht 54 15 10 35
      Leer Groningen 45 140 5 10
      Groningen Amersfoort 46 96 10 20
      68.3
      IMPOSSIBLE
      305.0532857 

      Note in the first example that it is better to take the slower train from Hamburg to Bremen, since the fast train would give an expected travel time of 70.25 minutes.


      1Given a travel plan of which trains to take (depending on previous connections and delays), the expected trip duration E is defined to be the sum of the trip duration Ti for each itinerary i possibly taken multiplied by the chance pi of that itinerary occurring: E = ∑ ipi Ti.

      Copyright notice

      This problem text is copyright by the NWERC 2011 jury. It is licensed under the Creative Commons Attribution-Share Alike license version 3.0; The complete license text can be found at: http://creativecommons.org/licenses/by-sa/3.0/legalcode


      Added by:Jeroen Bransen
      Date:2011-11-02
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:NWERC 2011 Jury









      SPOJ Problem Set ()

      9916. Help Dr Whooves

      Problem code: PONY1

       

      On the continent of Equestria, Dr. Whooves used to have it all.  He owned a very successful transportation business which was connected to all the villages and towns of Equestria.  However, when Discord took over Equestria, a lot of the ponies got confused.  Even now, some of his workers are working at the wrong routes, and Dr. Whooves is pretty sure that his business is now fragmented, and that he isn't connected to all the villages of Equestria anymore.
      Twilight Sparkle and her friends are here to help.  Dr. Whooves knows that there is some minimum number of routes he'll need to add to make sure his business is reconnected.  He asked Twilight Sparkle and her friends to find out how many different ways he can choose to add this minimum number of routes so that his business is connected to all the cities of Equestria.  There might be a lot of ways, so the ponies have agreed upon giving the answer modulo 999,999,93

      On the continent of Equestria, Dr. Whooves used to have it all.  He owned a very successful transportation business which was connected to all the villages and towns of Equestria.  However, when Discord took over Equestria, a lot of the ponies got confused.  Even now, some of his workers are working at the wrong routes, and Dr. Whooves is pretty sure that his business is now fragmented, and that he isn't connected to all the villages of Equestria anymore.

      Twilight Sparkle and her friends are here to help.  Dr. Whooves knows that there is some minimum number of routes he'll need to add to make sure his business is reconnected.  He asked Twilight Sparkle and her friends to find out how many different ways he can choose to add this minimum number of routes so that his business is connected to all the cities of Equestria.  There might be a lot of ways, so the ponies have agreed upon giving the answer modulo 999,999,937.


      Input

      First is an integer T, the number of test cases, followed by T sets of data for each test case.

      Each test case is in the following format:

      It indicates that there are C cities, numbered 1 through C, and R routes, on a single line.  After that follow R lines, each containing two city numbers Ai and Bi, indicating a bidirectional route between cities Ai and Bi.


      Test cases are not separated by blank lines, and the input ends with the last line of the final test case.

      Constraints: 1 <= C <= 1000000, 0 <= R < min{C, 100000}

      Output

      T lines, each containing the number of different ways Dr. Whooves can choose to add the minimum number of routes required to reconnect his business, modulo 999999937.

      Example

      Input:
      4
      4 0 3 1 1 2 5 4 1 2 2 3 3 4 2 5 7 6 2 3 3 4 2 4 5 6 6 7 7 5 Output: 16 2 1 63

      Added by:Alex Anderson
      Date:2011-11-05
      Time limit:1.5s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:My own problem









      SPOJ Problem Set (classical)

      9921. ABC Path

      Problem code: ABCPATH


      You will be given a 2-dimensional grid of letters. Find the length of the longest path of consecutive letters, starting at 'A'. Paths can step from one letter in the grid to any adjacent letter (horizontally, vertically, or diagonally).

      For example, in the following grid, there are several paths from 'A' to 'D', but none from 'A' to 'E':

       

      ABC

       

      One such path is:

       

      path

       

      Input:

      Each test case will start with a line contains two integers H, W the height and width of the grid respectively 1 <= H, W <= 50. Then H lines follow each of W uppercase letters only. Input terminates with H = 0 and W = 0.

       

      Output:

      For each test case print “Case C: X” without quotes where C is the case number starting with 1 and X is the solution.

       

      Sample Input:

      4  3

      ABE

      CFG

      BDH

      ABC

      0 0

       

      Sample Output:

      Case_1:_4

       

      Note: The underscore '_' symbol is only for clarity you should print space instead.



      Added by:Ali Arous
      Date:2011-11-05
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FCIS Local Contest 2012









      SPOJ Problem Set (classical)

      9934. Alice and Bob

      Problem code: ALICE

      Alice and Bob are very smart guys and they like to play all kinds of games in their spare time. The most amazing thing is that they always find the best strategy, and that's why they feel bored again and again. They just invented a new game, as they usually did.

      The rule of the new game is quite simple. At the beginning of the game, they write down N random positive integers, then they take turns (Alice first) to either:

      1. Decrease a number by one.
      2. Erase any two numbers and write down their sum.

      Whenever a number is decreased to 0, it will be erased automatically. The game ends when all numbers are finally erased, and the one who cannot play in his(her) turn loses the game.

      Here's the problem: Who will win the game if both use the best strategy? Find it out quickly, before they get bored of the game again!

      Input

      The first line contains an integer T (1 ≤ T ≤ 4000), indicating the number of test cases. Each test case contains several lines. The first line contains an integer N (1 ≤ N ≤ 50). The next line contains N positive integers A1... AN (1 ≤ Ai ≤ 1000), represents the numbers they write down at the beginning of the game.

      Output

      For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y is either "Alice" or "Bob".

      Example

      Input:
      3
      3
      1 1 2
      2
      3 4
      3
      2 3 5
      
      Output:
      Case #1: Alice
      Case #2: Bob
      Case #3: Bob
      

      Added by:Bin Jin
      Date:2011-11-08
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9935. Break the Chocolate

      Problem code: BC

      Benjamin is going to host a party for his big promotion coming up.

      Every party needs candies, chocolates and beer, and of course Benjamin has prepared some of those. But as everyone likes to party, many more people showed up than he expected. The good news is that candies are enough. And for the beer, he only needs to buy some extra cups. The only problem is the chocolate.

      As Benjamin is only a 'small court officer' with poor salary even after his promotion, he can not afford to buy extra chocolate. So he decides to break the chocolate cubes into smaller pieces so that everyone can have some.

      He have two methods to break the chocolate. He can pick one piece of chocolate and break it into two pieces with bare hand, or put some pieces of chocolate together on the table and cut them with a knife at one time. You can assume that the knife is long enough to cut as many pieces of chocolate as he want.

      The party is coming really soon and breaking the chocolate is not an easy job. He wants to know what is the minimum number of steps to break the chocolate into unit-size pieces (cubes of size 1×1×1). He is not sure whether he can find a knife or not, so he wants to know the answer for both situations.

      Input

      The first line contains an integer T (1 ≤ T ≤ 10000), indicating the number of test cases.

      Each test case contains one line with three integers N, M, K (1 ≤ N, M, K ≤ 2000), meaning the chocolate is a cube of size N×M×K.

      Output

      For each test case in the input, print one line: "Case #X: A B", where X is the test case number (starting with 1) , A and B are the minimum numbers of steps to break the chocolate into N×M×K unit-size pieces with bare hands and knife respectively.

      Example

      Input:
      2
      1 1 3
      2 2 2
      
      Output:
      Case #1: 2 2
      Case #2: 7 3
      

      Added by:Bin Jin
      Date:2011-11-08
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9936. Construct the Great Wall

      Problem code: CGW

      A defensive wall is a fortification used to protect a city or settlement from potential aggressors. From ancient to modern times, they were used to enclose settlements.

      Generally, these are referred to as city walls or town walls. Even though, our ancestors decided to build a Great Wall to protect the northern borders of the Chinese Empire against invasion by various nomadic groups.

      The map is given as an rectangle area of size N×M. Each grid is an empty area, a city or an enemy. The Great Wall is a simple polygon build alone the edge of the grids, enclosing all the cities and keeping all the enemies out.

      The Great Wall is not easy to build, so we should make the Great Wall as short as possible. Now it is your job to calculate the length of the shortest Great Wall so that it can protect all the cities from the enemies.

      Input

      The first line contains an integer T (1 ≤ T ≤ 50), indicating the number of test cases.

      Each test case contains several lines. The first line contains two integer H, W (1 ≤ H, W ≤ 8), indicating the number of rows and columns of the map. The following H lines contains W chars, indicating the map. 'o' represents a city, '.' represents a empty area and 'x' represents an enemy.

      You can assume that there will be at least one city on the map.

      Output

      For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y is the length of the shortest Great Wall (-1 if impossible).

      Example

      Input:
      3
      3 3
      .o.
      .x.
      o.o
      4 4
      ....
      .ox.
      .xo.
      ....
      5 5
      .ooo.
      .x...
      ..xoo
      x.xoo
      .ox.x
      
      Output:
      Case #1: 14
      Case #2: -1
      Case #3: 28
      

      Hint

      A simple polygon is a closed polygonal chain of line segments in the plane which do not have points in common other than the common vertices of pairs of consecutive segments.

      The solution for the first test case in sample is shown in Figure 1.

      There is no solution for the second test case because no matter how you build the Great Wall, it will always intersects with itself(Figure 2).


      Added by:Bin Jin
      Date:2011-11-08
      Time limit:50s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9938. Disney Fastpass

      Problem code: DISNEY

      Disney's FastPass is a virtual queuing system created by the Walt Disney Company. First introduced in 1999 (thugh the idea of a ride reservation system was first introduced in world fairs), FastPass allows guests to avoid long lines at the attractions on which the system is installed, freeing them to enjoy other attractions during their wait. The service is available at no additional charge to all park guests.

      --- Wikipedia

      Disneyland is a large theme park with plenties of entertainment facilities, also with a large number of tourists. Normally, you need to wait for a long time before getting the chance to enjoy any of the attractions. The FastPass is a system allowing you to pick up FastPass-tickets in some specific position, and use them at the corresponding facility to avoid long lines. With the help of the FastPass System, one can arrange his/her trip more efficiently.

      You are given the map of the whole park, and there are some attractions that you are interested in. How to visit all the interested attractions within the shortest time?

      Input

      The first line contains an integer T (1 ≤ T ≤ 25), indicating the number of test cases.

      Each test case contains several lines. The first line contains three integers N, M, K (1 ≤ N ≤ 50, 0 ≤ MN(N-1)/2, 0 ≤ K ≤ 8), indicating the number of locations(starting with 1, and 1 is the only gate of the park where the trip must be started and ended), the number of roads and the number of interested attractions.

      The following M lines each contains three integers A, B, D (1 ≤ A, BN, 0 ≤ D ≤ 104) which means it takes D minutes to travel between location A and location B.

      The following K lines each contains several integers Pi, Ti, FTi, Ni, Fi,1, Fi,2 ... Fi,Ni-1, Fi,Ni, (1 ≤ Pi, Ni, Fi,jN, 0 ≤ FTiTi ≤ 104), which means the i-th interested attraction is placed at location Pi and there are Ni locations Fi,1, Fi,2 ... Fi,Ni where you can get the FastPass for the i-th attraction. If you come to the i-th attraction with its FastPass, you need to wait for only FTi minutes, otherwise you need to wait for Ti minutes.

      You can assume that all the locations are connected and there is at most one road between any two locations. Note that there might be several attractions at one location.

      Output

      For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y is the minimum time of the trip.

      Example

      Input:
      2
      4 5 2
      1 2 8
      2 3 4
      3 4 19
      4 1 6
      2 4 7
      2 25 18 1 3
      4 12 6 1 3
      4 6 2
      1 2 5
      1 4 4
      3 1 1
      3 2 1
      3 4 1
      2 4 10
      2 8 3 1 4
      4 8 3 1 2
      
      Output:
      Case #1: 53
      Case #2: 14
      

      Added by:Bin Jin
      Date:2011-11-08
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9939. Eliminate the Conflict

      Problem code: EC

      Conflicts are everywhere in the world, from the young to the elderly, from families to countries. Conflicts cause quarrels, fights or even wars. How wonderful the world will be if all conflicts can be eliminated.

      Edward contributes his lifetime to invent a 'Conflict Resolution Terminal' and he has finally succeeded. This magic item has the ability to eliminate all the conflicts. It works like this:

      If any two people have conflict, they should simply put their hands into the 'Conflict Resolution Terminal' (which is simply a plastic tube). Then they play 'Rock, Paper and Scissors' in it. After they have decided what they will play, the tube should be opened and no one will have the chance to change. Finally, the winner have the right to rule and the loser should obey it. Conflict Eliminated!

      But the game is not that fair, because people may be following some patterns when they play, and if the pattern is founded by others, the others will win definitely.

      Alice and Bob always have conflicts with each other so they use the 'Conflict Resolution Terminal' a lot. Sadly for Bob, Alice found his pattern and can predict how Bob plays precisely. She is very kind that doesn't want to take advantage of that. So she tells Bob about it and they come up with a new way of eliminate the conflict:

      They will play the 'Rock, Paper and Scissors' for N round. Bob will set up some restricts on Alice. But the restrict can only be in the form of you must play the same (or different) on the i-th and j-th rounds. If Alice loses in any round or break any of the rules she loses, otherwise she wins.

      Will Alice have a chance to win?

      Input

      The first line contains an integer T (1 ≤ T ≤ 50), indicating the number of test cases.

      Each test case contains several lines. The first line contains two integers N, M (1 ≤ N ≤ 10000, 1 ≤ M ≤ 10000), representing how many round they will play and how many restricts are there for Alice.

      The next line contains N integers B1, B2, ..., BN, where Bi represents what item Bob will play in the i-th round. 1 represents Rock, 2 represents Paper, 3 represents Scissors.

      The following M lines each contains three integers A, B, K (1 ≤ A,BN, K=0 or 1) represent a restrict for Alice. If K equals 0, Alice must play the same on A-th and B-th round. If K equals 1, she must play different items on A-th and B-th round.

      Output

      For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y is "yes" or "no" represents whether Alice has a chance to win.

      Example

      Input:
      2
      3 3
      1 1 1
      1 2 1
      1 3 1
      2 3 1
      5 5
      1 2 3 2 1
      1 2 1
      1 3 1
      1 4 1
      1 5 1
      2 3 0
      
      Output:
      Case #1: no
      Case #2: yes
      

      Added by:Bin Jin
      Date:2011-11-08
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9940. Fruit Ninja

      Problem code: FNINJA

      Fruit Ninja is a juicy action game enjoyed by millions of players around the world, with squishy, splat and satisfying fruit carnage! Become the ultimate bringer of sweet, tasty destruction with every slash.

      --- Wikipedia

      It is a very popular game on cell phones where people can enjoy cutting the fruit by touching the screen. The screen is rectangular, and all the fruit can be considered as circles, with coordinate of the center, and radius. Note that the fruit may overlap with each other. In this problem, a touch is a straight line cutting through the whole screen, scoring all the fruits it cuts or touches.

      Now Fred is playing the Fruit Ninja, and seems absorbed in the game. He's desperate to create a new record, so he asks you for help. Now you are given a screen shot of the game, help him find the highest score he can get in a single touch.

      Input

      The first line contains an integer T (1 ≤ T ≤ 50), indicating the number of test cases.

      Each test case contains several lines. The first line contains an integer N (1 ≤ N ≤ 1000), indicating the number of fruit.

      The following N lines each contains three integers Xi, Yi, Ri (-1000 ≤ X, Y ≤ 1000, 1 ≤ Ri ≤ 1000), representing a fruit on the screen, where (X, Y) is the coordinate of the center of the fruit, and Ri is the radius.

      You can assume the screen is infinite.

      Output

      For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y is maximum number of fruit that you can cut in a single touch.

      It is guaranteed that the answer will remain the same even if you expand the radius of all the fruit slightly by 10-5.

      Example

      Input:
      2
      4
      -2 5 1
      5 5 1
      -3 2 1
      0 1 1
      4
      -4 5 1
      3 2 1
      -5 3 1
      4 -3 1
      
      Output:
      Case #1: 3
      Case #2: 2
      

      Added by:Bin Jin
      Date:2011-11-08
      Time limit:99s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9941. GRE Words

      Problem code: GRE

      Recently George is preparing for the Graduate Record Examinations (GRE for short). Obviously the most important thing is reciting the words.

      Now George is working on a word list containing N words. He has so poor a memory that it is too hard for him to remember all of the words on the list. But he does find a way to help him to remember. He finds that if a sequence of words has a property that for all pairs of neighboring words, the previous one is a substring of the next one, then the sequence of words is easy to remember.

      So he decides to eliminate some words from the word list first to make the list easier for him. Meantime, he doesn't want to miss the important words. He gives each word an importance, which is represented by an integer ranging from -1000 to 1000, then he wants to know which words to eliminate to maximize the sum of the importance of remaining words. Negative importance just means that George thought it useless and is a waste of time to recite the word.

      Note that although he can eliminate any number of words from the word list, he can never change the order between words. In another word, the order of words appeared on the word list is consistent with the order in the input. In addition, a word may have different meanings, so it can appear on the list more than once, and it may have different importance in each occurrence.

      Input

      The first line contains an integer T (1 ≤ T ≤ 50), indicating the number of test cases.

      Each test case contains several lines. The first line contains an integer N (1 ≤ N ≤ 2×104), indicating the number of words.

      Then N lines follows, each contains a string Si and an integer Wi, representing the word and its importance. Si contains only lowercase letters.

      You can assume that the total length of all words will not exceeded 3×105.

      Output

      For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y is the largest importance of the remaining sequence of words.

      Example

      Input:
      1
      5
      a 1
      ab 2
      abb 3
      baba 5
      abbab 8
      
      Output:
      Case #1: 14
      
      There was a serious and subtle problem regarding the test cases. It has been fixed and all submissions were rejudged now.
      Added by:Bin Jin
      Date:2011-11-08
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9942. Holiday Accommodation

      Problem code: HOLI

      Nowadays, people have many ways to save money on accommodation when they are on vacation. One of these ways is exchanging houses with other people.

      Here is a group of N people who want to travel around the world. They live in different cities, so they can travel to some other people's city and use someone's house temporary. Now they want to make a plan that choose a destination for each person. There are two rules should be satisfied:

      1. All the people should go to one of the other people's city.
      2. Two of them never go to the same city, because they are not willing to share a house.

      They want to maximize the sum of all people's travel distance. The travel distance of a person is the distance between the city he lives in and the city he travels to. These N cities have N-1 highways connecting them. The travelers always choose the shortest path when traveling.

      Given the highways' information, it is your job to find the best plan, that maximum the total travel distance of all people.

      Input

      The first line of input contains one integer T (1 ≤ T ≤ 10), indicating the number of test cases.

      Each test case contains several lines. The first line contains an integer N (2 ≤ N ≤ 105), representing the number of cities. Then the following N-1 lines each contains three integers X, Y, Z (1 ≤ X, YN, 1 ≤ Z ≤ 106), means that there is a highway between city X and city Y, and length of that highway.

      You can assume all the cities are connected and the highways are bi-directional.

      Output

      For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y represents the largest total travel distance of all people.

      Example

      Input:
      2
      4
      1 2 3
      2 3 2
      4 3 2
      6
      1 2 3
      2 3 4
      2 4 1
      4 5 8
      5 6 5
      
      Output:
      Case #1: 18
      Case #2: 62
      

      Added by:Bin Jin
      Date:2011-11-08
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9943. Isabella Message

      Problem code: ISAB

      Isabella and Steve are very good friends, and they often write letters to each other. They exchange funny experiences, talk about people around, share their feelings and write about almost everything through the letters. When the letters are delivered, they are quite afraid that some other people(maybe their parents) would peek. So they encrypted the letter, and only they know how to decrypt it. This guarantees their privacy.

      The encrypted message is an N×N matrix, and each grid contains a character.

      Steve uses a special mask to work as a key. The mask is N×N(where N is an even number) matrix with (N×N)/4 holes of size 1×1 on it.

      The decrypt process consist of the following steps:

      1. Put the mask on the encrypted message matrix.
      2. Write down the characters you can see through the holes, from top to down, then from left to right.
      3. Rotate the mask by 90 degrees clockwise.
      4. Go to step 2, unless you have wrote down all the N×N characters in the message matrix.
      5. Erase all the redundant white spaces in the message.

      For example, you got a message shown in figure 1, and you have a mask looks like figure 2. The decryption process is shown in figure 3, and finally you may get a message "good morning".

      You can assume that the mask is always carefully chosen that each character in the encrypted message will appear exactly once during decryption.

      However, in the first step of decryption, there are several ways to put the mask on the message matrix, because the mask can be rotated (but not flipped). So you may get different results such as "od morning go" (as showed in figure 4), and you may also get other messages like "orning good m", "ng good morni".

      Steve didn't know which direction of the mask should be chosen at the beginning, but after he tried all possibilities, he found that the message "good morning" is the only one he wanted because he couldn't recognize some words in the other messages. So he will always consider the message he can understand the correct one. Whether he can understand a message depends whether he knows all the words in the message. If there are more than one ways to decrypt the message into an understandable one, he will choose the lexicographically smallest one. The way to compare two messages is to compare the words of two messages one by one, and the first pair of different words in the two messages will determine the lexicographic order of them.

      Isabella sends letters to Steve almost every day. As decrypting Isabella's message takes a lot of time, and Steve can wait no longer to know the content of the message, he asked you for help. Now you are given the message he received, the mask, and the list of words he already knew, can you write a program to help him decrypt it?

      Input

      The first line contains an integer T (1 ≤ T ≤ 100), indicating the number of test cases.

      Each test case contains several lines. The first line contains an even integer N (2 ≤ N ≤ 50), indicating the size of the matrix.

      The following N lines each contains exactly N characters, reresenting the message matrix. The message only contains lowercase letters and periods('.'), where periods represent the white spaces. You can assume the matrix contains at least one letter.

      The following N lines each contains N characters, representing the mask matrix. The asterisk('*') represents a hole, and period('.') otherwise. The next line contains an integer M(1 ≤ M ≤ 100), the number of words he knew.

      Then the following M lines each contains a string represents a word. The words only contain lowercase letters, and its length will not exceed 20.

      Output

      For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y is Isabella's message.

      If Steve cannot understand the message, just print the Y as "FAIL TO DECRYPT".

      Example

      Input:
      3
      4
      o.do
      .ng.
      grmn
      o.i.
      .*..
      *.*.
      ....
      *...
      2
      good
      morning
      4
      ..lf
      eoyv
      oeou
      vrer
      ..*.
      .*..
      ....
      *.*.
      5
      i
      you
      the
      love
      forever
      4
      .sle
      s.c.
      e.fs
      ..uu
      *...
      .*..
      ...*
      ..*.
      1
      successful
      
      Output:
      Case #1: good morning
      Case #2: love you forever
      Case #3: FAIL TO DECRYPT
      

      Added by:Bin Jin
      Date:2011-11-08
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9944. Ji-Tu Problem

      Problem code: JITU

      There are some chickens and rabbits in the cage. They have fifteen heads and forty feet in all. How many chickens and rabbits are there respectively?

      It is a classical math problem which can date back to the Northern and Southern Dynasties (420-589). Here is an interesting algorithm to solve the problem: Assume that the chickens and rabbits are well trained. You whistle, and all of them lift a leg, then there are 40-15=25 feet on the floor. You whistle again, and there are 25-15=10 legs remain standing. After two whistles, all the chickens sit on the floor, and all the rabbits stand on two legs. So there are 10/2=5 rabbits and 15-5=10 chickens.

      John has a farm with lots of animals in it. He is now facing the similar problem. There are exactly N kinds of animals and he wants to know their quantities. He only knows that different kinds of animals have different number of legs (at least one), but he has no idea how many legs they each have. He trains the animals and tries to figure it out using the algorithm stated above. First he makes all the animals stand up with all their legs and counts their legs. Then, for each time he whistles, all the animals lift one leg(if it has at least one leg standing on the ground), and then he counts the feet again. After K times, he thinks that it is enough to determine the quantity of each kind of animal, but does it really work? So, it is your job to help him to solve the problem.

      Input

      The first line contains an integer T (1 ≤ T ≤ 100), indicating the number of test cases.

      Each test case contains two lines. The first line contains two integers N (1 ≤ N ≤ 1000) and K (1 ≤ K ≤ 1000), representing the number of different kinds of animals and the time he whistles.

      The second line contains K+1 integers A0 , A1... AK (0 ≤ Ai ≤ 104) where Ai represents the number of legs after his i-th whistle.

      Output

      For each test case in the input, print several lines.

      The first line contains "Case #X:", where X is the test case number (starting with 1). The next line contains "No Solution", "Unique Solution" or "Multiple Solutions" according to the result.

      If the result is uniquely determined, you should print N extra lines each contains two integer Li, Ni, where Li represents how many legs does the i-th kind of animal have and Ni represents the number of i-th kind of animal. The animals should be sorted by the number of their legs in ascending order.

      Example

      Input:
      3
      2 3
      14 9 6 3
      2 2
      8 5 3
      3 2
      20 13 8
      
      Output:
      Case #1:
      Unique Solution
      1 2
      4 3
      Case #2:
      No Solution
      Case #3:
      Multiple Solutions
      

      Added by:Bin Jin
      Date:2011-11-08
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2011









      SPOJ Problem Set (classical)

      9948. Will it ever stop

      Problem code: WILLITST

      When Bob was in library in University of Warsaw he saw on one of facades caption :"Will it ever stop?" and below some mysterious code:

      while n > 1
        if n mod 2 = 0 then
          n:=n/2
        else
          n:=3*n+3

      Help him finding it out !

      Input

      In first line one number n<=10^14.

      Output

      Print "TAK" if program will stop, otherwise print "NIE"

      Example

      Input:
      4
      
      Output:
      TAK
      

      Added by:Krzysztof Lewko
      Date:2011-11-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:AMPPZ 2011









      SPOJ Problem Set (classical)

      9950. IQ Team

      Problem code: IQTEAM

      In Byteland we can study only math and IT.

      In the university there are n math students and m IT students.

      Rector Byteasar knows IQ of every student. He wants to make the best team, which would solve the hardest human being problems. So he decided to pick team with the highest sumarry IQ.

      Of course it's not everything. He wants to make team in which each student knows another students from team.

      Every student from IT know other student from IT and same with math students.

      Help him finding team with the largest summary IQ and in which every student from team knows another students from team.

      Input

      In first line n,m,k ( 0<n<=400, 0<m<=400, 0<=k<=n*m ) which means number of math students, number of IT students, number of friendships between IT and math student.

      In next k lines pairs

      0<ai<=n 0<bi<=m, which means ai student from math knows bi student from IT.

      In next line n numbers, IQ of i-th math student.

      In next line m numbers, IQ of i-th IT student.

      Output

      Output in one line : number of team's summary IQ.

      Example

      Input:
      
      3 2 3
      1 1
      2 1
      2 2
      1 3 1
      1 2
      Output:
      6

      Added by:Krzysztof Lewko
      Date:2011-11-09
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:AMPPZ 2011









      SPOJ Problem Set (classical)

      9952. 111…1 Squared

      Problem code: GUANGGUN

      We call an integer Sticks if its decimal representation contains only digit 1.

      Let S(n) be the sticks with n digits, find the sum of digits of S(n)2

      For example, S(9)2=12345678987654321, its sum of digits is 81.

      Input

      Each line contains an integer represents n(1 ≤ n ≤ 1018).

      Input is terminated by EOF, and contains at most 100 lines.

      Output

      For each n, print an integer represents the answer.

      Example

      Input:
      9
      10
      
      Output:
      81
      82
      

      Added by:Bin Jin
      Date:2011-11-11
      Time limit:1s
      Source limit:4096B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      9964. Fibonacci vs Polynomial

      Problem code: PIBO

      Define a sequence Pib(n) as following

      • Pib(0) = 1
      • Pib(1) = 1
      • otherwise, Pib(n) = Pib(n-1) + Pib(n-2) + P(n)

      Here P is a polynomial.

      Given n and P, find Pib(n) modulo 1,111,111,111.

      Input

      First line of input contains two integer n and d (0 ≤ n ≤ 109, 0 ≤ d ≤ 100), d is the degree of polynomial.

      The second line contains d+1 integers c0,c1cd, represent the coefficient of the polynomial(Thus P(x) can be written as Σcixi). 0 ≤ ci ≤ 100 and cd ≠ 0 unless d = 0.

      Output

      A single integer represents the answer.

      Example

      Input:
      10 0
      0
      
      Output:
      89
      
      Input:
      10 0
      1
      
      Output:
      177
      
      Input:
      100 1
      1 1
      
      Output:
      343742333
      
      

      Added by:Bin Jin
      Date:2011-11-11
      Time limit:5s
      Source limit:10240B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: C++ 4.0.0-8









      SPOJ Problem Set (classical)

      9967. Playing with Words

      Problem code: PWORDS

      Amr M. believes in conspiracies. He is very suspicious about everything, and he is always trying to uncover the truth to everyone (or so he thinks). Lately he became very suspicious of TV ads, especially the ones that are made of 2 words: ad1 and ad2, and thinks they carry hidden messages.

      After contacting his top secret resources, he found out the process that the evil people use to hide the message. The original message is always two strings: orig1 and orig2.

      The transformation happened as follows:

      1. The letters from orig1 are shuffled.
      2. The letters from orig2 are shuffled.
      3. One letter from either orig1 or orig2 is replaced with its next or previous letter in the alphabet.

      This produces ad1 and ad2 from orig1 and orig2 respectively. For example for orig1 = "bcd", orig2 = "wcy" we may have ad1 = "dcb", ad2 = "cxy" (shuffled to cwy and 'w' replaced with 'x')

      After more research, Amr also found out the distance X, which is equal to distance(orig1,ad1)+distance (orig2,ad2). The distance between 2 strings is the sum of absolute difference between the letters at same positions (e.g. difference("ab","cd") =  abs('a'-'c')+abs('b'-'d') = 4)

      But the number of possible original messages appears to be very high, so Amr hired you to count them. Given string ad1 and ad2, and X = distance(orig1,ad1) + distance (orig2,ad2), return the number of possible strings orig1 & orig2.

      Input Specification:

      The first line of input contains an integer T that represents the number of test cases, then follow T lines each line is in format ad1 ad2 X, space separated where ad1, ad2 are composed from English small-case letters.

      1 ≤ length (ad1),  length(ad2)  ≤ 10, 'b' ≤ ad1[i], ad2[i] ≤ 'y' and 0 ≤ X ≤ 100000

      Output Specification:

      For each test case, output a single line of output in the form “Case K: cnt” where K is the number of the test case and cnt is the number of possible strings orig1 & orig2.

      Sample input:

      2
      c n 1
      kbenh kbenh 5

      Sample Output:

      Case 1: 4
      Case 2: 16

       


      Added by:Mostafa Saad
      Date:2011-11-13
      Time limit:50s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:10th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      9968. Magic Crystals and Laser Beams

      Problem code: MCLB

      John and Ged are playing a game with magic crystals and a laser beams. The game starts by arranging a 64 magic crystal in a single row and both John and Ged stand on the right of this row and start shooting them with laser beams. The magic crystals come in different colors each of which has a different behavior.  The red crystal absorbs the laser beam while the blue crystal allows the laser beam to move through it passing to the following crystal. In both cases, the crystals flip its color: red crystal flips to blue crystal while blue crystal flips to red crystal. The behavior of crystals with other colors is not always defined so they will not be part of the game. The game ends when all the magic crystals are all red.

      After a long time of playing with the magic crystals, John was wondering, given start state of crystals order, after how many laser beams they can reach a given target order before reaching the end of the game. Kindly help them J, and if the target state can’t be reached, tell them.

      Input Specification:

      A row of crystals is represented by a string, and the row's right is the last character in the given string. The first line of input contains an integer T that represents the number of test cases, then follow 2T lines such that each case will consist of 2 lines each of them contain a string of exactly 64 character either R (for Red) or B (for Blue) . The first line is the starting state of the game and the second line is the state that John wonders if they can reach.

      Output Specification:

      For each test case, output a single line of output in the form “Case K: state” where K is the number of the test case and state is either “The goal state could be reached after X laser beams.” Or “The goal state will never be reached!” where X is the number of laser beams needed before reaching the goal state.

      Sample input:

      3
      BBRRBRBRBRBBRBBBRBBRBRBBBRBBBRBRRRBBRBRBBRBRBRBRBBRBRBRBRRBBBBBR
      BBRRBRBRBRBBRBBBRBBRBRBBBRBBBRBRRRBBRBRBBRBRBRBRBBRBRBRBRBRRRRRR
      BBRRBRBRBRBBRBBBRBBRBRBBBRBBBRBRRRBBRBRBBRBRBRBRBBRBRBRBRRBBBBBR
      RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
      RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
      BBRRBRBRBRBBRBBBRBBRBRBBBRBBBRBRRRBBRBRBBRBRBRBRBBRBRBRBRRBBBBBR

      Sample Output:

      Case 1: The goal state could be reached after 2 laser beams.
      Case 2: The goal state will never be reached!
      Case 3: The goal state will never be reached!

       


      Added by:Mostafa Saad
      Date:2011-11-13
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:10th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      9969. Road Network

      Problem code: RDNWK

      In a country of N cities, the government would like to develop a new system that can answer drivers’ queries to find the shortest path between 2 cities in the country road network. However, some cities are more exciting than others, and drivers would prefer driving through them. Last month, a voting for the most exciting cities in the country was conducted, and a ranking of the P most exciting cities has been made. The government decided to utilize this ranking so that drivers can find the shortest path between 2 cities that only goes through the first K cities of the ranking as intermediate cites on the road. Hence, the query is defined as: the source city, the destination city, and K for the first K cities from the ranking. (Note that some cities may not be exciting at all, and so they will not be included in the ranking, i.e. P <= N)

      Given undirected graph representing the country cities, and ranked list of exciting cities, you are to answer Q quires, each one asking for the shortest path between 2 cities utilizing only the first K cities from the ranked list.

      For example, given the graph in the sample (4 cities and ranked list [2 1])

      1- Query(k=0, Src=3, dest=4): means no cities to use as intermediate, hence only direct path allowed à 3-4 with cost 10

      2- Query(k=1, Src=3, dest=4): means we can use first city on list (2), hence we can choose between paths (3-4, 3-2-4) à path 3-2-4 with cost 8 is best

      3- Query(k=2, Src=3, dest=4): means we can use first 2 cities on list (1, 2), hence we can choose between paths (3-4, 3-2-4, 3-2-1-4) à path 3-2-1-4 with cost 6 is best

       

       

      Input Specification:

      The first line of input contains an integer T that represents the number of test cases, then follow T test cases, each in following format:

      Line 1

                  N (1 ≤ N ≤ 150), the number of cities of the country

      N-1 lines follow, where ith line represents ith- city connections' costs, Ci,j is the cost of edge (i, j), if there is no edge between i, j then Ci, j = -1 else, 1 Ci,j 10000

                  C1, 2    C1, 3    ... C1, N

                  C2, 3    C2, 4    ... C2, N

                  ...

                  CN-1, N

      Line N+1

                  P (0 ≤ P ≤ N), represents the size of ranked list

      Line N+2

                  P space-separated list of distinct cities ids (1 <= city id <= N)

      Line N+3

                  Q (1 ≤ Q ≤ 6000), represents the number of queries

      Q lines follow

                  K source destination

      ....

       

      Note that: 0 ≤ K ≤ P, 1≤ source ≤ N and 1≤ destination ≤ N

       

      Output Specification:

      For each test case, output a single line of output in the form “Case K: A1 A2 …Aq” where K is the number of the test case and [A1 A2 … Aq] are the answers for the Q quires. Each answer is the shortest path cost between the 2 given cities using the first only K cities of given list as intermediate cities. In case no path between 2 cities, the answer is -1

      Sample input:

      1

      4

      2 -1 3

      1 7

      10

      2

      2 1

      3

      0 3 4

      1 3 4

      2 3 4

      Sample Output:

      Case 1: 10 8 6


      Added by:Mostafa Saad
      Date:2011-11-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:10th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      9970. The Egyptian Parliament

      Problem code: EGYPAR

      This year, Egypt has been going through an extremely challenging stage. The parliamentary elections are about to take place according to a newly introduced election laws. The seats of the parliament are going to be divided in a party-list proportional representation. This type of elections allows voters to vote for a party (not for individual candidates). Each party wins a number of seats which depends on the number of votes they received.

      You are the president of the ACM party in your electoral district (Association of Corrupt Murderers) and you want your party to win as much seats as possible in the coming elections. You know exactly how many people will vote for every party (including yours), thanks to your amazing prediction abilities.

      There are two proposed voting systems (explained later) and it is not yet decided which of them is going to be used. You can use your connections trying to influence the decision of which voting system is put to use. Assuming your prediction is completely correct, the problem is to find the voting system that will let your party win more seats.

      Voting System 1: D'Hondt method

      This system is used in many countries, including Turkey, Japan and Spain. Let's say there are P parties and S seats. This method creates a grid of numbers, with P rows and S columns, where the entry in the i-th row and j-th column is the number of votes won by the i-th party divided by the number j. The first seat is given to the party that has the entry with the highest value. The second seat is given to the party that has the entry with the second highest value, and so on. If two or more entries have the same value, then the seat is given to the party that occurs first in the input file (for the simplicity of this problem).

       

      For example: if 5 seats are to be allocated, divide each party's total votes by 1, then by 2, 3, 4 and 5. An example is given in the table below. The 5 highest five entries are highlighted in bold, ranging from 70.0 down to 30.0. The tie between party B and party D is resolved by giving the seat to B as it occurs first in the input. For each cell in bold, the corresponding party gets a seat.

      Party

      Number of received votes (V)

      V/1

      V/2

      V/3

      V/4

      V/5

      Seats won

      A

      70

      70

      35

      23.3

      17.5

      14

      2

      B

      60

      60

      30

      20

      15

      12

      2

      C

      50

      50

      25

      16.7

      12.5

      10

      1

      D

      30

      30

      15

      10

      7.5

      6

      0

       

      Voting System 2: Sainte-Laguë method

      This system is used in fewer countries, including Norway, Sweden and Germany. This method favors smaller parties more than D'Hondt method. After the votes to each party has been counted, the parliament seats are given in an iterative way, one by one to the party that has the highest quotient. The quotient of a party is calculated by this formula: quot = V / (2s+1)

      Where:

      V: is the total number of votes that party received, and

      s: is the number of seats that party has been allocated so far, initially 0 for all parties.

       

      For simplicity, if two or more parties are tied because they have the same quotients, the party that occurs first in the input file is given the  next seat allocated. The quotients are recalculated after each seat has been given and this process is repeated until all seats have been allocated.

      Example: using the same example from before, in the table below:

      Party

      Number of received votes (V)

      quot in round 1

      quot in round 2

      quot in round 3

      quot in round 4

      quot in round 5

      Seats won

      A

      70

      70

      23.3

      23.3

      23.3

      23.3

      2

      B

      60

      60

      60

      20

      20

      20

      1

      C

      50

      50

      50

      50

      16.7

      16.7

      1

      D

      30

      30

      30

      30

      30

      10

      1

      The cells in bold represent the highest quotient for this seat and their party wins a seat correspondingly.

      Input Specification:

      First line of the input will contain T, the number of test cases. T test cases follow. The first line of each test case contains two integers N and S, separated by a single space. N is the number of parties and S is the number of seats to be allocated, 2  ≤ N, S ≤ 10,000. Each of the next N lines contains the name of the party P[i], a unique string of at most 20 lowercase and upper case English letters, followed by a single space, then an integer V[i], the exact number of predicted votes to be earned by this party. 0  ≤ V[i] ≤ 10^9 (1,000,000,000). The number of earned votes may be delimited by comas (e.g. could be 127 or 12,7). “ACM” will exist as a party name exactly once in every input case.

      Output Specification:

      For each test case, output a single line of output in the form “Case K: Method” where K is the number of the test case and Method is “S”, “D”, or “No difference”.

      Method = “D” if D'Hondt method wins the ACM party more seats. Method = “S” if Sainte-Laguë method wins the ACM party more seats. If both methods result in the same seat count for your party, then method = “No difference”.

      Sample input:

      1

      6 10

      Yellow 47000

      White 16000

      Red 15900

      ACM 12000

      Blue 6000

      Pink 3100

      Sample Output:

      Case 1: No difference


      Added by:Mostafa Saad
      Date:2011-11-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:10th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      9971. Adventurous Chess Masters

      Problem code: ACHESS

      The world of the Adventurous Chess Masters is quite different than our world, instead of having streets and buildings everything is composed of a big chess board and chess pieces. A square of a chess board is said to be covered if at least one chess piece is placed on it. The mysteries of the world can be revealed by covering special magical squares over the chess board, and you can't wait to discover them.

      In every turn you can update the board by moving one of the pieces on the board according to the following rules:

      • The king moves only one square in any direction.
      • The queen moves any number of squares in any direction along a row, column, or diagonal.
      • The rook moves any number of squares along rows or columns (forward, backward, left or right).
      • The bishop moves any number of squares diagonally.
      • The knight moves to a square in an "L"-shape (two spaces forward, backward, left, or right and one space perpendicular to it).
      • The pawn can only move one space forward or backward (unlike a chess game).\

      Note that, unlike normal chess, more than one piece can occupy the same square and pieces can move through occupied squares. To reveal the secrets of the world you have to make the maximum number of magical squares covered, in the minimum number of turns.

      Input Specification:

      The first line of input contains an integer T that represents the number of test cases, then follow T test cases. The first line of each test case contains P and L, the number of chess pieces on the board and the number of magical squares in order.  Following the first line P lines each contains two integers x and y coordinates of the location of the piece where (1 ≤ x, y ≤ 8) and the type of the chess pieces (king, queen, rook, bishop, knight, or pawn…all in small letters) and the last L lines of the test case each contains a unique pair of integers x and y as the coordinates of the magical squares where (1 ≤ x, y ≤ 8). Note that: (0 ≤ P ≤ 64), and these P pieces won't be in any of the L given locations.

       

      Output Specification:

      For each test case, print on one line “Case K: Secret reveals after moving H pieces with minimum number of moves M.” Where K is test case number, H is the number of pieces to be moved and M is the total number of moves used. Check Sample below to see the format.

      Sample input:

      2
      1 1
      1 1 pawn
      8 1
      3 5
      2 8 king
      2 8 queen
      7 5 bishop
      1 1
      2 2
      3 6
      6 3
      4 4

      Sample Output:

      Case 1: Secret reveals after moving 1 pieces with minimum number of moves 7.
      Case 2: Secret reveals after moving 3 pieces with minimum number of moves 5.


      Added by:Mostafa Saad
      Date:2011-11-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:10th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      9972. The SKey

      Problem code: SKEY

      It is the 10-th ACM Egyptian National Programming Contest and Mostafa S., the chief judge, started to prepare for the problem set. In previous years, a chief judge used to ask problems’ setters to use his public key to encrypt the data so that they keep everything related to the problems secured. Unfortunately, the RSA algorithm was broken 2 weeks ago and Mostafa decided to invent a temporary algorithm till someone finds a new robust approach for encrypting/decrypting  plaintext. After finding the algorithm, Mostafa met the judges and described the new encryption algorithm for them and gave them an equation to generate a key which the algorithm depends on. The key is generated through the following equation:

      SKEY = (M * SUM [1 / A^K (from k = 0 to k = N)] ) % P

      A, N and P are integers and P is a prime number that is co-prime with A (e.g. gcd(A, P) = 1). Furthermore M is a very large number (millions of digits) generated to be divisible by . For example given: A = 3, N = 2, P =  7  and M = 18, then the skey value is:

       (18 * (1/1 + 1/3 + 1/9)  ) % 7 = 26 % 7 = 5.

       

      Unfortunately, sending extremely large numbers for M in the emails between judges is impractical. Luckily, a property of the modulus operator is: (A*B)%X = (A%X * B%X) %X.

      Hence, we still can find our way to evaluate the skey by replacing M with M%P.

       

      Given A, N, P, M%P, kindly help the chief judge with writing a code to compute the SKey.

      Input Specification:

      The first line of input contains an integer T that represents the number of test cases, then follow T lines each contains only four integer numbers A, N, P where 1 ≤ A ≤ 2147483647, 0 ≤ N ≤ 2147483647, 2 ≤ P ≤ 2147483647 and 0 ≤ M%P < P.

      Output Specification:

      For each test case, output a single line of output in the form “Case K: SKey” where K is the number of the test case and Skey is as defined in the problem statement. Check sample below for the format.

      Sample input:

      1

      3 2 7 4

      Sample Output:

      Case 1: 5


      Added by:Mostafa Saad
      Date:2011-11-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:10th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      9973. Problem Set Score

      Problem code: PROSCORE

      Fegla, one of the ACM ICPC coaches, is very happy as one of his teams won the ACPC regional contest, and now he is preparing his team for the ACM ICPC World Final. He decided to establish a training camp for his team in the north coast, practicing on subset of problem sets from previous World Final contests to sharpen the team skills, but he needs to choose this subset wisely as World Final is soon.

      After a long discussion with his team, they agreed on a certain criteria to choose the problem sets that will help in the training. Considering a problem set with N teams and P problems, a good problem set must satisfy the following conditions to be chosen:

      1. Any problem is solved by at least one team.
      2. Minimum number of solved problems per team is one.
      3. Maximum number of solved problems per team is less than p.

       

      Although they are all programmers, these lazy guys would to ask for your help in writing a program to calculate that for them. We really doubt that they will do something in the World Finals with such behavior,  so kindly help them, even if you are not from their school to state these 3 conditions for a given problem set. But, push them for some work, represent the true condition as 1 and the false condition as 0, and then convert the result to a decimal number to be the problem set score. Let the first condition to be the most left bit, the third condition to be the right most bit and the second condition to be middle bit. E.g. if a problem set matched only the first condition, it's represented as "100" and converted to 4.

      Input Specification:

      First line contains an integer T that represents the number of test cases, then follow T test cases, each in the following format: Line 1 contains two integers N and P, space separated, where 0 < N, P ≤  10. Then N lines each contains P integers are followed, where i-th line and j-th column represent (team=i, problem=j) state: 1 if problem is solved and 0 otherwise.

      Output Specification:

      For each test case, print on one line, “Case K: score” where K is the Test Case number and score is the problem set score.

      Sample input:

      1
      2 3
      1 1 1
      0 0 0

      Sample Output:

      Case 1: 4


      Added by:Mostafa Saad
      Date:2011-11-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:10th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      9974. Men From Mars

      Problem code: MENMARS

      Beings (men) living on Mars discovered that there are beautiful beings (women) living on Venus.  Men decided to change their life and want to travel using their spaceships to Venus to start a new life style. Unfortunately, women love connections and relationships and they won’t let a group of spaceships pass to their planet unless the number of spaceships in one of the “fully coupled” subgroups exceeds a certain minimum threshold. A fully coupled/connected group of spaceships is a group with each pair of spaceships can communicate together.

      The spaceships and their airport on mars are very complicated. First, a spaceship communicates with another spaceship only if a command from the airport headquarter is issued. Second, the airport is a small one that can launch at a time a group of maximum K spaceships, connected in a random way. There are 2 types of commands that can be issued from headquarter to manage the spaceships connections: 1) Flip command for a group that establishes a new communication between every pair of disconnected spaceships and disconnect every previously connected pair of spaceships in the group, 2) Merge command for some of the groups to let them be one group, but no communications/connections modifications happen.

      Unfortunately, under these constraints we can’t launch all spaceships in a fully coupled state that satisfies women. So, the Men developed an automatic software that will issue commands to launch the spaceships in groups, then will issue commands (Flip, Merge) in a way that hopefully produces at least one of the fully connected subgroups with maximum number of spaceships that satisfies women so that they pass to Venus.

      Given the groups of spaceships and the issued commands for them, you have to calculate the maximum number of spaceships that are fully coupled in the final group.

      Input Specification:

      The first line of input contains an integer T that represents the number of test cases, then follow T test cases. Each test case start with a line with N (the number of spaceships - 1 ≤ N ≤ 1000), M (the number of launch groups - 1 ≤ M ≤ 1000). Then M lines follow, one for each group: starting with K (number of spaceships in the group 1 ≤ K ≤ 10), E (number of connections in the group), and then E pair of numbers representing bidirectional connection between 2 spaceships: space_ship_id1, space_ship_id2 where 0 ≤ space_ship_id1, space_ship_id2 < K. The m-th group has id (m-1).

      Then Set of commands are given, each one on a line. Flip command on format “F group_id” to flip the group with given group id. Merge Command on format “M T group_id_1, group_id_2… group_id_T” that merges T groups and let their new id to be the maximum id of the merged groups.

       

      Output Specification:

      For each test case, output a single line of output in the form “Case K: T” where K is the number of the test case and T is the maximum number of spaceships that are fully coupled in the final group. Check sample below for the format.

      Sample input:

      1

      7 4

      3 3 0 1 0 2 1 2

      2 1 0 1

      1 0

      1 0

      F 1

      M 2 1 2

      F 0

      M 2 0 2

      F 2

      M 2 3 2

      *

      Sample Output:

      Case 1: 6

      Sample Explanation

      In this example we have 7 spaceships in 4 groups. First group (id = 0) is forming a triangle shape, second is segment shape, third is isolated spaceship and forth (id = 3) is also isolated. The first command flips the second group to 2 isolated spaceships. The second command merge 2 groups, id =2 to have 3 isolated spaceships with new. The third command flips first group to 3 isolated spaceships. The fourth one merges them under one group of 6 isolated group with id = 2. The fifth command flips this group to a fully coupled group of 6 spaceships. Finally a merge for that group with the fourth group and we have a new group with id = 3 of 6 spaceships fully connected and 1 isolated node.


      Added by:Mostafa Saad
      Date:2011-11-13
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:10th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      9975. No Stories Any More!

      Problem code: FSEQ

      Have you ever wished to be given a direct problem statement in the contest? Do you hate the boring stories that problem setters write...starting from “john was going on a trip”…passing with “blablabla”…and ending with “kindly help John J”. We all know that there is no John so why wasting contestants time. As we were contestants and know that feeling very well, we decided to break that boring way and save your time…

      Given the following sequence details:  F(0) = 0, F(1) = 1       and 

                 SUM F(i) [i from 0 to n] = F(n+2) - 1

      For a given integer M, we will generate another infinite sequence defined as:  T(i) = F(i) % M. We noticed that this is a repeating sequence: it repeats itself after some C iterations, where C is the cycle length for sequence T. Let’s define H(j), as the finite, most left, strictly increasing sub-sequence starting at position j in the sequence T, preserving the elements order of T. In other words:

      1)      H(0), the first element in H, is T(j)

      2)      H(1)  = T(k1), where T(k1) is the first element > T(j) where j < k1

      3)      H(2)  = T(k2), where T(k2) is the first element > T(k1) where k1 < k2, and so on

      For example, if M = 4, then T = [0 1 1 2 3 1   0 1 1 2 3 1   0 1 1 2 …]. Furthermore: H(0) = [0 1 2 3], H(3) = [2 3], and H(5) = [1 2 3]. Length(  H(j) ) is the number of elements in that sequence, e.g. Length(H(5)) = 3. The Cycle length(C) for sequence T is 6.

       

      For a given M, you will calculate its C, and evaluate the following summation:

                                                SUM Length( H(k) ) [k = 0 to C-1]

      Input Specification:

      The first line of input contains an integer T that represents the number of test cases, then follow T lines each contains an integer 1 ≤ M ≤ 105. NOTE: for any given test case, sequence T repeats after maximum C iterations where C ≤ 105.

      Output Specification:

      For each test case, output a single line of output in the form “Case K: summation” where K is the number of the test case and summation is as defined in the problem statement.

       

      Sample input:

      1

      4

      Sample Output:

      Case 1: 16


      Added by:Mostafa Saad
      Date:2011-11-13
      Time limit:13s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:10th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      9985. Distance

      Problem code: DISTX

      In this task let's consider distance between two positive integers defined as below.

      Single operation is : multiplying some number by prime number or dividing some number by prime number ( we can divide only when remainder is equal to 0 )

      Distance d between two numbers a,b is minimum number operations to convert one number to another.

      For example d(69,42)=3

      This distance is very similiar to well-known term "distance" in real human life:

      d(a,a)=0 , distance number to itself is 0

      d(a,b)=d(b,a) distance from a->b is equal to b->a

      d(a,b)+d(b,c)>=d(a,c) triangle equation is true too

      With given n number you have to determine for each i-th of those numbers closest number aj from set that

      i!=j and if there is many numbers with equal, smallest distance, you have to pick number with smallest index

      Input

      In first line - number n <=10^5.

      In next n lines - i-th number. Every number is not greater than 10^6

      Output

      You have to output n lines.

      I-th line should contain index of closest number ( if there is many answers, please output smallest index )

      Example

      Input:
      6
      1
      2
      3
      4
      5
      6
      Output: 2
      1
      1
      2
      1
      2

      Added by:Krzysztof Lewko
      Date:2011-11-15
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:19th POI 1st stage









      SPOJ Problem Set (classical)

      10050. Power Tower City

      Problem code: POWTOW

      You are living in a city build entirely of power towers such as 3^3^3 and 10^10^10^10. To enter a building you must type the last 9 digits of the number represented by the tower, written in decimal form, on a keypad next to the main entrance. You are not sharp enough at mental maths, but you can write a handy program to bring along in your pocket.

      A power tower is defined as repeated exponentiation. We write this using Knuth's up-arrow notation as: e↑↑a = e^e^...^e (a terms). Remember that ^ (exponentiation) is right assosiative. For example: 2↑↑4 = 2^2^2^2 = 2^(2^(2^2)) = 2^2^4 = 2^16 = 65536, and 3↑↑1 = 3. The value of a tower of heigh 0 is 1.

      Input

      The first line contains integer C in [0..1000], the number of test cases.

      Then follows C lines, each with integers e,a in [0..2147483647]. (non-negative 32-bit ints).

      Output

      For each testcase output e↑↑a, or if the output has more than 9 digits, output "..." and then the last 9 digits.

      Example

      Input:
      
      3
      0 0
      2 5
      993306745 75707320
      
      Output:
      
      1
      ...719156736
      ...884765625

      Added by:Thomas Dybdahl Ahle
      Date:2011-11-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10069. Kompiæi

      Problem code: KOMPICI

       

      After successfully solving his math homework from the previous task, Mirko has become bored, so he 
      has made a list of N large integers. On the list there are some pairs of numbers that he likes, and some 
      pairs he doesn’t like. 
      Mirko has named the pairs that he likes pals. Two numbers are pals if they have at least one digit in 
      common (not necessarily in the same position). 
      Help Mirko count how many pairs of numbers in his list are pals. 
      INPUT 
      The first line of input contains the positive integer N (1 ≤ N ≤ 1 000 000). 
      Each of the next N lines contains a positive integer from the range [1, 10
      18
      ], a number from Mirko’s 
      list. No two numbers in the list will be equal. 
      OUTPUT 
      The first and only line of output must contain the number of pairs that are pals. 

      After successfully solving his math homework from the previous task, Mirko has become bored, so he has made a list of N large integers. On the list there are some pairs of numbers that he likes, and some pairs he doesn’t like. Mirko has named the pairs that he likes pals. Two numbers are pals if they have at least one digit in common (not necessarily in the same position). 

      Help Mirko count how many pairs of numbers in his list are pals

      Input

      The first line of input contains the positive integer N (1 ≤ N ≤ 500 000).Each of the next N lines contains a positive integer from the range [1, 10^18], a number from Mirko’s list. No two numbers in the list will be equal.

      Output

      The first and only line of output must contain the number of pairs that are pals.

      Example

      Input:
      3
      4
      20
      44
      
      Output:
      1

      Added by:Tadeusz Dul
      Date:2011-11-23
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 HASK JAVA PAS fpc PYTH 2.7
      Resource:COCI 2011/2012 2nd round









      SPOJ Problem Set (classical)

      10070. Trick or Treat

      Problem code: TRICKTRT

      Johnny and his friends have decided to spend Halloween night doing the usual candy collection from the households of their village. As the village is too big for a single group to collect the candy from all houses sequentially, Johnny and his friends have decided to split up so that each of them goes to a different house, collects the candy (or wreaks havoc if the residents don’t give out candy), and returns to a meeting point arranged in advance.

      There are n houses in the village, the positions of which can be identified with their Cartesian coordinates on the Euclidean plane. Johnny’s gang is also made up of n people (including Johnny himself). They have decided to distribute the candy after everybody comes back with their booty. The houses might be far away, but Johnny’s interest is in eating the candy as soon as possible.

      Keeping in mind that, because of their response to the hospitality of some villagers, some children might be wanted by the local authorities, they have agreed to fix the meeting point by the river running through the village, which is the line y = 0. Note that there may be houses on both sides of the river, and some of the houses may be houseboats (y = 0). The walking speed of every child is 1 meter per second, and they can move along any direction on the plane.

      At exactly midnight, each child will knock on the door of the house he has chosen, collect the candy instantaneously, and walk back along the shortest route to the meeting point. Tell Johnny at what time he will be able to start eating the candy.



      Input

      Each test case starts with a line indicating the number n of houses (1 ≤ n ≤ 50 000). The next n lines describe the positions of the houses; each of these lines contains two floating point numbers x and y (−200 000 ≤ x, y ≤ 200 000), the coordinates of a house in meters. All houses are at different positions.

      A blank line follows each case. A line with n = 0 indicates the end of the input; do not write any output for this case.



      Output

      For each test case, print two numbers in a line separated by a space: the coordinate x of the meeting point on the line y = 0 that minimizes the time the last child arrives, and this time itself (measured in seconds after midnight). Your answer should be accurate to within an absolute or relative error of 10−5.



      Sample Input

      2
      1.5 1.5
      3 0
      
      1
      0 0
      
      4
      1 4
      4 4
      -3 3
      2 4
      
      5
      4 7
      -4 0
      7 -6
      -2 4
      8 -5
      
      0
      


      Sample Output

      1.500000000 1.500000000
      0.000000000 0.000000000
      1.000000000 5.000000000
      3.136363636 7.136363636
      

      Problemsetter: Javier Gómez Serrano

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:2s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10071. Working at the Restaurant

      Problem code: RESTAURN


      Last night, Tom went on a date with a really nice girl. However, he forgot to take his credit card with him and he had no cash in his wallet, so he ended up working at the restaurant to pay for the bill. His task is to take plates from the waiter when he comes from the tables, and pass them along when the diswasher requests them. It is very important for the plates to be washed in the same order as they are brought from the tables, as otherwise it could take too long before a plate is washed, and leftover food might get stuck. Trying to hold all the plates in his hands is probably not a great idea, so Tom puts them on a table as soon as the waiter hands them over to him, and picks them up from the table again when the time comes to pass them along to the dishwasher. There is space for only two piles of plates on the table, which will be referred to as pile 1 and pile 2. There is only one table Tom can use.

      Tom won last year’s SWERC, so he is certainly capable of optimizing for efficiency. You have to output a transcript of one possible way in which Tom might decide to organize the plates on the table during the process, given the sequence of plates and requests he receives.



      Input

      The input has several test cases. Each case begins with a line containing a number N (1 ≤ N ≤ 1 000), followed by N lines, which contain either DROP m or TAKE m, where m > 0 is the number of plates to take or drop. DROP m represents that the next event is the waiter bringing m plates to Tom, one by one, so he has to drop them on the table; TAKE m represents that the next event is Tom taking m plates from the table, one by one, and passing them along in the right order. You can assume that he never receives a TAKE m instruction when there are fewer than m plates on the table, and that the sum M of all values of m corresponding to DROP operations does not exceed 100 000. Note that there might be plates left on Tom’s table when the last request is issued, as Tom might be relieved of his duty to stay until the restaurant closes.

      The input ends with a line with N = 0, which must not be processed.



      Output

      For every test case, the output will be a series of lines describing the operations to be performed with the plates. The content of each line will be one of the following:

      • DROP 1 m (DROP 2 m), m>0, if Tom needs to take a plate from the waiter, drop it on top of pile 1 (pile 2), and repeat this operation m times in total.
      • TAKE 1 m (TAKE 2 m), m>0, if Tom needs to take a plate from the top of pile 1 (pile 2), pass it along to the dishwasher, and repeat m times in total.
      • MOVE 1->2 m (MOVE 2->1 m), m>0, if Tom needs to take a plate from the top of pile 1 (pile 2), drop it on top of pile 2 (pile 1), and repeat m times in total.

      You must output at most 6N lines, and the total number of movements of plates in your transcript (that is, the sum of the m’s printed in your output, for all three kinds of operations), must be at most 6M, as otherwise Tom won’t be able to cope with all the work.

      Note that Tom must obey the commands in the same order as they are issued. This means that, if he receives a TAKE m command, he must perform a certain number of MOVE and TAKE operations such that the sum of the numbers of plates taken adds up exactly to m before performing the operations corresponding to the next command; and if he receives a DROP m command, he must perform a number of DROP or MOVE operations for which the sum of the numbers of plates dropped adds up exactly to m before performing the operations corresponding to the next command.

      Of course, it is also forbidden to take plates from the waiter or pass them along to the dishwasher in the absence of the corresponding order.

      There must be an empty line between the outputs of different cases.

      Any solution satisfying these conditions will be accepted.



      Sample Input

      3
      DROP 100
      TAKE 50
      TAKE 20
      3
      DROP 3
      DROP 5
      TAKE 8
      0
      



      Sample Output

      DROP 2 100
      MOVE 2->1 100
      TAKE 1 50
      TAKE 1 20
      
      DROP 2 3
      DROP 2 5
      MOVE 2->1 8
      TAKE 1 8
      

      Problemsetter: Abel Molina Prieto 

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10072. Lights

      Problem code: LIGHTS2

      John has n light bulbs and a switchboard with n switches; each bulb can be either on or off, and pressing the i−th switch changes the state of bulb i from on to off, and viceversa. He is using them to play a game he has made up. In each move, John selects a (possibly empty) set of switches and presses them, thus inverting the states of the corresponding bulbs. Initially all lights are off, and after exactly m moves John would like to have the first v bulbs on and the rest off; otherwise he loses the game. There is only one restriction: he is not allowed to press the same set of switches in two different moves.

      This is quite an easy game, as there are lots of ways of winning. This has encouraged him to keep playing different winning games, and now he is intent on trying them all. Help him count how many ways of winning there are. Two games are considered the same if, after a reordering of the moves in one of them, at every step the same set of switches is pressed in both of them.

      For example, if n = 4, m = 3, and v = 2, one possible winning game is obtained by pressing switches 1, 2 and 4 in the first move, 1 and 3 in the second one, and 1, 3 and 4 in the last one. This is considered equivalent to, say, first pressing 1 and 3; then 1, 2, 4; and then 1, 3, 4.



      Input

      The input has at most 500 lines, one for each test case. Each line contains three integers n (1 ≤ n ≤ 1 000), m (1 ≤ m ≤ 1 000), and v (0 ≤ vn). The last line of input will hold the values 0 0 0 and must not be processed.



      Output

      Print one line for each test case containing the number of ways John can play the game, modulo the prime 10 567 201.


      Sample Input

      3 3 1
      6 4 0
      6 4 3
      0 0 0
      


      Sample Output

      7
      10416
      9920
      

      Problemsetter: David García Soriano

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10073. Darts

      Problem code: DARTS

      After a long week of work at the ICPC Headquarters, Bill and his friends usually go to a small pub on Friday evenings to have a couple of beers and play darts. All of them are well aware of the fact that their ability at darts decreases at the same rate as the amount of beer left in their mugs.

      They always play 501, one of the easiest games. Players start with a score of N points (typically, N=501, hence the name) and take turns throwing darts. The score of each player decreases by the value of the section hit by the dart, unless the score becomes negative, in which case it remains unchanged. The first player to reach a score of 0 wins. The figure below shows the dartboard with which the game is played.

      Dartboard

      As the clock ticks closer to midnight and they start running out of beer, everyone wonders the same: is it worth trying to aim the dart at a specific section? Or is it better just to throw the dart at a random section on the dartboard? You are asked to deal with the question by finding out what would happen if two players (A and B) applying these two different strategies were to play against each other:

      • Player A throws the darts at random, and consequently they land with equal probability in each of the sections of the dartboard.
      • If Player B aims at a certain section, the dart has the same probability of landing in the correct one as in each of the two adjacent ones (the neighbouring regions to the left and right). Moreover, he is completely aware of his ability and sober enough to aim at the section that maximizes his probability of winning.

      Given the initial score of both players, can you determine the probability that the first player wins? Of course, being the first to throw a dart might be advantageous, so the answer depends on who plays first.



      Input

      The input consists of a series of lines, each containing an integer N (1 ≤ N ≤ 501), the initial score of both players. A case with N = 0 marks the end of the input and must not be processed.



      Output

      For each number in the input, your program should output a line containing two real numbers: the probability that A wins if A throws the first dart, and the probability that B wins if B throws the first dart. Your answers should be accurate to within an absolute or relative error of 10−8.



      Sample Input

      5
      100
      0
      



      Sample Output

      0.136363636364 0.909090909091
      0.072504908290 0.950215081962
      

      Problemsetter: Luis Hernández Corbato 

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10074. Genetics

      Problem code: GENETIC2

      A colony of alien bacteria has recently been discovered close to a crater in New Mexico. Dr. Poucher is in charge of the scientific team at the ICPC BioLab committed to the study of the alien DNA structure. We briefly sketch their discoveries here.

      Alien DNA molecules have the structure of a circular sequence. Each sequence is composed of nucleotides. There are 26 different types of nucleotides, and each of them can occur in two faces. It is very important to remark that in any given alien DNA molecule, every nucleotide either does not appear at all or appears exactly twice (hence, the length of a DNA molecule is an even integer between 2 and 52). In case a nucleotide occurs twice, each occurrence can be of either type independently. Alien bacteria have two types of extremities, which in the technical biological jargon are referred to as arms and legs. A major discovery of Dr. Poucher’s team is a method to determine the exact number of arms and legs of a bacterium by examining its DNA structure.

      Here we represent each nucleotide as a letter of the alphabet. We refer to the different nucleotides as a, A, …z, Z, where the lowercase and uppercase forms of a letter represent the two possible faces a nucleotide may appear with; we shall also use a/A, b/B, …z/Z to refer to a nucleotide in either face.

      To determine the number of extremities, Dr. Poucher starts by initializing two counters of arms and legs to zero, and then proceeds to perform a number of surgeries, transforming a DNA sequence into another one. After each transformation, you may need to increase some of the counters, depending on the type of surgery applied. When the empty sequence of nucleotides (which will be denoted by ∅) has been reached, the number of extremities of the original molecule has been found. The possible surgeries are:

      1. Eliminate consecutive instances of a given nucleotide appearing with opposite faces. The number of arms and legs is preserved. For example: aBbCaCaCaC by eliminating Bb. Another example: DeHhEdeHhE by eliminating dD. Remember that DNA structure is circular, so in our representation as a string the last and first letters are connected.
      2. Eliminate consecutive nucleotides appearing with the same face. Add one to the number of arms. For example: BBcgCgcgCg by eliminating BB. Another example: xabyyaBXxabaBX by eliminating yy.
      3. Eliminate a sequence of four nucleotides formed by two different nucleotides that appear alternately where different occurrences of the same nucleotide have opposite faces. Add one to the number of legs. For example: dcDCefFeefFe, by eliminating dcDC. Another example: cmNMnCcC by eliminating mNMn.
      4. Cut and paste, the most sophisticated procedure. First, a nucleotide is selected, for instance a/A, and the DNA sequence is chopped into two linear chains such that the nucleotide appears once in each of them.

        Second, if both occurrences of a/A are of the same face, one of the chains is “inverted” by reversing the sequence and changing the face of every nucleotide in the chain. Given a chain S, S denotes its “inverted” chain.

        Then, the chains are combined by concatenating the subsequence occurring before a with the subsequence occurring after A, and the subsequence occurring after a with the sub-sequence occurring before A.

        Finally, two new a/A nucleotides are added to close the chain into a circular shape. The face of the new nucleotides are the same if the original pair of nucleotides selected had the same face, and is different otherwise.

        Formally, suppose you select the nucleotide a/A, and further assume for the moment that it appears both times with the face a (A). The cut and paste surgery turns sequences of the form S1aS2S3aS4 (respectively S1AS2S3AS4) into S2aS1S_3aS_4 (respectively S2AS1S_3AS_4). On the other hand, if nucleotide a/A appears with its two different faces, the surgery turns sequences of the form S1aS2S3AS4 into S2aS1S4AS3. S1, S2, S3 and S4 are arbitrary sub-chains (possibly empty). In both cases the original circular chain was chopped into S1(a/A)S2 and S3(a/A)S4.

        For example (see the figure below): starting with the sequence BacDcAbD, we can get chains BacDc and AbD. Then, merging at nucleotide a/A we get the sequence cDca’BbDA’ where a’ and A’ represent the new a/A nucleotides. Here, S1 = B, S2 = cDc, S3 = ∅ and S4 = bD.

        Another example: take the same DNA sequence BacDcAbD, and cut to get the chains DBac and DcAb; paste nucleotide c/C (in this case you need to reverse one chain, for example BaCd) to get the sequence cDBadcBa. Here, S1 = DBa, S2 = ∅, S3 = D and S4 = Ab.


        Figure 1: First example of use of cut&paste

        This surgery does not modify the number of arms or legs, but can be used cleverly in combination with the previous surgeries to reduce the size of the DNA molecule and finish the calculation.

      However, alien bacteria do not present both arms and legs at the same time. This is due to the fact that, in their early development, a leg, in the presence of one or more arms, becomes two arms. Because of the above, the end result is either a number of arms or a number of legs, but not both at the same time. In order to avoid expensive surgical procedures, Dr. Poucher has hired you to write a program that computes the number of arms and legs a bacterium will develop, given its DNA sequence. It is guaranteed that the result is determined uniquely by the original string, regardless of the particular sequence of surgeries applied.



      Input

      Each test case consists of a string of even length between 2 and 52, inclusive, representing the DNA structure of an alien bacterium. All characters are letters. There will be one case per line in the input. The last line contains the word “END” and must not be processed.



      Output

      The output for each test case should have exactly one line, containing the number of arms or legs the bacterium will have, followed by the word “arms” or “legs” respectively (if the number is 1, the words should be in singular). In case there will be neither arms nor legs, the program should print the word “none”.



      Sample Input

      rkrk
      abcdeABCDE
      shcoOCfFHS
      END
      



      Sample Output

      1 arm
      2 legs
      none
      

      Problemsetter: Luis Hernández Corbato

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10075. Haunted Graveyard

      Problem code: GRAVEYRD

      Tonight is Halloween and Scared John and his friends have decided to do something fun to celebrate the occasion: crossing the graveyard. Although Scared John does not find this fun at all, he finally agreed to join them in their adventure. Once at the entrance, the friends have begun to cross the graveyard one by one, and now it is the time for Scared John. He still remembers the tales his grandmother told him when he was a child. She told him that, on Halloween night, “haunted holes” appear in the graveyard. These are not usual holes, but they transport people who fall inside to some point in the graveyard, possibly far away. But the scariest feature of these holes is that they allow one to travel in time as well as in space; i.e., if you fall inside a “haunted hole”, you appear somewhere in the graveyard a certain time before (or after) you entered the hole, in a parallel universe otherwise identical to ours.

      The graveyard is organized as a grid of W × H cells, with the entrance in the cell at position (0,0) and the exit at (W−1,H−1). Despite the darkness, Scared John can always recognize the exit, and he will leave the moment he reaches it, determined never to set foot anywhere in the graveyard again. On his way to the exit, he can walk from one cell to an adjacent one, and he can only head to the North, East, South or West. In each cell there can be either one gravestone, one “haunted hole”, or grass:

      • If the cell contains a gravestone, you cannot walk over it, because gravestones are too high to climb.
      • If the cell contains a “haunted hole” and you reach it, you will appear somewhere in the graveyard at a possibly different moment in time. The time difference depends on the particular “haunted hole” you fell into, and can be positive, negative or zero.
      • Otherwise, the cell has only grass, and you can walk freely over it.

      He is terrified, so he wants to cross the graveyard as quickly as possible. And that is the reason why he has phoned you, a renowned programmer. He wants you to write a program that, given the description of the graveyard, computes the minimum time needed to go from the entrance to the exit. Scared John accepts using “haunted holes” if they permit him to cross the graveyard quicker, but he is frightened to death of the possibility of getting lost and being able to travel back in time indefinitely using the holes, so your program must report these situations.


      Sample graveyard

      The figure illustrates a possible graveyard (the second test case from the sample input). In this case there are two gravestones in cells (2,1) and (3,1), and a “haunted hole” from cell (3,0) to cell (2,2) with a difference in time of 0 seconds. The minimum time to cross the graveyard is 4 seconds, corresponding to the path:

      (0,0) →secEast (1,0) →secEast (2,0) →secEast (3,0) →sechole (2,2) →secEast (3,2)

      If you do not use the “haunted hole”, you need at least 5 seconds.



      Input

      The input consists of several test cases. Each test case begins with a line containing two integers W and H (1 ≤ W, H ≤ 30). These integers represent the width W and height H of the graveyard. The next line contains an integer G (G ≥ 0), the number of gravestones in the graveyard, and is followed by G lines containing the positions of the gravestones. Each position is given by two integers X and Y (0 ≤ X < W and 0 ≤ Y < H).

      The next line contains an integer E (E ≥ 0), the number of “haunted holes”, and is followed by E lines. Each of these contains five integers X1, Y1, X2, Y2, T. (X1,Y1) is the position of the “haunted hole” (0 ≤ X1 < W and 0 ≤ Y1 < H). (X2,Y2) is the destination of the “haunted hole” (0 ≤ X2 < W and 0 ≤ Y2 < H). Note that the origin and the destination of a “haunted hole” can be identical. T (−10 000 ≤ T ≤ 10 000) is the difference in seconds between the moment somebody enters the “haunted hole” and the moment he appears in the destination position; a positive number indicates that he reaches the destination after entering the hole. You can safely assume that there are no two “haunted holes” with the same origin, and the destination cell of a “haunted hole” does not contain a gravestone. Furthermore, there are neither gravestones nor “haunted holes” at positions (0,0) and (W-1,H-1).

      The input will finish with a line containing 0 0, which should not be processed.



      Output

      For each test case, if it is possible for Scared John to travel back in time indefinitely, output Never. Otherwise, print the minimum time in seconds that it takes him to cross the graveyard from the entrance to the exit if it is reachable, and Impossible if not.



      Sample Input

      3 3
      2
      2 1
      1 2
      0
      4 3
      2
      2 1
      3 1
      1
      3 0 2 2 0
      4 2
      0
      1
      2 0 1 0 -3
      0 0
      



      Sample Output

      Impossible
      4
      Never
      

      Problemsetter: Enrique Martín Martín

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10076. Slalom

      Problem code: SLALOM2

      In spite of the scarcity of snowfall in Madrid, interest in winter sports is growing in the city, especially with regard to skiing. Many people spend several weekends or even full weeks improving their skills in the mountains.

      In this problem we deal with only one of the multiple alpine skiing disciplines: slalom. A course is constructed by laying out a series of gates, which are formed by two poles. The skier must pass between the two poles forming each gate. The winner is the skier who takes the least time to complete the course while not missing any of the gates.

      You have recently started to learn to ski, but you have already set yourself the goal of taking part in the Winter Olympic Games of 2018, for which Madrid will presumably present a candidature. As part of the theoretical training, you need to write a program that calculates, given a starting point and a series of gates, the minimum-length path starting from the point given and passing through each gate until you reach the last one, which is the finish line. You may assume that the gates are horizontal and are ordered from highest to lowest, so that you need to pass through them in order. You consider yourself an accomplished skier, so you can make any series of turns, no matter how difficult, and your only concern is minimizing the total length of the path.



      Input

      The first line of each case gives the number of gates n (1 ≤ n ≤ 1 000). The next line contains two floating point numbers, the Cartesian coordinates x and y of the starting position, in that order. Next come n lines with three floating point numbers each, y x1 x2, meaning that the next gate is a horizontal line from (x1, y) to (x2, y). You can safely assume that x1 < x2. The values of y are strictly decreasing and are always smaller than that of the starting position. The last gate represents the finish line. All coordinates are between −500 000 and 500 000, inclusive. A value of 0 for n means the end of the input. A blank line follows each case.



      Output

      For each test case, output a line with the minimum distance needed to reach the finish line. Your answer should be accurate to within an absolute or relative error of 10−7.



      Sample Input

      2
      0 2
      1 1 2
      0 0.5 3
      
      3
      0 4
      3 1 2
      2 -1 0
      1 1 2
      
      0
      



      Sample Output

      2.41421356237
      4.24264068712
      

      Problemsetter: Manuel Abellanas

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10077. Routing

      Problem code: ROUTING

      You work as an engineer for the Inane Collaboration for Performance Computing, where you are in charge of designing an intercommunication network for their computers. The network is arranged as a rectangular array of 2n−1 rows, each having 2n − 1 switches. A switch is a device with two input wires, X and Y, and two output wires, X′ and Y′. If the switch is off, data from input X will be relayed to output X′, and data from Y to Y′. If it is on, X will be connected to Y′ and Y to X′. Additionally, there are 2n computers in the topmost and bottommost rows, and messages need to be sent between pairs of them. Notice that data from two different sources cannot share a wire but, of course, both pieces of data can be routed through the same switch on different inputs.

      You have come to the conclusion that the network that best suits your purposes has the Beneš topology. A 1-Beneš network is just a switch. For n > 1, a n-Beneš network can be constructed recursively as follows:

      • In the first (top) row there are 2n − 1 switches such that switch j (0 ≤ j < 2n−1) has data inputs from computers 2j and 2j + 1 (we label the computers in the topmost and bottommost rows with integers between 0 and 2n − 1, inclusive, from left to right).
      • Then a perfect shuffle permutation is applied to the output wires between the first and the second rows of switches, meaning that output number j in a row is connected to input number j′ in the next row, where j′ is obtained by rotating the n-bit pattern representing j in binary one bit to the right (again, inputs and outputs are numbered from left to right).
      • If n > 2, the next rows of switches, up to (and including) the last-but-one, form two (n−1)-Beneš subnetworks, one on the left side and the other on the right side.
      • Finally, the inverse shuffle permutation is applied to the outputs and a last row of switches is added.

         
      3-Benes network

      For example, the figure on the left shows the Beneš network for n=3 ( squares represent switches; computers in the top and bottom rows are not drawn, but assigned with integers from 0 to 7). The figure on the right shows a possible state of the switches; squares where two of the lines cross are switches that have been turned on. You may verify that this state allows us to simultaneously establish communication paths from computers 0, 1, 2, 3, 4, 5, 6, 7 at the bottom to 3, 7, 4, 0, 2, 6, 1, 5 at the top, respectively.

      You are given a set of pairs (a, b) of computers to connect simultaneously (where a is a computer in the bottom row and b a computer in the top row) by means of wire-disjoint paths, and you are to find how to select the state of all switches so that this can be accomplished.



      Input

      The first line of each test case is an integer n (1 ≤ n ≤ 13), meaning that you have 2n pairs of computers to connect, as described above. A line with n = 0 marks the end of the input and should not be processed.

      Each line with n > 0 will be followed by another line containing 2n integers. The i-th integer (0 ≤ i < 2n) will be the computer in the topmost row that the i-th computer in the bottommost row needs to communicate with.



      Output

      The output for each case should have 2n−1 lines, each containing a binary string of length 2n−1 indicating, for each switch, whether it must be turned on (1) or off (0).

      The input given will always have at least one solution. In case of several solutions, return the lexicographically smallest one. That is, the string in the top row must be lexicographically smallest; in case of a tie, the string in the second row must be lexicographically smallest, and so on.

      Outputs for different test cases should be separated by a blank line.



      Sample Input

      2
      3 2 1 0
      3
      3 7 4 0 2 6 1 5
      0
      



      Sample Output

      00
      11
      11
      
      0011
      0000
      0110
      1111
      1101
      

      Problemsetter: David García Soriano

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10078. Happy Telephones

      Problem code: HAPPYTL

      In the land of Eden, all phone conversations are happy ones. People complaining on the phone are immediately put in jail. To enforce this law, the police taps all phone conversations.

      The police wants to hire the appopiate number of operators to listen to all conversations in a given period of time. Unfortunately, each of their operators can listen to one conversation only before needing a really long break to rest from the effort.

      As a contractor of the police department, you have been asked to provide a program capable of determining the required number of operators. If the program does not work correctly, you will be put in jail as well, along with all the unhappy complainers. Do you really want to end up there?

      Input

      Each test case starts with two integers denoting the number of phone calls N (1 ≤ N < 10 000) and the number of intervals M (1 ≤ M < 100). This is followed by N lines describing the telephone calls, each one consisting of four integers Source, Destination, Start and Duration. Source and Destination identify the pair of telephone numbers establishing the connection (0 ≤ Source, Destination ≤ 10 000 000). Start and Duration are the start time and duration of the call in seconds (1 ≤ Duration ≤ 10 000 and Start ≥ 0). You can safely assume that the sum of Start and Duration fits into a 32-bit signed integer.

      Afterwards follow M lines containing the time intervals the police are interested in, each described by two integers Start and Duration, in the same format and with the same meaning and constraints as those in the telephone calls. The last test case is represented by N = M = 0 and must not be processed.



      Output

      For each of the M intervals of each test case, print the number of calls that are active during at least one second of the interval.



      Sample Input

      3 2
      3 4 2 5
      1 2 0 10
      6 5 5 8
      0 6
      8 2
      1 2
      8 9 0 10
      9 1
      10 1
      0 0
      



      Sample Output

      3
      2
      1
      0
      

      Problemsetter: Manuel Freire 

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10079. Stammering Aliens

      Problem code: STAMMER

      Dr. Ellie Arroway has established contact with an extraterrestrial civilization. However, all efforts to decode their messages have failed so far because, as luck would have it, they have stumbled upon a race of stuttering aliens! Her team has found out that, in every long enough message, the most important words appear repeated a certain number of times as a sequence of consecutive characters, even in the middle of other words. Furthermore, sometimes they use contractions in an obscure manner. For example, if they need to say bab twice, they might just send the message babab, which has been abbreviated because the second b of the first word can be reused as the first b of the second one.

      Thus, the message contains possibly overlapping repetitions of the same words over and over again. As a result, Ellie turns to you, S.R. Hadden, for help in identifying the gist of the message.

      Given an integer m, and a string s, representing the message, your task is to find the longest substring of s that appears at least m times. For example, in the message baaaababababbababbab, the length-5 word babab is contained 3 times, namely at positions 5, 7 and 12 (where indices start at zero). No substring appearing 3 or more times is longer (see the first example from the sample input). On the other hand, no substring appears 11 times or more (see example 2).

      In case there are several solutions, the substring with the rightmost occurrence is preferred (see example 3).



      Input

      The input contains several test cases. Each test case consists of a line with an integer m (m ≥ 1), the minimum number of repetitions, followed by a line containing a string s of length between m and 40 000, inclusive. All characters in s are lowercase characters from “a” to “z”. The last test case is denoted by m = 0 and must not be processed.



      Output

      Print one line of output for each test case. If there is no solution, output none; otherwise, print two integers in a line, separated by a space. The first integer denotes the maximum length of a substring appearing at least m times; the second integer gives the rightmost possible starting position of such a substring.



      Sample Input

      3
      baaaababababbababbab
      11
      baaaababababbababbab
      3
      cccccc
      0
      



      Sample Output

      5 12
      none
      4 2
      

      Problemsetter: David García Soriano

      Added by:David García Soriano
      Date:2011-11-23
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Soutwestern Europe Regional, SWERC 2009









      SPOJ Problem Set (classical)

      10080. Lawn Mower

      Problem code: LAWNMWR

      The International Collegiate Soccer Competition (ICSC) is famous for its well-kept rectangular stadiums. The grass playing fields in ICSC stadiums are always 100 meters long, and 75 meters wide. The grass is mowed every week with special lawn mowers, always using the same strategy: first, they make a series of passes along the length of the field, and then they do the same along the width of the field. All passes are straight lines, parallel to the sides of the field.



      The ICSC has hired a new lawn-mower, Guido. Guido is very chaotic, and instead of covering the field incrementally, he likes to choose random starting positions for each of his passes. But he is afraid of not doing a good job and being fired by the ICSC, so he has asked you to help him. Write a program to make sure that the grass in the field is perfectly cut: all parts of the field have to be mowed at least once when the mower goes from end to end, and again when the mower goes from side to side.



      Input

      Each test case contains 3 lines. The first line contains two integers, nx (0 < nx < 1 000) and ny (0 < nx < 1 000), and a real number w (0 < w ≤ 50), which represents the width of the cut of that particular lawn mower. The next line describes the end-to-end passes (along the length of the field), and contains nx real numbers xi (0 ≤ xi ≤ 75) describing the starting positions of the mower’s center in Guido’s end-to-end passes. The last line describes the side-to-side passes, with ny real numbers yi (0 ≤ yi ≤ 100).

      The end of the test cases is signalled with a line that contains the numbers 0 0 0.0. You should generate no output for this line, as it is not a test case.

      Real numbers for w, xi and yi can have up to 7 digits after the decimal point, and any cut will also include its boundaries. For example, if a 2.0-meter wide cut is performed along the 10.0-meter mark, then a strip of grass from 9.0 to 11.0 (including both) will be considered “cut”.



      Output

      Print YES if Guido has done a good job, or NO if some part of the field has not been mowed at least once when the mower was travelling along the length of the field, and again when it was travelling along the width.



      Sample Input

      8 11 10.0
      0.0 10.0 20.0 30.0 40.0 50.0 60.0 70.0
      0.0 10.0 20.0 30.0 40.0 50.0 60.0 70.0 80.0 90.0 100.0
      8 10 10.0
      0.0 10.0 20.0 30.0 40.0 50.0 60.0 70.0
      0.0 10.0 30.0 40.0 50.0 60.0 70.0 80.0 90.0 100.0
      4 5 20.0
      70.0 10.0 30.0 50.0
      30.0 10.0 90.0 50.0 70.0
      4 5 20.0
      60.0 10.0 30.0 50.0
      30.0 10.0 90.0 50.0 70.0
      0 0 0.0
      



      Sample Output

      YES
      NO
      YES
      NO
      

      The ICSC is sponsored by the Association for Sports Machinery (ASM), which started out in the US, so they prefer to use the term ‘soccer’ instead of ‘football’.

      Problemsetter: Manuel Freire

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10081. Periodic Points

      Problem code: PERIODIC

      Computing the number of fixed points and, more generally, the number of periodic orbits within a dynamical system is a question attracting interest from different fields of research. However, dynamics may turn out to be very complicated to describe, even in seemingly simple models. In this task you will be asked to compute the number of periodic points of period n of a piecewise linear map f mapping the real interval [0,m] into itself. That is to say, given a map f : [0, m] → [0, m] you have to calculate the number of solutions to the equation fn(x) = x for x ∈ [0, m], where fn is the result of iterating function f a total of n times, i.e.

      fn = 
      n fs

      
      f ∘ .. ∘ f ∘ f
       
       
      ,

      where ∘ stands for the composition of maps, (gh) (x) = g(h(x)).

      Fortunately, the maps you will have to work with satisfy some particular properties:

      • m will be a positive integer and the image of every integer in [0,m] under f is again an integer in [0,m], that is, for every k ∈ {0, 1, … , m} we have that f(k) ∈ {0, 1, … , m}.
      • For every k ∈ {0, 1, …, m − 1}, the map f is linear in the interval [k, k + 1]. This means that for every x ∈ [k, k + 1], its image satisfies f(x) = (k + 1 − x)f(k) + (xk)f(k + 1), which is equivalent to its graph on [k,k + 1] being a straight line segment.

          
      Figure 1: Graphs of the third map in the sample input, f3 (left), and of its square, f32 (right).

      Since there might be many periodic points you will have to output the result modulo an integer.



      Input

      The input consists of several test cases, separated by single blank lines. Each test case begins with a line containing the integer m (1 ≤ m ≤ 80). The following line describes the map f; it contains the m + 1 integers f(0), f(1), …, f(m), each of them between 0 and m inclusive. The test case ends with a line containing two integers separated by a blank space, n (1 ≤ n ≤ 5 000) and the modulus used to compute the result, mod (2 ≤ mod ≤ 10 000).

      The input will finish with a line containing 0.



      Output

      For each case, your program should output the number of solutions to the equation fn(x) = x in the interval [0, m] modulo mod. If there are infinitely many solutions, print Infinity instead.



      Sample Input

      2
      2 0 2
      2 10
      
      3
      0 1 3 2
      1 137
      
      3
      2 3 0 3
      20 10000
      
      0
      



      Sample Output

      4
      Infinity
      9074
      

      Problemsetter: Luis Hernández Corbato

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:17s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10082. Comparing Answers

      Problem code: CMPANS

      In a place in Southwestern Europe, the name of which I do not wish to recall, not long ago there were n cities connected by unidirectional roads, with possibly more than one road connecting a city to another one, or even to itself. As a homework assignment for your geography class, you need to calculate the number of paths of length exactly two that were between each pair of cities. However, you’ve been too busy celebrating the Spanish victory in the World Cup, so now you are copying the answers from your friend. You would like to make sure his answers are correct before handing in your homework.



      Input

      The input consists of several test cases, separated by single blank lines. Each test case begins with a line containing the integer n (1 ≤ n ≤ 700). The following n lines contain n elements each, with element j of line i being the number of roads from city i to city j (a number between 0 and 10, inclusive). After that, there will be n lines. Each will contain n elements, with element j of line i being the answer from your friend for the number of length-2 paths from city i to city j; it will be an integer between 0 and 100 000 inclusive.

      The test cases will finish with a line containing only the number zero (also preceded by a blank line).

      Note: Large input file; use fast I/O routines (e.g. scanf in C++ or BufferedReader in Java).



      Output

      For each case, your program should output a line. The content of this line should be YES if your classmate’s solution to the assignment is right, and NO otherwise.



      Sample Input

      3
      2 0 1
      1 0 3
      1 1 0
      5 1 2
      5 3 1
      3 0 4
      
      3
      2 0 1
      1 0 3
      1 1 0
      5 1 2
      5 3 2
      3 0 4
      
      0
      



      Sample Output

      YES
      NO
      

      Problemsetter: Abel Molina Prieto

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:7s-9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10084. Fake Scoreboard

      Problem code: FAKESCOR

      As you know, after the award ceremony of SWERC it is customary to publish a complete scoreboard with detailed information on the submissions and verdicts received. However, due to the buggy contest management system, most of the relevant data are not being recorded today. Clearly such state of affairs fails to meet the high standards we are committed to, so the judges have resolved to make up the rest of the data based on whatever shred of information left, and hope contestants are unable to tell the difference. To make our lives even simpler, we kindly ask you to provide a solution for us, or else today’s scoreboard will remain forever veiled in mystery (even the fake one).

      What we will know by the end of the contest is the number T of teams, the number P of problems, and the number of accepted submissions by each team. From the number and colour of balloons floating around on the premises we will also be able to infer how many teams solved each of the problems. Your task is to figure out which teams solved which problems.

      Our counting skills are not up to par, so your program should be able to detect when the data we collected must be wrong (see sample input 1). Otherwise you should output a possible solution, represented as a sequence of T strings of P characters each, in the following way. Both problems and teams are assigned with distinct integers, from 1 to P and 1 to T, respectively. For team number i (1 ≤ iT), write the string on alphabet N,Y such that its j-th (1 ≤ jP) character is Y if the team managed to get problem j accepted, and N otherwise. For example, the following three strings form a solution to the second sample case, where the score of each of three teams is 2,1,2, and the count of accepted submissions for each of three problems is 1,2,2:

      NYY
      NNY
      YYN

      There is at least one other solution, namely

      NYY
      NYN
      YNY

      When several solutions are possible we ask you to supply the one giving rise to the lexicographically smallest string, when each of the T rows are concatenated in order. In the example above we prefer the first solution, since NYYNNYYYN comes before NYYNYNYNY in lexicographical order. (String S comes before S′ in lexicographical order if the first different character between the two is N in S but Y in S′).



      Input

      Each input case is described by three lines:

      The first contains two space-separated integers T (the number of teams) and P (the number of problems), with 1 ≤ T, P ≤ 80. The second contains T space-separated integers between 0 and 90 (inclusive), the i-th of which indicates the number of problems solved by team i. The third (and last) line has P integers between 0 and 90, the j-th of which describes the number of teams successfully solving problem j.

      Different input cases are separated by a blank line. The last line of the input file will be 0 0.



      Output

      If the input data has a solution, print T lines of P characters each, depicting the lexicographically smallest solution as explained above. Otherwise output a single line with the word Impossible. In any case a blank line should separate outputs for different test cases.



      Sample Input

      2 2
      1 2
      1 1
      
      3 3
      2 1 2
      1 2 2
      
      3 5
      3 3 1
      3 1 1 0 2
      
      0 0
      



      Sample Output

      Impossible
      
      NYY
      NNY
      YYN
      
      YNYNY
      YYNNY
      YNNNN
      

      Problemsetter: David García Soriano

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:50s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10085. Palindromic DNA

      Problem code: PALINDNA

      A DNA sequence is composed of a series of four possible nucleobases, namely Adenine, Guanine, Thymine and Cytosine; we will refer to each of these bases by their initial. For our purposes, nucleobases have an associated cyclic “order”: A is followed by G, which in turn is followed by T, which is followed by C, which is followed by A again. State-of-the-art research in genomics has revealed the startling fact that many diseases are caused by certain subsequences of bases not forming a palindromic sequence! Your mission as a leading researcher at ICPC laboratories is to take a DNA string S and a series of subsets P1, …, Pt of indices to characters (nucleobases) in S, and transform S so that each of the restrictions of the resulting string to P1, …, Pt are palindromic. (The restriction of S to a subset P={i1, i2, …, ik} of indices, where 0 ≤ i1 < i2 < … < ik < |S|, is the string Si1 Si2Sik). It is possible to inspect any base of S at will, but only three transformations can be applied to a base:

      1. Leave it unaltered.
      2. Increase it by 1 in the cyclic order of nucleobases (e.g. turn C into A).
      3. Decrease it by 1 (e.g. turn T into G).

      Moreover, owing to limitations of current technology, it is impossible to modify two bases in consecutive positions of the sequence. Is our goal achievable?

      By way of example, consider DNA sequence AGTAT. Number positions starting from 0, and suppose we have the three subsets P1 = {1, 4}, P2 = {0, 1} and P3 = {0, 2, 4}. One solution is to increase the first character and decrease the last, yielding S′ = GGTAG. The restrictions of S′ to P1, P2 and P3 are GG, GG and GTG, respectively; all of them are palindromic.

      One case where no solution is possible is when the string is CATGC, and we require the subsequences determined by positions {0,3} and {3,4} be palindromic. Here, characters 3, 0 and 4 would all need to become a T. But this entails modifying consecutive characters 3 and 4, which is not allowed.



      Input

      The first line of each test case has two integers N and T (1 ≤ N ≤ 10 000, 1 ≤ T ≤ 6 000), the sequence length and number of subsets to consider. The next line contains the DNA sequence of length N, all of whose characters are in ACGT. The subsets are described by the following T lines. Each line starts by “L:”, where L (0 ≤ LN) is the number of positions in the subset, and is followed by T distinct integers between 0 and N − 1 in increasing order. Subsets may overlap partially or totally.

      A blank line separates different test cases. The input file is terminated by a line containing 0 0.



      Output

      In a single line per test case, print YES if the task is solvable and NO otherwise.



      Sample Input

      5 3
      AGTAT
      2: 1 4
      2: 0 1
      3: 0 2 4
      
      5 3
      CATGC
      0:
      2: 0 3
      2: 3 4
      
      0 0
      



      Sample Output

      YES
      NO
      

      Problemsetter: David García Soriano

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:3s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10086. Jumping Monkey

      Problem code: JMPMNKEY

      You are a hunter chasing a monkey in the forest, trying to shoot it down with your all-powerful automatic machine gun. The monkey is hiding somewhere behind the branches of one of the trees, out of your sight. You can aim at one of the trees and shoot; your bullets are capable of going through the branches and killing the monkey instantly if it happens to be in that tree. If it isn’t, the monkey takes advantage of the time it takes you to reload and takes a leap into a neighbouring tree without you noticing. It never stays in the same place after a shot. You would like to find out whether there is an strategy that allows you to capture the monkey for sure, irrespective of its initial location and subsequent jumps. If so, you need to determine the shortest sequence of shots guaranteeing this.


       

      As an example, consider the situation in which there are only two neighboring trees in the forest (left hand side of the figure). It is then possible to make sure you capture the monkey by shooting twice at the same tree. Your first shot succeeds if the monkey happened to be there in the first place. Otherwise, the monkey was behind the other tree and it will necessarily have moved when you shoot for the second time.

      However, depending on the shape of the forest it may not be possible for you to ensure victory. One example of this is if there are three trees, all connected to one another (right hand side of the figure). No matter where you aim at, there are always two possible locations for the monkey at any given moment. (Note that here we are concerned with the worst-case scenario where the monkey may consistently guess your next target tree).



      Input

      The input consists of several test cases, separated by single blank lines. Each test case begins with a line containing two integers n and m (1 ≤ n ≤ 21); n is the number of trees in the forest, and m is the number of adjacency relations between trees. Each of the following m lines contains two distinct integers between 0 and n−1 (inclusive), the identifiers of the trees in an adjacent pair. The order of both trees within a pair carries no meaning, and no pair appears more than once. You may further assume that no tree is adjacent to itself, and there is always a path between any two trees in the forest.

      The test cases will finish with a line containing only two zeros (also preceded with a blank line).



      Output

      Print a line for each test case. The line should contain the single word Impossible if the task is impossible. Otherwise, it must contain the shortest sequence of shots with the required property, in the format L: V1 V2VL, where L is the length of the sequence, and V1, V2, …, VL are space-separated integers containing the identifiers of the trees to shoot at in the right order. If several shortest sequences exist, print the lexicographically smallest one. (A sequence is smaller than another in lexicographic order if the first element on which they differ is smaller in the first one).



      Sample Input

      2 1
      0 1
      
      3 3
      0 1
      1 2
      2 0
      
      4 3
      0 1
      2 3
      1 3
      
      0 0
      


      Sample Output

      2: 0 0
      Impossible
      4: 1 3 3 1
      

      Problemsetter: Marçal Garolera Huguet

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10087. Sensor Network

      Problem code: SENSORNT

      In response to a request by the SWERC 2010 problem-setting team, a sensor network has just been installed in the headquarters. The organizing committee has put in the problem-setters the disproportionate fear of suffering a leak of classified information about the problems.

      Nevertheless, in the rush they forgot to think about the electricity network needed to make the sensors work. Because of this, the security system is currently not working, but we need to justify the great amount of resources invested in it, so the installation must be ready before the end of the contest. Hence you are now asked to elaborate a program which will help the electrician in his duty.

      Since the organizing committee spared no expense, they ordered the sensors from a prestigious company. Every sensor is handcrafted and a number is written on each of them, whose meaning is the recommended voltage that should be applied to it for correct operation. They can be used under higher voltages, with an increasing risk of failure, but never with a voltage below the recommended one. The electrician gazed open-mouthed at the sensors when they were given to him: nearly all of them had different recommended voltages! The sensors were installed in the building in such a way that each of them controls exactly two doors and every door is controlled by at least one sensor. Now is the time for the electrician to supply power to the sensors. He faces the following constraints:

      • Fortunately, there is no need to activate all sensors. However, we will require that the subset of sensors chosen to be on satisfy that every door is controlled by, at least, one sensor in the subset.
      • Electricity is to be supplied to one of the active sensors, and then distributed to the others with wires. In order not to waste wires, they can only be installed by connecting a pair of neighboring active sensors (by “neighbouring” we mean that some door is controlled by both of them). Since we must supply energy to every active sensor, not every subset of sensors is suitable as the chosen subset of working sensors.
      • Because of the above, all of the sensors will be supplied the same voltage, which cannot be below the corresponding recommended voltages.

      For simplicity, we will refer to a subset of sensors satisfying the first two constraints above as an admissible subset. The network is designed so that the set of all sensors is always admissible, but we would like to take a possibly smaller subset so as to minimize the margin, defined as the maximum of the differences, in absolute value, between the numbers written on each pair of sensors in the subset. (This is to keep the chances of failure to a minimum).

      The electrician could not solve the task of finding the admissible subset of the set of sensors for which the margin is minimum. Therefore, the electrical installation is still missing. Today, we ask you to write a program to find out the answer, given a sensor network and the recommended voltage for each of the sensors.



      Input

      The input consists of several test cases, separated by single blank lines. Each test case begins with a line containing the integer n (2 ≤ n ≤ 350), the number of doors in the building. The following line contains another integer, m (n − 1 ≤ mn (n − 1) / 2), the number of sensors in the network. The test case finishes with m lines containing a description of each of the m sensors. The i-th of those lines contains three integers, a (0 ≤ an − 1), b (0 ≤ bn − 1) and w (1 ≤ w ≤ 215), in that order. Integers a and b represent the pair of doors controlled by the i-th sensor, and w its recommended voltage. You can safely assume that there are no two sensors controlling the same two doors.

      The input will finish with a line containing 0.



      Output

      For each case, your program should output a line containing the minimum margin of an admissible subset of the sensors.



      Sample Input

      3
      3
      0 1 220
      1 2 120
      2 0 160
      
      4
      5
      2 3 80
      1 3 80
      0 1 180
      2 1 200
      3 0 140
      
      0
      



      Sample Output

      40
      60
      

      Problemsetter: Luis Hernández Corbato

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:75s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10088. Assembly Line

      Problem code: ASSEMBLY

      The last worker in a production line at the factory of Automated Composed Machinery is worried. She knows that her job hangs in the balance unless her productivity increases. Her work consists of assembling a set of pieces in a given sequence, but the time spent on assembling pieces a and b and then c may not the same as that on assembling pieces b and c, and then assembling a with the resulting component. Only two consecutive pieces may be assembled at a time, and once they are assembled they behave as another piece in terms of the time needed for further assembly.

      In order to aid her, you need to find the optimal way to assemble all components. The input to your program will be a set of symbols representing (types of) pieces, and a so-called assembly table representing the time it takes to assemble them, as well as the type of the resulting component. For instance, we may have two symbols {a,b}, and the following table:

        a b
      a 3-b 5-b
      b 6-a 2-b

      This means, for example, that two pieces of type a and a may be assembled in 3 minutes, and the result is a component of type b, in that the time required to assemble it again with another piece of, say, type a is 6 minutes, and so on. Note that the table is not symmetric, i.e. assembling b and a may be more time-consuming than a and b.

      For a sequence of components labelled aba, the two possible solutions are:

      • (ab)a = ba = a with time time(ab) + time(ba) = 5+6 = 11.
      • a(ba) = aa = b with time time(ba) + time(aa) = 6+3 = 9.

      So the result for this case would be a piece of type b in 9 minutes (denoted 9-b).



      Input

      The input consists of several test cases. Each test case begins with a line containing a natural number k (1 ≤ k ≤ 26), followed by a line with k symbols (characters in [a-z]) separated by spaces. The following k lines contain the assembly table: the i-th line has k pairs of the form time-result, where time is an integer between 0 and 1 000 000 inclusive, and result a symbol belonging to the preceding set. The j-th pair in the i-th line represents the time to compose pieces of types represented by the i-th and j-th symbols, along with the type of the resulting piece. After the table, a line with an integer n indicates the number of lines that follow, each line being a string of at most 200 symbols. Each of these lines is a sequence of components that need to be assembled together in the right order.

      The input will finish with a line containing 0, which should not be processed.



      Output

      For each test case, print n lines, each with an integer time and a symbol result in the format time-result. Each line represents the minimum time and the type of the resulting piece for the corresponding case in the input. In case of a tie among several possible results with the same minimum time, choose from among those the piece whose type letter appears first in the line that contained the k symbols at the beginning of the test case. (For example, if that line was a  c  b and both c and b can be obtained with minimum cost 5, print 5-c).

      There must be an empty line between the output of different test cases.

      Sample Input

      2
      a b
      3-b 5-b
      6-a 2-b
      2
      aba
      bba
      2
      m e
      5-e 4-m
      3-e 4-m
      1
      eme
      0
      



      Sample Output

      9-b
      8-a
      
      7-m
      

      Problemsetter: Enrique Martín Martín

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:100s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10089. Locks and Keys

      Problem code: LOCKKEY

      A wizard is in a labyrinth where there are V rooms and V−1 doors connecting some pairs of rooms in both directions, in such a way that there is always a sequence of doors one can traverse to go from a room to any other room. Additionally, there are C locks and C keys of C different colours (one of each) in some of the doors and rooms of the maze, respectively; each door has at most one lock, and there is at most one key placed in each room. It should be an easy matter for the wizard to bypass the lock system, were it not for the fact that he forgot his spell book, without which his wizardry is utterly useless. The wizard is currently in room X, and he wants to get his spell book, located in room Y, without taking too long. At every step he may go to an adjacent room through one of the doors. Of course, if the door is locked, he needs to be carrying the key of the same colour as the lock (unless, of course, that door has already been unlocked). The wizard can carry only one key at a time and after picking up a key it is not possible for him to drop it somewhere in the maze in order to take it again afterwards. Once a door has been unlocked, the key is thrown away since it is no longer any use.

      Given the maze and the positions of the C keys and C locks, determine how to reach Y from X, if possible. Any path whose length does not exceed 4 · (C + 1) · V is acceptable.



      Input

      The first line of each case contains four integers: the number V of rooms in the maze (1 ≤ V ≤ 1 500), the number C of locks (0 ≤ C < V), and rooms X and Y numbered 0,1,…,V−1. Then comes a (possibly empty) line with C integers indicating the location of each of the keys, in order of increasing colour. The next V − 1 lines describe the maze: each contains three integers A B L, meaning that there is a door between rooms A and B which can be unlocked with the key of colour L, if 0 ≤ L < C; a value of −1 for L indicates that no lock is needed.

      The last line has V, C, X, Y = 0, 0, 0, 0.



      Output

      There is one line of output per test case. If there is no solution, output Impossible. Otherwise print the full path corresponding to your solution in the format LV0VL, where L ≤ 4 (C + 1) V is the length of a path from X to Y, and X = V0, V1, …, VL−1, VL = Y is the sequence of L + 1 vertices visited in the right order. A single space must precede each vertex in the path; see sample output for clarification.



      Sample Input

      1 0 0 0
      
      
      3 1 0 2
      1
      0 1 -1
      0 2 0
      
      3 2 0 2
      1 2
      0 1 1
      0 2 0
      
      5 3 0 4
      2 0 3
      0 1 0
      0 2 -1
      1 3 1
      2 4 2
      
      0 0 0 0
      



      Sample Output

      0: 0
      3: 0 1 0 2
      Impossible
      10: 0 2 0 1 0 1 3 1 0 2 4
      

      Problemsetter: Javier Gómez Serrano

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:16s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Soutwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10091. Three-sided Dice

      Problem code: DICE

       

      Just like every fall, the organizers of the Southwestern Europe Dice Simulation Contest are busy again this year. In this edition you have to simulate a 3-sided die that outputs each of three possible outcomes (which will be denoted by 1, 2 and 3) with a given probability, using three dice in a given set. The simulation is performed this way: you choose one of the given dice at random, roll it, and report its outcome. You are free to choose the probabilities of rolling each of the given dice, as long as each probability is strictly greater than zero. Before distributing the materials to the contestants, the organizers have to verify that it is actually possible to solve this task.

      For example, in the first test case of the sample input you have to simulate a die that yields outcome 1, 2 and 3 with probabilities 3/10, 4/10 and 3/10. We give you three dice, and in this case the i-th of them always yields outcome i, for each i = 1, 2, 3. Then it is possible to simulate the given die in the following fashion: roll the first die with probability 3/10, the second one with probability 4/10 and the last one with probability 3/10.



      Input

      The input consists of several test cases, separated by single blank lines. Each test case consists of four lines: the first three of them describe the three dice you are given and the last one describes the die you have to simulate. Each of the four lines contains 3 space-separated integers between 0 and 10 000 inclusive. These numbers will add up to 10 000, and represent 10 000 times the probability that rolling the die described in that line yields outcome 1, 2 and 3, respectively.

      The test cases will finish with a line containing only the number zero repeated three times (also preceded with a blank line).



      Output

      For each case, your program should output a line with the word YES if it is feasible to produce the desired die from the given ones, and NO otherwise.



      Sample Input

      0 0 10000
      0 10000 0
      10000 0 0
      3000 4000 3000
      
      0 0 10000
      0 10000 0
      3000 4000 3000
      10000 0 0
      
      0 0 0
      



      Sample Output

      YES
      NO
      

      Problemsetter: Abel Molina Prieto

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2010









      SPOJ Problem Set (classical)

      10092. Party Night

      Problem code: PRTYNGHT

      Today is the town’s celebration day, on which tradition dictates that all townspeople go partying. Each of them should attend a party at one of the pubs, and dance and drink to the point of intoxication. Later on, once all the parties have come to an end, after-parties start being thrown at other pubs, and every villager then goes to one. In order for the villagers to make as many acquaintances as possible, no two of them attend the same two parties.

      Needless to say, such practice causes everyone to have a severe blackout regarding the events of the night, but people are still curious to know what happened. Unfortunately, all they seem to be able to remember is who coincided with them at some point, but they have serious trouble identifying when or where. And as their memory of even this piece of information may be shaky (to say the least), they need help in figuring out whether all their recollections are consistent or if, on the contrary, some of the townspeople must have made a mistake (either by failing to remember someone else who was there, or by incorrectly thinking they met someone they didn’t). Can you help them?

      For example, in a town of 4 people, if we are told that villagers 0, 1 and 2 all met one another, and villagers 2 and 3 met as well, the data is consistent because there might have been parties P0 and P1, and after-parties A0, A1 and A2, such that person 0 went to P0 and A0, person 1 to P0 and A1, person 2 to P0 and A2, and person 3 to P1 and A2; this arrangement satisfies all required conditions. However, if persons 0 and 3 claimed to have met too, the data would become inconsistent.



      Input

      The input file will contain several test cases. Each of them begins with a line containing two integers: 1 ≤ n ≤ 100, the number of villagers; and 0 ≤ m ≤ 1000. m lines follow, each containing a pair of integers i and j, 0 ≤ i, j < n, ij, meaning that persons numbered i and j remember having been together in a pub. No pair of people will appear twice.

      Different test cases will be separated by a blank line. A line with n = m = 0 signals the end of the input.



      Output

      For each test case, print “YES” if there is a configuration of parties, after-parties, and villagers attending them under the conditions described, such that the pairs of people who met each other are exactly those in the input data. Print “NO” otherwise.



      Sample Input

      4 4
      0 1
      0 2
      1 2
      2 3
      
      4 5
      0 1
      0 2
      1 2
      2 3
      0 3
      
      7 11
      0 1
      0 2
      0 4
      1 3
      1 5
      1 6
      2 4
      2 5
      3 5
      3 6
      5 6
      
      0
      



      Sample Output

      YES
      NO
      YES
      

      Problemsetter: David García Soriano

      Added by:David García Soriano
      Date:2011-11-24
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CUPCAM 2009









      SPOJ Problem Set ()

      10095. Caper Pizza

      Problem code: CAPPIZZA

      Brunno Doiuna is very fond of caper pizzas, which he always likes to share with his girlfriend. As she also loves capers, it is of the utmost importance, in order to avoid unnecessary quarrels, to split the pizza into two equally-sized slices in such a way that each half contains exactly the same number of capers. However, most caper pizzas also contain a number of peppercorns, and neither Brunno nor his girlfriend likes them. Therefore, it is also crucial that each of the two halves contain the same number of peppercorns. As you can easily observe, depending on the position of capers and peppercorns on the pizza, it is not always possible to make a straight-line cut into the pizza in such a way that the two slices have the same area and the same number of capers and peppercorns lie in each resulting piece. Your task is to design a program to decide if it is possible to make such a cut or not, knowing the positions of capers and peppercorns.



      Input

      We will assume that the pizza is circular and is centered at the origin, and is big enough to contain all capers and peppercorns. We also assume that there is an even number of capers and an even number of peppercorns, and that no cut goes through any of the capers or pepper balls. Additionally, no pair of peppercorns, capers, or a peppercorn and a caper are aligned with the origin, or form an angle of less than 10−6 degrees with the origin.

      There can be multiple test cases, one after the other. The first line of a test case contains two even integers c ≥ 0 and p ≥ 0 (where 2 ≤ c + p ≤ 30000) separated by a space, the number of capers and peppercorns, respectively. Each of the following c lines describes the position of a caper using two floating point numbers, separated by a space, representing its x and y coordinates. Each of the next p lines holds two floating point numbers, the x and y coordinates of a peppercorn. A blank line follows each test case.

      The last line of input will contain −1 −1. This marks the end of input – do not write any output for this special last line.



      Output

      YES for a positive answer, NO otherwise.



      Sample Input

      2 2
      1 1
      1 0
      0 1
      -1 1
      
      2 2
      1 1
      -1 1
      0 1
      0.1 -1
      
      -1 -1
      



      Sample Output

      NO
      YES
      

      Problemsetter: Manuel Abellanas

      Added by:David García Soriano
      Date:2011-11-25
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:CUPCAM 2009









      SPOJ Problem Set (classical)

      10096. Lights (Extreme)

      Problem code: LIGHTS3

      Note: it is advisable to solve LIGHTS2 before attempting this problem.

      John has n light bulbs and a switchboard with n switches; each bulb can be either on or off, and pressing the i−th switch changes the state of bulb i from on to off, and viceversa. He is using them to play a game he has made up. In each move, John selects a (possibly empty) set of switches and presses them, thus inverting the states of the corresponding bulbs. Initially all lights are off, and after exactly m moves John would like to have the first v bulbs on and the rest off; otherwise he loses the game. There is only one restriction: he is not allowed to press the same set of switches in two different moves.

      This is quite an easy game, as there are lots of ways of winning. This has encouraged him to keep playing different winning games, and now he is intent on trying them all. Help him count how many ways of winning there are. Two games are considered the same if, after a reordering of the moves in one of them, at every step the same set of switches is pressed in both of them.

      For example, if n = 4, m = 3, and v = 2, one possible winning game is obtained by pressing switches 1, 2 and 4 in the first move, 1 and 3 in the second one, and 1, 3 and 4 in the last one. This is considered equivalent to, say, first pressing 1 and 3; then 1, 2, 4; and then 1, 3, 4.



      Input

      The input has at most 1500 lines, one for each test case. Each line contains three integers n (1 ≤ n ≤ 10 000 000), m (1 ≤ m ≤ 10 000 000), and v (0 ≤ vn). The last line of input will hold the values 0 0 0 and must not be processed.



      Output

      Print one line for each test case containing the number of ways John can play the game, modulo the prime 10 567 201.


      Sample Input

      3 3 1
      6 4 0
      6 4 3
      0 0 0
      


      Sample Output

      7
      10416
      9920
      

      Problemsetter: David García Soriano 

      Added by:David García Soriano
      Date:2011-11-25
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10105. Alphabet Soup

      Problem code: ALPHSOUP

       

      Peter is having lunch at home. Unfortunately for him, today’s meal is soup. As Peter’s mother is aware that he doesn’t like it very much, she has cooked a special soup using pasta pieces shaped like letters from the alphabet, numbers and other characters. She has a special knife with which she can prepare an unlimited supply of pasta pieces that may come in S different forms. The soup always has P pasta pieces in it, and is so thick that the pieces never move.

      Despite her efforts, Peter is still not happy with today’s menu and asks how many days in his life he will have to eat soup. His mother promises him that she will prepare a different soup every day, and that on no day will the dish contain the same shapes in all positions as any soup dish previously served. However, the number P of pasta pieces, as well as the positions in which pieces float, will remain the same every day. Peter is not easily fooled (or so he thinks), and he cleverly realizes that this can still make him eat soup for ages. In an attempt to reduce the number of configurations, he tells his mother he will not accept any dish which can be obtained by rotating one of the configurations previously seen.


      Figure 1: Top view of Peter’s dish

      Consider the dish as a circle of radius 2 centered at the origin. All the symbols will be floating in the soup at a given angle (in millidegrees) at distance 1 from the origin. Two plates are considered equal if you can perform a rotation of one of the dishes about its center so that the positions of the symbols, as well as the symbols themselves, are the same in both.

      Your program will be given the number of possible symbols Peter’s mother has available, and the angles determining the location of each of the pasta pieces (measured clockwise in millidegrees). Write a program that returns the number of possible plates Peter’s mother can prepare. As this number can be very large, output the number modulo 100,000,007, which is prime.



      Input

      The first line of input in each test case contains two numbers: S (2 ≤ S ≤ 1,000), the number of symbols Peter’s mother can use; and P (P > 0), the number of pasta pieces floating in the soup. Each of the next P lines contains the angle A (0 ≤ A < 360,000) of one of the P pieces (measured clockwise in millidegrees). All angles will be different.

      Different tests cases are separated by a blank line. After the last test case there is a line with S = P = −1.



      Output

      For each test case output a single integer in a line by itself, the number of different plates Peter’s mother can cook modulo 100,000,007.



      Sample Input

      2 4
      0
      90000
      180000
      270000
      
      100 5
      0
      45000
      90000
      180000
      270000
      
      -1 -1
      



      Sample Output

      6
      99999307
      

      Problemsetter: Javier Gómez Serrano

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10106. Coin Collecting

      Problem code: COIN

      As a member of the Association of Coin Minters (ACM), you are fascinated by all kinds of coins and one of your hobbies involves collecting national currency from different countries. Your friend, also an avid coin collector, has her heart set on some of your precious coins and has proposed to play a game that will allow the winner to acquire the loser’s collection (or part thereof).

      She begins by preparing two envelopes, each of them enclosing two coins that come from different countries. Then she asks you to choose one of the two envelopes. You can see their contents before making your choice, and also decline the offer and take neither. This process is repeated for a total of r times. As the game progresses, you are also allowed to change your mind about your previous picks if you think you can do better. Eventually, your friend examines the envelopes in your final selection, and from among them she picks a few envelopes herself. If her selection is non-empty and includes an even number of coins from every country (possibly zero), she wins and you must hand over your entire coin collection to her, which would make years of painstaking effort go to waste and force you to start afresh. But if you win, you get to keep the coins from all the envelopes you picked.

      Despite the risks involved, the prospect of enlarging your collection is so appealing that you decide to take the challenge. You’d better make sure you win as many coins as possible.



      Input

      The first line of each test case is the number r of rounds (1 ≤ r ≤ 300); a line with r = 0 indicates the end of the input. The next r lines contain four non-negative integers 0 ≤ a, b, c, d < 10,000, meaning that your friend puts coins from countries labelled a and b inside one of the envelopes, and c and d inside the other one. A blank line separates test cases.



      Output

      Print a line per test case containing the largest number of coins you are guaranteed.



      Sample Input

      4
      0 1 0 5
      5 1 0 5
      1 2 0 1
      1 5 2 0
      
      6
      1 4 1 4
      2 4 2 4
      0 3 0 3
      0 4 0 4
      4 3 4 3
      1 3 1 3
      
      0
      



      Sample Output

      6
      8
      

      Problemsetter: David García Soriano

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:40s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10107. Cybercrime Donut Investigation

      Problem code: DONUT

      Year 2042. The Internet has evolved to a virtual reality dataspace where crimes are committed every day. The 2041 SWERC winner developed an agent that drops a donut every time a crime is committed in the Cyberspace. Each of the donuts has its own signature. The Madrid Police have a huge database with crimes and their donut signatures.

      Today is your day. Your task is to implement a new agent that looks for the records in the database that bear a strong resemblance to the given signature of a dropped donut found at a new crime scene.


      Figure 1: The major piece of evidence for today’s unsolved crime streak

      Experts in virtual criminology have obtained the best similarity measure between donuts: compute the difference in radius of the internal part of the toroids (holes), compute the difference in radius of the external part of the toroids (tubes), and then add up those differences.



      Input

      The first line of each test case contains n (1 ≤ n ≤ 50,000), the number of donuts in the database. The ith of the following n lines contains the radius of the hole and radius of the tube of the ith donut in the database, described by two integers l and w (1 ≤ l, w ≤ 109). After that there is a line containing q (1 ≤ q ≤ 10,000), the number of donuts that you are looking for in the database. Then q lines follow, the ith of them describing the dimensions of the newly found ith donut in the same way.

      Different test cases are separated by a blank line. A line containing −1 marks the end of the input.



      Output

      The output of your program on each test case should have q lines, each of them containing an integer. The ith of these lines should contain the similarity between the newly found ith donut and the donut in the database that most closely resembles it. Outputs for different test cases should be separated by a blank line.



      Sample Input

      2
      2 3
      3 4
      2
      1 1
      3 4
      
      2
      1 1
      9 9
      4
      4 5
      6 5
      2 5
      3 4
      
      -1
      



      Sample Output

      3
      0
      
      7
      7
      5
      5
      

      Problemsetter: Abel Molina Prieto

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:75s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10108. Distributing Ballot Boxes

      Problem code: BALLOT

      Today, besides SWERC’11, another important event is taking place in Spain which rivals it in importance: General Elections. Every single resident of the country aged 18 or over is asked to vote in order to choose representatives for the Congress of Deputies and the Senate. You do not need to worry that all judges will suddenly run away from their supervising duties, as voting is not compulsory.

      The administration has a number of ballot boxes, those used in past elections. Unfortunately, the person in charge of the distribution of boxes among cities was dismissed a few months ago due to financial restraints. As a consequence, the assignment of boxes to cities and the lists of people that must vote in each of them is arguably not the best. Your task is to show how efficiently this task could have been done.

      The only rule in the assignment of ballot boxes to cities is that every city must be assigned at least one box. Each person must vote in the box to which he/she has been previously assigned. Your goal is to obtain a distribution which minimizes the maximum number of people assigned to vote in one box.

      In the first case of the sample input, two boxes go to the first city and the rest to the second, and exactly 100,000 people are assigned to vote in each of the (huge!) boxes in the most efficient distribution. In the second case, 1, 2, 2 and 1 ballot boxes are assigned to the cities and 1,700 people from the third city will be called to vote in each of the two boxes of their village, making these boxes the most crowded of all in the optimal assignment.



      Input

      The first line of each test case contains the integers N (1 ≤ N ≤ 500,000), the number of cities, and B (NB ≤ 2,000,000), the number of ballot boxes. Each of the following N lines contains an integer ai, (1 ≤ ai ≤ 5,000,000), indicating the population of the ith city.

      A single blank line will be included after each case. The last line of the input will contain -1 -1 and should not be processed.



      Output

      For each case, your program should output a single integer, the maximum number of people assigned to one box in the most efficient assignment.



      Sample Input

      2 7
      200000
      500000
      
      4 6
      120
      2680
      3400
      200
      
      -1 -1
      



      Sample Output

      100000
      1700
      

      Problemsetter: Luis Hernandez Corbato

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10109. Game, Set and Match

      Problem code: GSM

      In this problem you need to assist in computing the probability of winning at tennis. Here is a brief explanation of how the scoring system works. In a tennis match, players play a certain number of consecutive sets. Each set is in turn made up of a series of games (and may include a tie-break if needed). Finally each game is made of points.

      Points.

      Every point is started by one of the players serving (i.e. hitting the ball into the service box in the opposite court) and the other receiving serve. The server then attempts to return the ball into the server’s court and players alternate hitting the ball across the net. When one of the players fails to make a legal return (e.g. if the ball is knocked out of the court), he or she loses the point. The specifics of how points are won are not important to us.

      Games.

      The scoring system within a game is peculiar to say the least. As the player wins points in a game, his score goes from the initial value of 0 (read “love”) to 15, 30, or 40 (yes, just when you think you’re starting to spot a pattern in this mess it breaks down). There is no a-priori limit to the length of a game (meaning the number of points played), but a player’s score is always indicated by one of these numbers according to the following rules. When a player has three points (score 40) and wins the following point as well, he wins the game unless the scoreline was 40−40 (read “deuce”) to start with. A player needs to win two consecutive points from deuce to win the game. Winning one gives him advantage; if followed by a second winning point the game is won by him, but if followed by a losing point the score reverts to deuce.

      Example: at 40−30, if the first player wins the next point he wins the game. However, if the second player wins the next three points the game is his.

      Sets.

      A player wins a set if he wins at least six games (in the current set) and he is two games ahead of his opponent but, as you may be starting to suspect, there is yet another exception. In case the scoreline for the number of games won reaches six-all (6−6), a tie-break is played instead to decide the set.

      Example: at 5−4, if the first player wins the next game he takes the set 6−4. But if he loses, the set is still undecided and can eventually go to either 7−5, 5−7 or a tie-break.

      Tie-break.

      A tie-break (and the set to which it belongs) is won when a player wins at least seven points by a margin of two points or more.

      Match.

      The winner of a match is the first player to win 2 sets (the wins do not need to be consecutive). Hence a match may go to 2 or 3 sets depending on how the game develops.


      Rafa has been carefully studying his past performances against his next opponent and he knows he wins each point with probability precisely p, irrespective of whether he is serving or receiving and regardless of all other points played. Can you help him assess his chances of winning the match?



      Input

      Each test case is described by a single floating point number p, 0 ≤ p ≤ 1 in its own line. A value of −1 for p marks the end of the input.



      Output

      For each test case, print a single line with the probabilities of Rafa winning a given game, set and match, respectively. These three numbers must be separated by a space character. Your answers should be accurate to within an absolute error of 10−6.


      Sample Input

      0.5
      0.3
      0.7
      -1
      



      Sample Output

      0.50000000000 0.50000000000 0.50000000000
      0.09921103448 0.00016770463 0.00000008437
      0.90078896552 0.99983229537 0.99999991563
      

      Problemsetter: David García Soriano

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10110. Guess the Numbers

      Problem code: GUESSNM2

      John has never been very good at maths. Due to his bad grades, his parents have sent him to the Academic Coalition of Mathematics (ACM). Despite the large amount of money his parents are spending on the ACM, John does not pay much attention during classes. However, today he has begun to think about all the effort his parents are putting into his education, and he has started to feel somewhat… guilty. So he has made a decision: he is going to improve his maths grades!

      However, no sooner had he resolved to pay attention than the lesson ended. So the only thing he has been able to do is to hurriedly copy the content of the blackboard in his notebook. Today, the teacher was explaining basic arithmetic expressions with unknowns. He vaguely remembers that his classmates have been substituting values into the unknowns to obtain the expressions’ results. However, in all the hurry, John has only written down expressions, values and results in a messy fashion. So he does not know which value comes with each unknown, or which result goes with each expression.

      That is the reason he needs your help: he wants to know, given an expression, some values and a result, whether it is possible or not to assign those values to the unknowns in order for the expression to evaluate to the given result. The particular assignment of values does not matter to John, as he wants to do it by himself. He only wants to know whether it is possible or not.



      Input

      Each test case in the input file consists of two lines:

      • The first line contains a sequence of natural numbers. The first one (1 ≤ n ≤ 5) is the number of unknowns that will occur in the expression. It is followed by a sequence of n integers v1vn (0 ≤ vi ≤ 50), which are the values to be assigned to the unknowns. Finally, there is an integer m (0 ≤ m ≤ 1000) representing the desired result of the evaluation of the expression.
      • The second line contains an arithmetic expression composed of lowercase letters (a-z), brackets (( and )) and binary operators (+, -, *). This expression will contain n unknowns, represented by n different lowercase letters, without repetitions. The expression will not contain any blanks and will always be syntactically correct, i.e. it is just an unknown or has the form (e1 op e2 ), where e1 and e2 are expressions and op is one of the three possible binary operators.

      The input will finish with a dummy test case of just one line containing 0 0, which must not be processed.



      Output

      For each test case, print a single line with YES if there exists an assignment of the values v1vn to the unknowns such that the expression evaluates to m, and NO otherwise. Notice that each value vi must be assigned to exactly one unknown.



      Sample Input

      3 2 3 4 14
      ((a+b)*c)
      2 4 3 11
      (a-b)
      1 2 2
      a
      0 0
      



      Sample Output

      YES
      NO
      YES
      

      Problemstter: Enrique Martín Martín

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10111. Nonnegative Partial Sums

      Problem code: PARSUMS

      You are given a sequence of n numbers a0, …, an−1. A cyclic shift by k positions (0 ≤ kn−1) results in the following sequence: ak, ak+1, …, an−1, a0, a1, …, ak−1. How many of the n cyclic shifts satisfy the condition that the sum of the first i numbers is greater than or equal to zero for all i with 1 ≤ in?



      Input

      Each test case consists of two lines. The first contains the number n (1 ≤ n ≤ 106), the number of integers in the sequence. The second contains n integers a0, …, an−1 (−1000 ≤ ai ≤ 1000) representing the sequence of numbers. The input will finish with a line containing 0.



      Output

      For each test case, print one line with the number of cyclic shifts of the given sequence which satisfy the condition stated above.



      Sample Input

      3
      2 2 1
      3
      -1 1 1
      1
      -1
      0
      



      Sample Output

      3
      2
      0
      

      Problemsetter: Adrian Kuegel

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10112. Peer Review

      Problem code: REVIEW

      For scientific conferences, scientists submit papers presenting their ideas, and then review each other’s papers to make sure only good papers are presented at the conference. Each paper must be reviewed by at least one scientist, and scientists must not review papers written by people they collaborate with (including themselves), or review the same paper more than once.

      You have been asked to write a program to check if your favorite conference is doing things right. Whether a paper is being reviewed too much, too little, or by the wrong people - the organizers must know before it is too late!



      Input

      The first line in each test case has two integers, K (1 ≤ K ≤ 5) and N (1 ≤ N ≤ 1000). K is the number of reviews that each paper will receive, while N is the number of papers to be reviewed. The conference only accepts papers with a single author, and authors can only present a single paper at the conference.

      Each of the next N lines describes an author and includes the name of the institution to which the author belongs, followed by the list of the K papers he or she has been requested to review. It is assumed that researchers from the same institution collaborate with each other, whereas researchers from different institutions don’t. All institution names are shorter than 10 characters, and contain only upper or lowercase letters and no whitespace. Since we have as many papers as authors, papers are identified by their author’s index; paper 1 was written by the first author in the list, and paper N was written by the last author.

      The end of the test cases is marked with a line containing K=0 and N=0. You should generate no output for this line.



      Output

      For each test case, your program should output NO PROBLEMS FOUND (if all rules are being followed) or P PROBLEMS FOUND, where P is the number of rule violations found (counting at most 1 violation per paper). If there is exactly one rule violation overall, your program should output 1 PROBLEM FOUND.



      Sample Input

      2 3
      UCM 2 3
      UAM 1 3
      UPM 1 2
      2 3
      UCM 2 3
      UAM 1 2
      UPM 2 2
      0 0
      



      Sample Output

      NO PROBLEMS FOUND
      3 PROBLEMS FOUND
      

      Problemsetter: Manuel Freire

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10113. Regular Convex Polygon

      Problem code: REGPOLYG

      A regular convex polygon is a polygon where each side has the same length, and all interior angles are equal and less than 180 degrees. A square, for example, is a regular convex polygon. You are given three points which are vertices of a regular convex polygon R; can you determine the minimum number of vertices that R must have?



      Input

      Each test case consists of three lines. Line i consists of two floating point values xi and yi (−104x1, y1 ≤ 104) where (xi, yi) are the coordinates of a vertex of R. The coordinates are given with a precision of 10−6, i.e., they differ from the exact coordinates by at most 10−6. You may assume that for each test case the Euclidean distance between any two given points is at least 1, and R has at most 1000 vertices. The input will finish with a line containing the word END.



      Output

      For each test case, print one line with the minimum number of vertices that R must have.



      Sample Input

      -1385.736326 -146.954822
      430.000292 -2041.361203
      1162.736034 478.316025
      0.000000 4147.000000
      -4147.000000 0.000000
      0.000000 -4147.000000
      END
      



      Sample Output

      3
      4
      

      Problemsetter: Adrian Kuegel

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10114. Remoteland

      Problem code: RMTLAND

      In the Republic of Remoteland, the people celebrate their independence day every year. However, as it was a long long time ago, nobody can remember when it was exactly. The only thing people can remember is that today, the number of days elapsed since their independence (D) is a perfect square, and moreover it is the largest possible such number one can form as a product of distinct numbers less than or equal to n.

      As the years in Remoteland have 1,000,000,007 days, their citizens just need D modulo 1,000,000,007. Note that they are interested in the largest D, not in the largest D modulo 1,000,000,007.



      Input

      Every test case is described by a single line with an integer n, (1 ≤ n ≤ 10,000,000). The input ends with a line containing 0.



      Output

      For each test case, output the number of days ago the Republic became independent, modulo 1,000,000,007, one per line.



      Sample Input

      4
      9348095
      6297540
      0
      



      Sample Output

      4
      177582252
      644064736
      

      Problemsetter: Javier Gómez Serrano

      Added by:David García Soriano
      Date:2011-11-26
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Southwestern Europe Regional, SWERC 2011









      SPOJ Problem Set (classical)

      10128. Treasures and Vikings

      Problem code: TANDV

      You have a treasure map that is arranged into a N _M grid. A grid square may be either sea or part of

      an island. In addition, the map shows the treasure and an enemy Viking ship that occupies one (sea)

      square. Finally, for convenience you have also drawn your own position.

      Now you must set up a fixed route to get the treasure. The route must start at your position, end at

      the treasure, and consist of a sequence of moves. In each move, you can go only to an (horizontally

      or vertically) adjacent square that is not part of an island. But beware: The Viking ship might follow

      you, using the same kind of moves! After each of your moves according to your route, the Viking

      ship may move or not. Your move and the Vikings’ reaction together is called a round.

      After every round, the following checks are made:

      _ If you are in line with the Viking ship (you are in the same vertical or horizontal line as the

      Viking ship with only sea between the Viking ship and you), you are dead.

       _ If you aren’t dead and at the treasure-spot, you get the treasure.

      Write a program that decides whether it is possible to set up a fixed route in advance such that you

      can get the treasure by following this route and will not get killed by the Vikings – no matter how the

      Viking ship moves.

      Input

      The first line of input contains two integers N and M (1<=N,M<=700) , the dimensions of the map. Each of the

      following N lines contain M characters. Each character describes a square in the map, and is either

      . (sea), I (part of an island), V (the Viking ship), Y (your position), or T (the treasure). Each of V, Y,

      and T will occur exactly once.

      Output

      The only line of the output must contain the string YES, if it is possible to set up a route to get the

      treasure, or NO otherwise.

      Example

      Input:
      5 7
      Y.....V
      ..I....
      ..IIIII
      .......
      ...T...
      Output:
      YES

      Added by:bnta2
      Date:2011-11-28
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 D F# JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3
      Resource:BOI









      SPOJ Problem Set (classical)

      10141. STRAZA

      Problem code: STRAZA

      Near a military base there is a system of trenches, modeled as line segments on a plane. During nighttime, when most soldiers are fast asleep, three guards stand watch of the trenches. Two guards can see each other if there is a trench (or a row of trenches) along the entire straight line segment between them and there is no third guard on that line segment.

       For security reasons, the guards must be placed so that each guard sees the other two. How many ways can they be placed?

       INPUT

      The first line contains the integer N (1 ≤ N ≤ 20), the number of trenches. Each of the next N lines contains the description of one trench: four positive integers X1, Y1, X2, Y2 (all less than or equal to 1000), where X1 and Y1 are coordinates of one end, while X2 and Y2 are coordinates of the other  end of the trench.

       Trenches in the input may overlap and share endpoints.


       OUTPUT 

      in a single line, output the number of ways the guards can be placed.

       

      SAMPLE TEST DATA


      Added by:Santiago Zubieta
      Date:2011-11-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Croatian Open Competition in Informatics (COCI), Contest 2 - November 25, 2006









      SPOJ Problem Set ()

      10145. Birthday Cake

      Problem code: BCAKE

       

      Today is the birthday of Seraph. Seraph love to eat chocolate cake, unfortunately Seraph should not be too much to eat chocochip, the maximum he can only take K chocochip in the cake.
      You'll give the configuration of the cake, then please help Seraph to know maximum area of that cake that Seraph can eat.

       

      Today is the birthday of Seraph. Kasumi as his best friend want to give a surprice to Seraph, she know that Seraph love to eat chocolate cake, unfortunately Seraph should not be too much to eat chocochip, the maximum he can only take K chocochip in the cake and he want the cake that he'll eat is rectangle. If Seraph can't get K chocochip or not rectangle then he don't want eat that cake.

      You'll give the configuration of the cake, then please help Kasumi to know minimum area of that cake that Seraph can eat.

       

       

      Input

      first line is test case, then each test case will contain H (1 ≤ H ≤ 30), W (1 ≤ W ≤ 30), K (0 ≤ K ≤ 900) that means H is the height of cake, W is width of cake and K is maximum chocochip that seraph can eat.

      on the next line you'll give the configuration of the cake where 'C' means chocochip area and '.' is normal cake area. You can assume that width and height of cake between 1 and 30 inclusive.

      Output

      Print one line A that means the minimum area that seraph can eat. If Seraph can't eat that cake then print '-1'

      Example

       

      Sample Input 1:
      1
      5 6 4
      ......
      .C....
      ..CC..
      ...CC.
      ......
      
      Sample Output 1:
      6

       

      Sample Input 2:
      1
      5 6 3
      ......
      ......
      ..CC..
      ..CC..
      ......
      
      Sample Output 2:
      -1


      Added by:[Retired] Fendy Kosnatha
      Date:2011-12-01
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:inspired by TopCoder problem









      SPOJ Problem Set (classical)

      10186. Divisor Digits

      Problem code: PUCMM025

      Given a number, output how many digits in number that number itself is divisible by. Count all occurences of such digits in the number, not just the first.

      For example, 12345 is divisible by 1, 3, and 5, so, the answer in this case must be 3.

      Input

      Each test case is a number between 1 and 10240.

      Output

      for each test case, output how many of its digits divide the number.

      Example

      Input:
      12345
      661232
      312
      730000000

      Output:
      3
      3
      3
      0

      Added by:Olson Ortiz
      Date:2011-12-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Used in 2da Olimpiada de Programacion PUCMM-ACM-ISC (fase 2)









      SPOJ Problem Set (classical)

      10210. After Party Transfers

      Problem code: TRANSFER

      You've been to a potluck party (party where each person contributes food), but some people are angry that they spent more money preparing their dish than the others. Now they want you (they span the bottle) to figure out how the participants of the party can, in the fewest amount of transfers, become even.

      To clarify, you are free to transfer money between them in any way you like, but eventually the money they spent on their dishes, plus the money they received, minus the money the sent, must be equal for all participants.

      Input

      The first line contains C ∈ [0..10] - the number of test cases.

      For each test case, the first line contains the number N ∈ [0..20] - the number of people at the party.

      The following N lines contains a interger xi ∈ [0,10^6] representing the amount of money the ith persons dish cost.

      Output

      For each testcase:

      The first line should be the minimal amount of transfers needed to even out the party budget.

      The following lines should be on the form "a -> b: t", where a,b ∈ [0..N) and represent that person 'a' must transfer 't' money to person 'b'. t is here a floating point number of at least 6 digits precision. (Notice: that is 6 digits precision after adding together your in and out flows)

      In case of multiple best solutions exists, print any.

      Example

      Input:
      2
      6
      2
      4
      1
      5
      0
      6
      3
      9
      16
      25
      
      Output:
      3
      0 -> 1: 1.0
      2 -> 3: 2.0
      4 -> 5: 3.0
      2
      0 -> 1: 7.6666666666667
      1 -> 2: 8.33333333333
      Explaination:

      In the first case, 3 is the minimal amount of transfers. An alternative transfer pattern would be "0 -> 3: 1    1 -> 3: 2    2 -> 4: 2     2 -> 5: 1". That would have made everyone even, but would have taken one more transfer (4).

      In the second case, after the transfers, each person is down 16.666.


      Added by:Thomas Dybdahl Ahle
      Date:2011-12-13
      Time limit:5s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10228. Magic Grid

      Problem code: AMR11A

       

      Thanks a lot for helping Harry Potter in finding the Sorcerer's Stone of Immortality in October. Did we not tell you that it was just an online game ? uhhh! now here is the real onsite task for Harry. You are given a magrid S ( a magic grid ) having R rows and C columns. Each cell in this magrid has either a Hungarian horntail dragon that our intrepid hero has to defeat, or a flask of magic potion that his teacher Snape has left for him. A dragon at a cell (i,j) takes away |S[i][j]| strength points from him, and a potion at a cell (i,j) increases Harry's strength by S[i][j]. If his strength drops to 0 or less at any point during his journey, Harry dies, and no magical stone can revive him.

      Harry starts from the top-left corner cell (1,1) and the Sorcerer's Stone is in the bottom-right corner cell (R,C). From a cell (i,j), Harry can only move either one cell down or right i.e., to cell (i+1,j) or cell (i,j+1) and he can not move outside the magrid. Harry has used magic before starting his journey to determine which cell contains what, but lacks the basic simple mathematical skill to determine what minimum strength he needs to start with to collect the Sorcerer's Stone. Please help him once again.

      Thanks a lot for helping Harry Potter in finding the Sorcerer's Stone of Immortality in October. Did we not tell you that it was just an online game ? uhhh! now here is the real onsite task for Harry. You are given a magrid S ( a magic grid ) having R rows and C columns. Each cell in this magrid has either a Hungarian horntail dragon that our intrepid hero has to defeat, or a flask of magic potion that his teacher Snape has left for him. A dragon at a cell (i,j) takes away |S[i][j]| strength points from him, and a potion at a cell (i,j) increases Harry's strength by S[i][j]. If his strength drops to 0 or less at any point during his journey, Harry dies, and no magical stone can revive him.

      Harry starts from the top-left corner cell (1,1) and the Sorcerer's Stone is in the bottom-right corner cell (R,C). From a cell (i,j), Harry can only move either one cell down or right i.e., to cell (i+1,j) or cell (i,j+1) and he can not move outside the magrid. Harry has used magic before starting his journey to determine which cell contains what, but lacks the basic simple mathematical skill to determine what minimum strength he needs to start with to collect the Sorcerer's Stone. Please help him once again.

       

      Input (STDIN):

      The first line contains the number of test cases T. T cases follow. Each test case consists of R C in the first line followed by the description of the grid in R lines, each containing C integers. Rows are numbered 1 to R from top to bottom and columns are numbered 1 to C from left to right. Cells with S[i][j] < 0 contain dragons, others contain magic potions.

      Output (STDOUT):

      Output T lines, one for each case containing the minimum strength Harry should start with from the cell (1,1) to have a positive strength through out his journey to the cell (R,C).

      Constraints:

      1 ≤ T ≤ 5

      2 ≤ R, C ≤ 500

      -10^3 ≤ S[i][j] ≤ 10^3

      S[1][1] = S[R][C] = 0

       

      Sample Input:

      3
      2 3
      0 1 -3
      1 -2 0
      2 2
      0 1
      2 0
      3 4
      0 -2 -3 1
      -1 4 0 -2
      1 -2 -3 0

       

      Sample Output:

      2
      1
      2

      Explanation:

      Case 1 : If Harry starts with strength = 1 at cell (1,1), he cannot maintain a positive strength in any possible path. He needs at least strength = 2 initially.

      Case 2 : Note that to start from (1,1) he needs at least strength = 1.


      Added by:Varun Jalan
      Date:2011-12-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Anil Kishore - ICPC Asia regionals, Amritapuri 2011









      SPOJ Problem Set (classical)

      10229. Save the Students

      Problem code: AMR11B

       

      Hogwarts is under attack by the Dark Lord, He-Who-Must-Not-Be-Named. To protect the students, Harry Potter must cast protective spells so that those who are protected by the spells cannot be attacked by the Dark Lord.
      Harry has asked all the students to gather on the vast quidditch sports field so that he can cast his spells.  The students are standing in a 2D plane at all grid points - these are the points (x,y) such that both x and y are integers (positive, negative or 0). Harry's spell can take the shapes of triangle, circle or square, and all who fall within that shape (including its boundaries) are protected.
      Given the types of spells and the details regarding where Harry casts the spell, output the number of people saved by Harry's spells. 
      Input (STDIN):
      The first line contains the number of test cases T. T test cases follow.
      Each case contains an integer N on the first line, denoting the number of spells Harry casts. N lines follow, each containing the description of a spell.
      If the ith spell is a triangle, then the line will be of the form "T x1 y1 x2 y2 x3 y3". Here, (x1,y1), (x2,y2) and (x3,y3) are the coordinates of the vertices of the triangle.
      If the ith spell is a circle, then the line will be of the form "C x y r". Here, (x,y) is the center and r is the radius of the circle.
      If the ith spell is a square, then the line will be of the form "S x y l". Here, (x,y) denotes the coordinates of the bottom-left corner of the square (the corner having the lowest x and y values) and l is the length of each side.
      Output (STDOUT):
      Output T lines, one for each test case, denoting the number of people Harry can save.
      Constraints:
      All numbers in the input are integers between 1 and 50, inclusive.
      The areas of all geometric figures will be > 0.
      Time Limit: 3 s
      Memory Limit: 32 MBytes
      Sample Input:
      4
      1
      C 5 5 2
      1
      S 3 3 4
      1
      T 1 1 1 3 3 1 
      3
      C 10 10 3
      S 9 8 4
      T 7 9 10 8 8 10
      Sample Output:
      13
      25
      6
      34

       

      Hogwarts is under attack by the Dark Lord, He-Who-Must-Not-Be-Named. To protect the students, Harry Potter must cast protective spells so that those who are protected by the spells cannot be attacked by the Dark Lord.

      Harry has asked all the students to gather on the vast quidditch sports field so that he can cast his spells.  The students are standing in a 2D plane at all grid points - these are the points (x,y) such that both x and y are integers (positive, negative or 0). Harry's spell can take the shapes of triangle, circle or square, and all who fall within that shape (including its boundaries) are protected.

      Given the types of spells and the details regarding where Harry casts the spell, output the number of people saved by Harry's spells.

       

      Input (STDIN):

      The first line contains the number of test cases T. T test cases follow.

      Each case contains an integer N on the first line, denoting the number of spells Harry casts. N lines follow, each containing the description of a spell.

      If the ith spell is a triangle, then the line will be of the form "T x1 y1 x2 y2 x3 y3". Here, (x1,y1), (x2,y2) and (x3,y3) are the coordinates of the vertices of the triangle.

      If the ith spell is a circle, then the line will be of the form "C x y r". Here, (x,y) is the center and r is the radius of the circle.

      If the ith spell is a square, then the line will be of the form "S x y l". Here, (x,y) denotes the coordinates of the bottom-left corner of the square (the corner having the lowest x and y values) and l is the length of each side.

       

      Output (STDOUT):

      Output T lines, one for each test case, denoting the number of people Harry can save.

       

      Constraints:

      All numbers in the input are integers between 1 and 50, inclusive.

      The areas of all geometric figures will be > 0.

       

      Sample Input:

      4

      1

      C 5 5 2

      1

      S 3 3 4

      1

      T 1 1 1 3 3 1 

      3

      C 10 10 3

      S 9 8 4

      T 7 9 10 8 8 10

       

      Sample Output:

      13

      25

      6

      34

       

       


      Added by:Varun Jalan
      Date:2011-12-15
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Venkatesh Basker - ICPC Asia regionals, Amritapuri 2011









      SPOJ Problem Set (classical)

      10230. Robbing Gringotts

      Problem code: AMR11C

       

      The Death Eaters are low on funds, and their leader Voldemort has asked them to get more money quickly, or face his wrath.  They decide that the best way is to rob Gringotts Wizarding Bank.  
      By threatening one of the goblins in charge of the bank, the 'M' Death Eaters have discovered that Gringotts has 'N' vaults, with vault number 'i' containing  X[i] gold items.  The weights of the gold items in the ith vault are g[i][1],g[i][2],...,g[i][X[i]]. But as soon as a vault is robbed, the magical wards go off and alarm bells ring. Thus they have enough time to rob just one vault each, and all robberies have to take place at the same time. The Death Eaters have decided that no two of them will rob the same vault as this increases the chances of them being caught.
      Death Eater j has a bag which can hold weight v[j]. They are a greedy and cowardly lot, so a Death Eater will only agree to rob a vault if he can fill up his bag completely to its capacity by taking some subset of the objects present in that vault. Note that it is not possible for a Death Eater to break any gold item; either it should be taken fully, or not be taken.
      Find the maximum weight of gold they can take away by planning their strategy correctly. 
      Input (STDIN):
      The first line contains the number of test cases T. T test cases follow. Each test case contains integers M and N on the first line. The next line contains M integers, the jth of which is v[j], which is the maximum weight of gold the jth Death Eater's bag can hold. The following N lines describe the gold items in the vaults. The ith line contains X[i], the number of gold items present in the ith vault, followed by X[i] integers g[i][1]..g[i][X[i]], denoting the weights of the each of the items present in the ith vault. There is a blank line after each test case.
      Output (STDOUT):
      Output one line for each test case, containing the maximum total weight of gold that the Death Eaters can rob.
      Constraints:
      1 <= T <= 10
      1 <= N,M <= 50
      1 <= X[i] <= 25
      1 <= v[i],g[i][j] <= 10,000,000
      Time Limit: 10 s
      Memory Limit: 64 MB
      Sample Input:
      2
      2 3
      3 9
      2 4 5
      2 3 9
      1 10
      4 4
      3 7 8 10
      3 1 2 4
      2 3 7
      4 2 2 4 4
      1 3
      Sample Output:
      12
      28

       

      The Death Eaters are low on funds, and their leader Voldemort has asked them to get more money quickly, or face his wrath.  They decide that the best way is to rob Gringotts Wizarding Bank.  

       

      By threatening one of the goblins in charge of the bank, the 'M' Death Eaters have discovered that Gringotts has 'N' vaults, with vault number 'i' containing  X[i] gold items.  The weights of the gold items in the ith vault are g[i][1],g[i][2],...,g[i][X[i]]. But as soon as a vault is robbed, the magical wards go off and alarm bells ring. Thus they have enough time to rob just one vault each, and all robberies have to take place at the same time. The Death Eaters have decided that no two of them will rob the same vault as this increases the chances of them being caught.

       

      Death Eater j has a bag which can hold weight v[j]. They are a greedy and cowardly lot, so a Death Eater will only agree to rob a vault if he can fill up his bag completely to its capacity by taking some subset of the objects present in that vault. Note that it is not possible for a Death Eater to break any gold item; either it should be taken fully, or not be taken.

       

      Find the maximum weight of gold they can take away by planning their strategy correctly.

       

      Input (STDIN):

      The first line contains the number of test cases T. T test cases follow. Each test case contains integers M and N on the first line. The next line contains M integers, the jth of which is v[j], which is the maximum weight of gold the jth Death Eater's bag can hold. The following N lines describe the gold items in the vaults. The ith line contains X[i], the number of gold items present in the ith vault, followed by X[i] integers g[i][1]..g[i][X[i]], denoting the weights of the each of the items present in the ith vault. There is a blank line after each test case.

       

      Output (STDOUT):

      Output one line for each test case, containing the maximum total weight of gold that the Death Eaters can rob.

       

      Constraints:

      1 <= T <= 10

      1 <= N,M <= 50

      1 <= X[i] <= 25

      1 <= v[i],g[i][j] <= 10,000,000

       

      Sample Input:

      2

      2 3

      3 9

      2 4 5

      2 3 9

      1 10

       

      4 4

      3 7 8 10

      3 1 2 4

      2 3 7

      4 2 2 4 4

      1 3

       

      Sample Output:

      12

      28

       

       


      Added by:Varun Jalan
      Date:2011-12-15
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Varun Jalan - ICPC Asia regionals, Amritapuri 2011









      SPOJ Problem Set (classical)

      10231. Wizarding Duel

      Problem code: AMR11D

       

      You are the organizer of a Wizarding Duel tournament at Hogwarts. N players participated in the tournament and each player played with every other player exactly once, and each such game resulted in a winner and a loser (no drawn games). It is now time to declare the results. Each player's score is the number of games the player won. However, you realize that something possibly went wrong with the scoring system, and the scores that you have noted down might be wrong. In fact, the scores you have noted down could simply not be possible. For example, suppose there are 3 players and the scores that you noted are 0,0 and 2. Clearly this is not possible as the game between the first two players must have had a winner and thus both the players cannot have score 0.
      While you have no way to figure out the correct scores of each player, you've decided to set the scores right by adjusting the scores of some players. The new set of scores should be possible to have arisen in the tournament, otherwise there would be ample proof that the scoring is wrong. However, making drastic changes might cause suspicion. So you've decided to adjust the scores so that the sum of the absolute differences between the old and the new scores of each player is minimized. In other words, if the original scores which you noted are a1,..,aN, you must change them to the series of possible scores b1,...bN such that the sum |ai - bi| is minimized.
      Input (STDIN):
      The first line contains the number of test cases T. T test cases follow. Each case contains an integer N on the first line, followed by the set of scores which you have noted down: a1..aN.
      Output (STDOUT):
      Output T lines, one for each test case, containing the minimum sum of absolute values in order to make the scorecard a valid one.
      Constraints:
      1 <= T <= 20
      2 <= N <= 50
      0 <= ai <= 100
      Time Limit: 3 seconds
      Memory Limit: 64 MB
      Sample Input:
      2
      3
      0 0 2
      5
      5 3 2 1 4
      Sample Output:
      1
      5

       

      You are the organizer of a Wizarding Duel tournament at Hogwarts. N players participated in the tournament and each player played with every other player exactly once, and each such game resulted in a winner and a loser (no drawn games). It is now time to declare the results. Each player's score is the number of games the player won. However, you realize that something possibly went wrong with the scoring system, and the scores that you have noted down might be wrong. In fact, the scores you have noted down could simply not be possible. For example, suppose there are 3 players and the scores that you noted are 0,0 and 2. Clearly this is not possible as the game between the first two players must have had a winner and thus both the players cannot have score 0.

       

      While you have no way to figure out the correct scores of each player, you've decided to set the scores right by adjusting the scores of some players. The new set of scores should be possible to have arisen in the tournament, otherwise there would be ample proof that the scoring is wrong. However, making drastic changes might cause suspicion. So you've decided to adjust the scores so that the sum of the absolute differences between the old and the new scores of each player is minimized. In other words, if the original scores which you noted are a1,..,aN, you must change them to the series of possible scores b1,...bN such that the sum |ai - bi| is minimized.

      Input (STDIN):

      The first line contains the number of test cases T. T test cases follow. Each case contains an integer N on the first line, followed by the set of scores which you have noted down: a1..aN.

      Output (STDOUT):

      Output T lines, one for each test case, containing the minimum sum of absolute values in order to make the scorecard a valid one.

      Constraints:

      1 <= T <= 20

      2 <= N <= 50

      0 <= ai <= 100

       

      Sample Input:

      2

      3

      0 0 2

      5

      5 3 2 1 4

       

      Sample Output:

      1

      5

       

       


      Added by:Varun Jalan
      Date:2011-12-15
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Varun Jalan - ICPC Asia regionals, Amritapuri 2011









      SPOJ Problem Set ()

      10232. Distinct Primes

      Problem code: AMR11E

       

      Arithmancy is Draco Malfoy's favorite subject, but what spoils it for him is that Hermione Granger is in his class, and she is better than him at it.  Prime numbers are of mystical importance in Arithmancy, and Lucky Numbers even more so. Lucky Numbers are those positive integers that have at least three distinct prime factors; 30 and 42 are the first two. Malfoy's teacher has given them a positive integer n, and has asked them to find the nth lucky number. Malfoy would like to beat Hermione at this exercise, so although he is an evil git, please help him, just this once.  After all, the know-it-all Hermione does need a lesson.
      Input (STDIN):
      The first line contains the number of test cases T. Each of the next T lines contains one integer n.
      Output (STDOUT):
      Output T lines, containing the corresponding lucky number for that test case.
      Constraints:
      1 <= T <= 20
      1 <= n <= 1000
      Time Limit: 2 s
      Memory Limit: 32 MB
      Sample Input:
      2
      1
      2
      Sample Output:
      30
      42

       

      Arithmancy is Draco Malfoy's favorite subject, but what spoils it for him is that Hermione Granger is in his class, and she is better than him at it.  Prime numbers are of mystical importance in Arithmancy, and Lucky Numbers even more so. Lucky Numbers are those positive integers that have at least three distinct prime factors; 30 and 42 are the first two. Malfoy's teacher has given them a positive integer n, and has asked them to find the nth lucky number. Malfoy would like to beat Hermione at this exercise, so although he is an evil git, please help him, just this once.  After all, the know-it-all Hermione does need a lesson.

       

      Input (STDIN):

      The first line contains the number of test cases T. Each of the next T lines contains one integer n.

       

      Output (STDOUT):

      Output T lines, containing the corresponding lucky number for that test case.

       

      Constraints:

      1 <= T <= 20

      1 <= n <= 1000

       

      Sample Input:

      2

      1

      2

       

      Sample Output:

      30

      42

       

       


      Added by:Varun Jalan
      Date:2011-12-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:Varun Jalan - ICPC Asia regionals, Amritapuri 2011









      SPOJ Problem Set ()

      10233. Magical Bridges

      Problem code: AMR11F

       

      Hogwarts School of Witchcraft and Wizardry has a circular lane having N towers numbered 1 to N. Towers i and i+1 are adjacent to each other for 1 ≤ i < N and also towers 1 and N are adjacent to each other. Each of these towers has exactly F number of floors, numbered 1,2,3,..,F-1,F from bottom to top. Floors i and i+1 in a tower are adjacent to each other and it takes one second to move between them. It also takes one second to move between floor 1 of a tower and floor 1 of its adjacent tower. Apart from these, there are M bridges designed for a quick escape in case of a Death Eater attack, each of which connects two floors of different towers. Each of these bridges is given as bi fi bj fj t, meaning it takes t seconds to move along this bridge that connects the floor fi of tower bi and the floor fj of tower bj. All ways are bidirectional.
      Given (qbi,qfi) and (qbj,qfj), find the minimum time in seconds it takes to reach floor qfj of tower qbj, starting from floor qfi of tower qbi. You have to answer a lot of such queries.
      Input (STDIN):
      The first line contains the number of test cases T. T cases follow. Each test case consists of N F M in the first line. N is the number of towers, F is the number of floors in each tower and M is the number of bridges. M lines follow, each of the form bi fi bj fj t, as mentioned in the problem statement. Next line contains Q, the number of queries and Q lines follow, each of the form qbi qfi qbj qfj.
      Output (STDOUT):
      For each query of the form qbi qfi qbj qfj, output one line denoting the minimum time in seconds it takes to reach the floor qfj of tower qbj, starting from the floor qfi of tower qbi.
      Constraints:
      1 ≤ T ≤ 3
      2 ≤ N, M ≤ 100
      2 ≤ F ≤ 1,000,000
      1 ≤ t ≤ 1,000,000
      1 ≤ Q ≤ 100,000
      1 ≤ bi, bj, qbi, qbj ≤ N
      1 ≤ fi, fj, qfi, qfj ≤ F
      Time Limit : 5s
      Memory Limit : 64 MB
      Sample Input:
      1
      5 4 3
      1 3 2 4 3
      2 3 3 3 2
      3 4 5 3 1
      5
      1 3 2 3
      1 3 3 2
      1 1 3 4
      3 3 4 4
      4 3 4 4
      Sample Output:
      4
      5
      4
      6
      1

      Hogwarts School of Witchcraft and Wizardry has a circular lane having N towers numbered 1 to N. Towers i and i+1 are adjacent to each other for 1 ≤ i < N and also towers 1 and N are adjacent to each other. Each of these towers has exactly F number of floors, numbered 1,2,3,..,F-1,F from bottom to top. Floors i and i+1 in a tower are adjacent to each other and it takes one second to move between them. It also takes one second to move between floor 1 of a tower and floor 1 of its adjacent tower. Apart from these, there are M bridges designed for a quick escape in case of a Death Eater attack, each of which connects two floors of different towers. Each of these bridges is given as bi fi bj fj t, meaning it takes t seconds to move along this bridge that connects the floor fi of tower bi and the floor fj of tower bj. All ways are bidirectional.

      Given (qbi,qfi) and (qbj,qfj), find the minimum time in seconds it takes to reach floor qfj of tower qbj, starting from floor qfi of tower qbi. You have to answer a lot of such queries.

       

      Input (STDIN):

      The first line contains the number of test cases T. T cases follow. Each test case consists of N F M in the first line. N is the number of towers, F is the number of floors in each tower and M is the number of bridges. M lines follow, each of the form bi fi bj fj t, as mentioned in the problem statement. Next line contains Q, the number of queries and Q lines follow, each of the form qbi qfi qbj qfj.

       

      Output (STDOUT):

      For each query of the form qbi qfi qbj qfj, output one line denoting the minimum time in seconds it takes to reach the floor qfj of tower qbj, starting from the floor qfi of tower qbi.

       

      Constraints:

      1 ≤ T ≤ 3

      2 ≤ N, M ≤ 100

      2 ≤ F ≤ 1,000,000

      1 ≤ t ≤ 1,000,000

      1 ≤ Q ≤ 100,000

      1 ≤ bi, bj, qbi, qbj ≤ N

      1 ≤ fi, fj, qfi, qfj ≤ F

       

      Sample Input:

      1

      5 4 3

      1 3 2 4 3

      2 3 3 3 2

      3 4 5 3 1

      5

      1 3 2 3

      1 3 3 2

      1 1 3 4

      3 3 4 4

      4 3 4 4

       

      Sample Output:

      4

      5

      4

      6

      1

       

       


      Added by:Varun Jalan
      Date:2011-12-15
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Anil Kishore - ICPC Asia regionals, Amritapuri 2011









      SPOJ Problem Set ()

      10235. Array Diversity

      Problem code: AMR11H

       

      Here we go!
      Let's define the diversity of a list of numbers to be the difference between the largest and smallest number in the list.
      For example, the diversity of the list (1, -1, 2, 7) = 7 - (-1) = 8.
      A substring of a list is considered a non-empty sequence of contiguous numbers from the list. For example, for the list (1,3,7), the substrings are (1), (3), (7), (1,3), (3,7), (1,3,7). A subsequence of a list is defined to be a non-empty sequence of numbers obtained by deleting some elements from the list. For example, for the list (1,3,7), the subsequences are (1), (3), (7), (1,3), (3,7), (1,7), (1,3,7).
      Given a list of length N find the number of substrings and subsequences in this list with the maximum diversity. If a substring/subsequence having maximum diversity occurs multiple times in the list, each of its occurances adds towards the answer.   And tell Harry Potter your answer.
      Input (STDIN):
      The first line contains T, the number of test cases. Then follow T test case blocks.
      Each blocks starts with the first line containing the number N.
      The second line contains a list of numbers in this list.
      Output (STDOUT):
      For each test case, output the number of substrings and the number of subsequences in this list with the maximum diversity.
      Since the answers maybe very large, output them modulo 1000000007.
      Constraints:
      T <= 10
      N <= 100,000
      Each number in the list is between 1 and 100,000 inclusive.
      Time Limit: 2 s
      Memory Limit: 32 MB
      Sample Input:
      3
      3
      1 2 3
      4
      1 4 3 4
      3
      3 2 1
      Sample Output:
      1 2
      3 6
      12

      Enough with this Harry Potter, please! What are we, twelve-year olds?  Let's get our teeth into some real pumpkin pasties -- oops, programming problems!

       

      Here we go!

      Let's define the diversity of a list of numbers to be the difference between the largest and smallest number in the list.

      For example, the diversity of the list (1, -1, 2, 7) = 7 - (-1) = 8.

       

      A substring of a list is considered a non-empty sequence of contiguous numbers from the list. For example, for the list (1,3,7), the substrings are (1), (3), (7), (1,3), (3,7), (1,3,7). A subsequence of a list is defined to be a non-empty sequence of numbers obtained by deleting some elements from the list. For example, for the list (1,3,7), the subsequences are (1), (3), (7), (1,3), (3,7), (1,7), (1,3,7).

       

      Given a list of length N find the number of substrings and subsequences in this list with the maximum diversity. If a substring/subsequence having maximum diversity occurs multiple times in the list, each of its occurences adds towards the answer.   And tell Harry Potter your answer

       

      Input (STDIN):

      The first line contains T, the number of test cases. Then follow T test case blocks.

      Each blocks starts with the first line containing the number N.

      The second line contains a list of numbers in this list.

       

      Output (STDOUT):

      For each test case, output the number of substrings and the number of subsequences in this list with the maximum diversity.

      Since the answers maybe very large, output them modulo 1000000007.

       

      Constraints:

      T <= 10

      N <= 100,000

      Each number in the list is between 1 and 100,000 inclusive.

       

      Sample Input:

      3

      3

      1 2 3

      4

      1 4 3 4

      3

      3 2 1

       

      Sample Output:

       

      1 2

      3 6

      1 2

       

       


      Added by:Varun Jalan
      Date:2011-12-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Pratik Tandel - ICPC Asia regionals, Amritapuri 2011









      SPOJ Problem Set ()

      10236. Generations

      Problem code: AMR11I

       

      Harry's friend Charlie Weasley has partnered with an old-time breeder of dragons in Romania.  When Harry visited Charlie over the summer, Charlie showed him breeding records stretching back centuries.  It had started out with just one female dragon named Abraxia that had then reproduced to give many generations of dragons.  The breeding record showed a family tree of dragons, starting with Abraxia and showing each descendant* (only females' descendants were shown),  the year each was hatched from its egg and the year each died.  Only already dead dragons were included. Charlie pointed out that a dragon matured early, and once hatched, could herself lay and hatch an egg in the very year it was born.  Dragon eggs did not need a mother's care to hatch -- the breeders simply used the warmth of a blowtorch to keep the egg warm and hatch it, sometimes long after the mother dragon was dead.
      Harry noticed that sometimes many generations of dragons were alive at the same time.   He was curious to figure out, for each dragon when it was alive, what was the maximum generational difference (absolute value) between it and its coeval** descendants.  Can you help him?  Assume that if a dragon dies the year another is hatched, they were coeval.
      *A descendant is a child, grandchild, great-grandchild etc.
      **coeval: Alive at the same time.
      Input (STDIN):
      The first line contains the number of test cases T.
      The first line of each test case starts with an integer N - the number of dragons.
      It is followed by N lines. The ith line (0 indexed) contains 3 integers, p_i, hatchyear_i and deathyear_i. p_i is the parent of ith dragon and its interval is hatchyear_i to deathyear_i.  The dragon with index 0 is Abraxia, and a mother's index is smaller than all its descendants'. 
      Output (STDOUT):
      Output T lines.
      Each line contains a space-separated list of N integers, the ith of them denoting the required answer for the ith dragon. If the ith dragon's life does not overlap with any descendant's, output 0 for that dragon.
      Constraints:
      1 <= T <= 3
      1 <= N <= 70000
      0 <= hatchyear <= deathyear <= 10^9
      p_0 = -1
      For all i > 0, 0 <= p_i < i
      hatchyear of dragon >= hatchyear of its mother
      Time Limit: 3s
      Memory Limit: 64 MB
      Sample Input:
      2
      5
      -1 0 10
      0 1 5
      0 2 8
      0 2 5
      3 10 12
      9
      -1 0 10
      0 1 1
      0 2 2
      1 2 3
      1 3 4
      2 2 3
      2 2 4
      6 10 11
      6 20 30
      Sample Output:
      2 0 0 0 0
      3 0 1 0 0 0 0 0 0

       

      Harry's friend Charlie Weasley has partnered with an old-time breeder of dragons in Romania.  When Harry visited Charlie over the summer, Charlie showed him breeding records stretching back centuries.  It had started out with just one female dragon named Abraxia that had then reproduced to give many generations of dragons.  The breeding record showed a family tree of dragons, starting with Abraxia and showing each descendant* (only females' descendants were shown),  the year each was hatched from its egg and the year each died.  Only already dead dragons were included. Charlie pointed out that a dragon matured early, and once hatched, could herself lay and hatch an egg in the very year it was born.  Dragon eggs did not need a mother's care to hatch -- the breeders simply used the warmth of a blowtorch to keep the egg warm and hatch it, sometimes long after the mother dragon was dead.

      Harry noticed that sometimes many generations of dragons were alive at the same time.   He was curious to figure out, for each dragon when it was alive, what was the maximum generational difference (absolute value) between it and its coeval** descendants.  Can you help him?  Assume that if a dragon dies the year another is hatched, they were coeval.

       

      *A descendant is a child, grandchild, great-grandchild etc.

      **coeval: Alive at the same time.

       

      Input (STDIN):

      The first line contains the number of test cases T.

      The first line of each test case starts with an integer N - the number of dragons.

      It is followed by N lines. The ith line (0 indexed) contains 3 integers, p_i, hatchyear_i and deathyear_i. p_i is the parent of ith dragon and its interval is hatchyear_i to deathyear_i.  The dragon with index 0 is Abraxia, and a mother's index is smaller than all its descendants'. 

       

      Output (STDOUT):

      Output T lines.

      Each line contains a space-separated list of N integers, the ith of them denoting the required answer for the ith dragon. If the ith dragon's life does not overlap with any descendant's, output 0 for that dragon.

       

      Constraints:

      1 <= T <= 3

      1 <= N <= 70000

      0 <= hatchyear <= deathyear <= 10^9

      p_0 = -1

      For all i > 0, 0 <= p_i < i

      hatchyear of dragon >= hatchyear of its mother

       

      Sample Input:

      2

      5

      -1 0 10

      0 1 5

      0 2 8

      0 2 5

      3 10 12

      9

      -1 0 10

      0 1 1

      0 2 2

      1 2 3

      1 3 4

      2 2 3

      2 2 4

      6 10 11

      6 20 30

       

      Sample Output:

      2 0 0 0 0

      3 0 1 0 0 0 0 0 0

       

       


      Added by:Varun Jalan
      Date:2011-12-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Varun Jalan - ICPC Asia regionals, Amritapuri 2011









      SPOJ Problem Set ()

      10237. Goblin Wars

      Problem code: AMR11J

       

      The wizards and witches of Hogwarts School of Witchcraft found Prof. Binn's History of Magic lesson to be no less boring than you found your own history classes.  Recently Binns has been droning on about Goblin wars, and which goblin civilization fought which group of centaurs where etc etc.  The students of Hogwarts decided to use the new-fangled computer to figure out the outcome of all these wars instead of memorizing the results for their upcoming exams.  Can you help them?

       

      civilization fought which group of centaurs where etc etc.  The students of Hogwarts decided to use the new-fangled computer to figure out the outcome of all these wars instead of memorizing the results for their upcoming exams.  Can you help them?
      The magical world looks like a 2-D R*C grid. Initially there are many civilizations, each civilization occupying exactly one cell. A civilization is denoted by a lowercase letter in the grid. There are also certain cells that are uninhabitable (swamps, mountains, sinkholes etc.) - these cells are denoted by a '#' in the grid. All the other cells - to which the civilizations can move  - are represented by a '.' in the grid.
      A cell is said to be adjacent to another cell if they share the same edge - in other words, for a cell (x,y), cells (x-1, y), (x, y-1), (x+1, y), (x, y+1) are adjacent, provided they are within the boundaries of the grid.   Every year each civilization will expand to all unoccupied adjacent cells. If it is already inhabited by some other civilization, it just leaves the cell alone. It is possible that two or more civilizations may move into an unoccupied cell at the same time - this will lead to a battle between the civilizations and the cell will be marked with a '*'. Note that the civilizations fighting in a particular cell do not try to expand from that cell, but will continue to expand from other cells, if possible.
      Given the initial grid, output the final state of the grid after no further expansion by any civilization is possible.
      Input (STDIN):
      The first line contains T, the number of cases. This is followed by T test case blocks.
      Each test case contains two integers, R, C.
      This is followed by R lines containing a string of length C. The j-th letter in the i-th row describes the state of the cell in year 0.
      Each cell is either a
      1. '.' which represents an unoccupied cell
      2. '#' which represents a cell that cannot be occupied
      3. A civilization represented by a lowercase letter ('a' - 'z')
      Output (STDOUT):
      For each test case, print the final grid after no expansion is possible. Apart from the notations used in the input, use '*' to denote that a battle is being waged in that particular cell. 
      Print a blank line at the end of each case.
      Constraints:
      1 <= R, C <= 500
      1 <= T <= 5
      Time Limit:  3 s
      Memory Limit: 64 MB
      Sample Input:
      5
      3 5
      #####
      a...b
      #####
      3 4
      ####
      a..b
      ####
      3 3
      #c#
      a.b
      #d#
      3 3
      #c#
      ...
      a.b
      3 5
      .....
      .#.#.
      a...b
      Sample Output:
      #####
      aa*bb
      #####
      ####
      aabb
      ####
      #c#
      a*b
      #d#
      #c#
      acb
      a*b
      aa*bb
      a#.#
      aa*bb

      The magical world looks like a 2-D R*C grid. Initially there are many civilizations, each civilization occupying exactly one cell. A civilization is denoted by a lowercase letter in the grid. There are also certain cells that are uninhabitable (swamps, mountains, sinkholes etc.) - these cells are denoted by a '#' in the grid. All the other cells - to which the civilizations can move  - are represented by a '.' in the grid.

       

      A cell is said to be adjacent to another cell if they share the same edge - in other words, for a cell (x,y), cells (x-1, y), (x, y-1), (x+1, y), (x, y+1) are adjacent, provided they are within the boundaries of the grid.   Every year each civilization will expand to all unoccupied adjacent cells. If it is already inhabited by some other civilization, it just leaves the cell alone. It is possible that two or more civilizations may move into an unoccupied cell at the same time - this will lead to a battle between the civilizations and the cell will be marked with a '*'. Note that the civilizations fighting in a particular cell do not try to expand from that cell, but will continue to expand from other cells, if possible.

      Given the initial grid, output the final state of the grid after no further expansion by any civilization is possible.

       

      Input (STDIN):

      The first line contains T, the number of cases. This is followed by T test case blocks.

      Each test case contains two integers, R, C.

      This is followed by R lines containing a string of length C. The j-th letter in the i-th row describes the state of the cell in year 0.

      Each cell is either a

      1. '.' which represents an unoccupied cell

      2. '#' which represents a cell that cannot be occupied

      3. A civilization represented by a lowercase letter ('a' - 'z')

       

      Output (STDOUT):

      For each test case, print the final grid after no expansion is possible. Apart from the notations used in the input, use '*' to denote that a battle is being waged in that particular cell. 

      Print a blank line at the end of each case.

       

      Constraints:

      1 <= R, C <= 500

      1 <= T <= 5

       

      Sample Input:

      5

      3 5

      #####

      a...b

      #####

      3 4

      ####

      a..b

      ####

      3 3

      #c#

      a.b

      #d#

      3 3

      #c#

      ...

      a.b

      3 5

      .....

      .#.#.

      a...b

       

      Sample Output:

      #####

      aa*bb

      #####

       

      ####

      aabb

      ####

       

      #c#

      a*b

      #d#

       

      #c#

      acb

      a*b

       

      aa*bb

      a#.#b

      aa*bb

       

       


      Added by:Varun Jalan
      Date:2011-12-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Varun/Venkatesh/Pratik - ICPC Asia regionals, Amritapuri 2011









      SPOJ Problem Set (classical)

      10239. Between the Mountains

      Problem code: ACPC11B

       

      Did you try to ride a telepherique (cable car)? It is a lot of fun. Our company is trying to
      build a new telepherique line between two high mountains and you will be invited for a free
      ride. The trick to get your free ride is to help the company in building the telepherique line.
      The company wants to build two platforms, one on each mountain. The line will extend
      between these two platforms. The suitable points for holding a platform in each mountain
      were determined, and the altitudes of these points were reported.
      One of the talented engineers suggested that the company can save a lot of energy if the two
      stations have the same altitude or at least have altitudes which are as close to each other as
      possible. Your job is to select two points, one at each mountain, from those suitable points,
      so that the altitude difference between the two points is as little as possible.
      Input
      Your program will be tested on one or more test cases. The first line of the input will be a
      single integer T , the number of test cases (1 ≤ T ≤ 100). Follows 2T lines containing the
      test cases, each on a pair of lines.
      Each of the two lines in a case describe the altitudes of suitable points to build a platform
      on one mountain. Each line starts with an integer N , the number of reported altitudes
      (1 ≤ N ≤ 1, 000), followed by N integers, which represent the altitudes reported from this
      mountain. Any altitude value will be between 1 and 1, 000, 000, inclusive.
      Output
      For each test case, output, on a single line, a single number representing the minimum
      altitude difference between two suitable platform points, one at each mountain.

      Did you try to ride a telepherique (cable car)? It is a lot of fun. Our company is trying to build a new telepherique line between two high mountains and you will be invited for a free ride. The trick to get your free ride is to help the company in building the telepherique line.

      The company wants to build two platforms, one on each mountain. The line will extend between these two platforms. The suitable points for holding a platform in each mountain were determined, and the altitudes of these points were reported.

      One of the talented engineers suggested that the company can save a lot of energy if the two stations have the same altitude or at least have altitudes which are as close to each other as possible. Your job is to select two points, one at each mountain, from those suitable points, so that the altitude difference between the two points is as little as possible.

      Input

      Your program will be tested on one or more test cases. The first line of the input will be a single integer T , the number of test cases (1 ≤ T ≤ 100). Follows 2T lines containing the test cases, each on a pair of lines.

      Each of the two lines in a case describe the altitudes of suitable points to build a platform on one mountain. Each line starts with an integer N , the number of reported altitudes (1 ≤ N ≤ 1,000), followed by N integers, which represent the altitudes reported from this mountain. Any altitude value will be between 1 and 1,000,000, inclusive.

      Output

      For each test case, output, on a single line, a single number representing the minimum

      altitude difference between two suitable platform points, one at each mountain.

       

      Example

       

      Input:
      2
      8 1 3 5 7 9 7 3 1
      8 2 4 6 8 10 8 6 2
      8 2 3 5 10 9 3 2 1
      7 1 2 6 12 13 3 2
      
      Output:
      1
      0

      Added by:mohamedwahba
      Date:2011-12-15
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Arab Collegiate Programming Contest 2011









      SPOJ Problem Set ()

      10240. Circleland

      Problem code: ACPC11C

       

      You are visiting circleland, and you have long waited to visit their famous art exhibition.
      The exhibition has N rooms arranged in a cycle. In every room, there are some artistic
      pieces. The rooms are named R1 , R2 , ..., RN . There are also N corridors, named C1 , C2 ,
      ..., CN , of lengths L1 , L2 , ..., LN , respectively. Each corridor Ci connects the two rooms Ri
      and Ri+1 , except CN which connects RN and R1 . Thus, the whole exhibition forms a cycle.
      You can walk in both directions in every corridor.
      There is a single entrance to the exhibition in room R1 , but there are exits in every room.
      As there is nothing interesting to see in the corridors, you would like to spend the least effort
      walking through corridors in the exhibition. Compute the minimum total distance you need
      to walk in corridors such that you enter from the entrance, exit from any exit and visit all
      rooms.

       

      You are visiting circleland, and you have long waited to visit their famous art exhibition. The exhibition has N rooms arranged in a cycle. In every room, there are some artistic pieces. The rooms are named R1 , R2 , ..., RN . There are also N corridors, named C1 , C2 , ..., CN , of lengths L1 , L2 , ..., LN , respectively. Each corridor Ci connects the two rooms Ri and Ri+1 , except CN which connects RN and R1 . Thus, the whole exhibition forms a cycle. You can walk in both directions in every corridor. 

      There is a single entrance to the exhibition in room R1 , but there are exits in every room. As there is nothing interesting to see in the corridors, you would like to spend the least effort walking through corridors in the exhibition. Compute the minimum total distance you need to walk in corridors such that you enter from the entrance, exit from any exit and visit all rooms.

       

       Input

       

      Your program will be tested on one or more test cases. The first line of the input will be a single integer T , the number of test cases (1 ≤ T ≤ 100). Next T lines contain the test cases, each on a single line. 

      Each case starts with an integer N , the number of rooms in the exhibition (2 ≤ N ≤ 100, 000), followed by N numbers, the lengths of the corridors, L1 , L2 , ..., LN , in this order (1 ≤ Li ≤ 1,000,000).

      The sum of the lengths of all corridors will not exceed 1,000,000,000.

       

      Output

      For each test case, output, on a single line, a single number representing the minimum total distance you have to walk in corridors such that you visit all rooms.

       

      Example

      Input:
      2
      5 1 1 1 1 1
      7 100 15 20 42 33 15 24
      
      Output:
      4
      149

      Added by:mohamedwahba
      Date:2011-12-15
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Arab Collegiate Programming Contest 2011









      SPOJ Problem Set (classical)

      10242. Dice on a Board

      Problem code: ACPC11D

      You and your friends like to play chess and backgammon  every day.  But now you are bored of these games, and you would like to play a new game.  So you decided to make your own game, which will be played using a backgammon  die (singular of dice) on a board similar to the chess board, and it will be a single player game.

      <a target='_blank' title='ImageShack - Image And Video Hosting' href='http://imageshack.us/photo/my-images/266/imau.png/'><img src='http://img266.imageshack.us/img266/6522/imau.png' border='0'/></a>

      The game is played on a board of N rows and M columns.  Each cell is either empty or contains a number from 0 to 9, and  there  is a single die (a die with six faces containing the numbers from 1 to 6) placed in one of the empty cells (the borders of the bottom face is aligned to the

      axes of the board),  and your goal is to move it to a target  empty cell.

       

      The initial orientation of the die is defined by a string S which is a permutation of the digits from 1 to 6. Each digit represents  the number written  on a face of the die according to this order: right, left, back, front, top, bottom.  Moving the die is defined by the following rules:

       

      1. You can move the die from a cell to one of its four adjacent cells by flipping it on the corresponding face. For example, if the current orientation  of the die is 136425 and you will move it to the cell on its right,  you should flip the die on its right face and it will become the bottom  face in the right cell, so the orientation of the die will be 256431. (This is the example in the figure).

      2. Your score is initially  zero.  By moving the  die to another  cell, if the  number  on the bottom  face is the same as the number in the cell you just moved to, your score will be increased by the sum of these two numbers,  otherwise your score will be decreased by the sum of these two numbers.  Entering  the target  cell will not affect your score.

      3. You can not leave the board.

      4. Once you leave the starting  cell, you can not enter it again.

      5. Once you enter the target  cell, you can not leave it.

      6. You can not enter an empty cell, except the target  one.

       

      Given the board configuration, the starting  cell, the target cell and the die’s initial orientation, your task is to move the die from the starting  cell to the target  cell according the rules above, such that  you end up with the maximum  possible score.  Can you write a program  to help you?

       

      Input

       

      Your program  will be tested  on one or more test cases. The first line of the input  will be a single integer T , the number of test cases (1 ≤ T ≤ 200). After that  follow the specifications of T test  cases.

      Each  test  case is specified in N + 2 lines.  The  first line contains  two  integers  N  and  M (1 ≤ N, M  ≤ 10) representing  the  number  of rows and  number  of columns of the  board, respectively.  The second line contains the string S representing  the initial orientation  of the die in the starting  cell as described above.  Each line of the remaining  N  lines contains  M characters,  the j-th character  in the i-th line represents  the value of the j-th cell in the i-th row of the board.  Each character  will be one of the following values:

      1. '.' means an empty cell.

      2. 'S' means the starting  cell (which will appear  exactly once in the board).

      3. 'T' means the target  cell (which will appear  exactly once in the board).

      4. A digit from '0' to '9' means the value written  in this cell.

       

       

      Output

      For each test  case, output, on a single line, one of these values:

      1. "Impossible" if you can not reach the target  cell from the starting  cell.

      2. "Infinity" if there  is no limit  for your final score, and  you can increase it  with  no limit.

      3. Otherwise,  output the maximum score which you can get.

       

      Example

      Input:
      3
      4 4
      123456
      S789
      0987
      789.
      09.T
      3 6
      153462
      S16521
      .46324
      .....T
      4 4
      623451
      S6T.
      ....
      ....
      ....
      
      
      Output:
      Impossible
      Infinity
      12
      

      Added by:mohamedwahba
      Date:2011-12-16
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Arab Collegiate Programming Contest









      SPOJ Problem Set (classical)

      10264. Meteors

      Problem code: METEORS

      Byteotian Interstellar Union (BIU) has recently discovered a new planet in a nearby galaxy. The planet is unsuitable for colonisation due to strange meteor showers, which on the other hand make it an exceptionally interesting object of study.

      The member states of BIU have already placed space stations close to the planet's orbit. The stations' goal is to take samples of the rocks flying by. The BIU Commission has partitioned the orbit into sectors, numbered from to , where the sectors and are adjacent. In each sector there is a single space station, belonging to one of the member states.

      Each state has declared a number of meteor samples it intends to gather before the mission ends. Your task is to determine, for each state, when it can stop taking samples, based on the meter shower predictions for the years to come.

      Input

      The first line of the standard input gives two integers, and (), separated by a single space, that denote, respectively, the number of BIU member states and the number of sectors the orbit has been partitioned into.

      In the second line there are integers (), separated by single spaces, that denote the states owning stations in successive sectors.

      In the third line there are integers (), separated by single spaces, that denote the numbers of meteor samples that the successive states intend to gather.

      In the fourth line there is a single integer () that denotes the number of meteor showers predictions. The following lines specify the (predicted) meteor showers chronologically. The -th of these lines holds three integers , , (separated by single spaces), which denote that a meteor shower is expected in sectors (if ) or sectors (if ), which should provide each station in those sectors with meteor samples ().

      Output

      Your program should print lines on the standard output. The -th of them should contain a single integer , denoting the number of shower after which the stations belonging to the -th state are expected to gather at least samples, or the word NIE (Polish for no) if that state is not expected to gather enough samples in the foreseeable future.

      Example

      For the input data:

      3 5
      1 3 2 1 3
      10 5 7
      3
      4 2 4
      1 3 1
      3 5 2

      the correct result is:

      3
      NIE
      1

      Added by:Krzysztof Lewko
      Date:2011-12-20
      Time limit:1s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:XVIII POI 3rd stage









      SPOJ Problem Set (classical)

      10265. Subdivision of the kingdom

      Problem code: DIVIDEKR

      Byteasar, king of Byteotia, has finally decided to retire. He has two sons, however, and is unable to decide which one one of them should succeed him. Therefore he plans to split the kingdom into two halves, making each son a ruler.

      After the division, watchtowers have to be built along the roads connecting the halves. Obviously, building them will be costly, so ideally there should be as little roads between the halves as possible.

      Luckily, Byteotia consists of an even number of towns, connected by roads. Resulting from the division, each half-kingdom should contain half the towns. Each road connects (directly) two towns. The roads do not meet nor cross outside towns, though they can lead through flyovers or tunnels. Every two towns are directly connected by at most one road.

      Which exact towns should lie in which half of the kingdom is a matter of great importance. You may assume that the land outside the towns can be partitioned in such a way that the roads connecting towns lying in the same half will not cross the border. On the other hand, one watchtower has to be built by each road connecting towns from different halves.

      Task

      Write a programme that:

      • reads the descriptions of towns and the roads connecting them from the standard input,
      • determines such a partition of kingdom into halves that both the halves contain an equal number of towns and the number of roads connecting towns lying in different halves is minimum,
      • writes out the result to the standard output.

      If more than one optimum partition exists, your programme should pick one of them arbitrarily.

      Input

      The first line of the standard input contains two integers and , separated by a single space, denoting the number of towns and number of roads respectively, , , . The towns are numbered from to . Each of the following lines contains two integers separated by a single space. The line no. (for ) contains the numbers and , . These denote a road connecting and .

      Output

      Your programme should write out exactly one line to the standard output. It should contain integers separated by single spaces. These should be the numbers of towns belonging to the same half of the kingdom the town no. does, in an increasing order.

      Example

      For the input data:

      6 8
      1 2
      1 6
      2 3
      2 5
      2 6
      3 4
      4 5
      5 6
      

      the correct result is:

      1 2 6
      

      The dashed line in the figure shows the optimum partition, which requires building as little as watchtowers.


      Added by:Krzysztof Lewko
      Date:2011-12-20
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:XV POI 3rd stage









      SPOJ Problem Set (classical)

      10270. Temperature

      Problem code: TEMPERAT

      The Byteotian Institute of Meteorology (BIM) measures the air temperature daily. The measurement is done automatically, and its result immediately printed. Unfortunately, the ink in the printer has long dried out... The employees of BIM however realised the fact only recently, when the Byteotian Organisation for Meteorology (BOM) requested access to that data.

      An eager intern by the name of Byteasar saved the day, as he systematically noted down the temperatures reported by two domestic alcohol thermometers placed on the north and south outside wall of the BIM building. It was established decades ago by various BIM employees that the temperature reported by the thermometer on the south wall of the building is never lower than the actual temperature, while that reported by the thermometer on the north wall of the building is never higher than the actual temperature. Thus even though the exact temperatures for each day remain somewhat of a mystery, the range they were in is known at least.

      Fortunately for everyone involved (except Byteasar and you, perhaps), BOM does not require exact temperatures. They only want to know the longest period in which the temperature was not dropping (i.e. on each successive day it was no smaller than on the day before). In fact, the veteran head of BIM knows very well that BOM would like this period as long as possible. To whitewash the negligence he insists that Byteasar determines, based on his valuable notes, the longest period in which the temperature could have been not dropping. Now this is a task that Byteasar did not quite expect on his BIM internship, and he honestly has no idea how to tackle it. He asks you for help in writing a program that determines the longest such period.

      Input

      In the first line of the standard input there is one integer () that denotes the number of days for which Byteasar took notes on the temperature. The measurements from day are given in the line no. . Each of those lines holds two integers, and (). These denote, respectively, the minimum and maximum possible temperature on that particular day, as reported by the two thermometers.

      Output

      In the first and only line of the standard output your program should print a single integer, namely the maximum number of days for which the temperature in Byteotia could have been not dropping.

      Example

      For the input data:

      6
      6 10
      1 5
      4 8
      2 5
      6 8
      3 5

      the correct result is:

      4


      Added by:Krzysztof Lewko
      Date:2011-12-22
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:XVIII POI 2nd stage









      SPOJ Problem Set (classical)

      10283. ALL IZZ WELL

      Problem code: ALLIZWEL

      ALL IZZ WELL

       Problem Description:

                      Mr.ESP used to tell “ALL IZZ WELL” whenever he gets into any trouble.

      So his friends and the people around him used to laugh at him. But Mr.ESP is very

      strong in his belief. He believes that the term “ALL IZZ WELL” will make everything

      fine. Now your task is to ignore the story above and find whether there is a path in

      the given matrix which makes the sentence “ALL IZZ WELL”


      There is a path from any cell to all its neighbouring cells. A neighbour may share an edge or a corner.


      Input Specification:

                      The first line consists of an integer t representing the number of test cases.

      The first line of each test case consists of two integers R and C representing the number

      of rows and number of columns in the matrix. The description of the matrix follows.

      Output Specification:

                      For each test case print “YES” if there is a path which makes the sentence “ALLIZZWELL”.

      Else print “NO”.

      Note: Take care of 4th test case

      There is a new line after every test case in the input.


      Input constraints:

      t<=1000

      R<=100

      C<=100

      Sample Input:

      5

      3 6

      AWE.QX

      LLL.EO

      IZZWLL


      1 10

      ALLIZZWELL


      2 9

      A.L.Z.E..

      .L.I.W.L.


      3 3

      AEL

      LWZ

      LIZ


      1 10

      LLEWZZILLA

       

      Sample Output:

      YES

      YES

      NO

      NO

      YES


      Added by:cegprakash
      Date:2011-12-25
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10285. Why this kolaveri di

      Problem code: WTK


       

      WHY THIS KOLAVERI DI?

      Problem description:

                      The percentage of Soup boys in India is increasing day by day. These soup boys finally got fed up with girls cheating on them. N girls are randomly chosen and they are now under investigation. Somehow the soup boys found out that, if there are N girls, then the ratio of the number of girls who cheat to the total number of girls is (N-1)/N. As these soup boys are very angry, they wanted to punish all the cheaters. But, obviously, during investigation all the girls claimed to be only one that is good. Soup boys had a plan to find the real good girl. They asked all the girls to form a circle. Then their eyes are tied.  Now the leader of the soup boys goes into the middle of circle, removes the first girl from the group and then turns one step clockwise. Then leaves one girl and removes the second one. Then he leaves two girls and removes the third one and so on. The girl who is left at the end is declared as a good one and is free to go. The rest will await their surprise punishment. Being in the position of a good intelligent girl, you initially want to stand in the position which will get you free. Find such a position.

      Input Specification:

      The first line contains an integer T denoting the number of test cases. Then T lines follow, each with one integer N, the number of girls soup boys will choose from.

      Output Specification:

      For each test case output the position the good girl has to stand initially so that will be free at the end.

      Input Constraints:

      t<=250

      n<=100000

      Sample Input:

      3

      2

      1

      5

      Sample Output:

      2

      1

      4

      Explanation of third test case:

      There are 5 girls arranged in a circle as 1, 2, 3  4, 5. Girl 1 stands right next to 5. Girl 1 is removed first. Then 2 is skipped and 3 removed. The remaining girls will stand in the order 4,5,2. 4 and 5 are skipped and 2 removed. Only 4 and 5 are left and we have to skip three girls this time. We skip 4-5-4 and finally 5 is removed. So the intelligent, good girl should stand initially at 4th position.


      Added by:cegprakash
      Date:2011-12-25
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10286. DOTA HEROES

      Problem code: DOTAA



      DOTA HEROES

       

      Problem Description:

                      Defence Of The Ancients(DOTA) is one of the most addictive online multiplayer games. There are n heroes in our team and our motto is to conquer the opponent’s empire. To safeguard their empire, the opponents had constructed m towers on the path. If one or more heroes get into the sight of a tower, then the tower does D amount of damage to one of those heroes at that instant (i.e. one of the heroes’ health decreases by D). Any hero will die if his health H <=0.  Once a tower attacks one of the heroes at that instant, all of those at that instant get out of its sight. Find whether all of the heroes in our team can reach the opponent’s empire alive.

       

      Input Specification:

      The first line consists of one integer t representing the number of test cases. For each test case, the first line consists of three integers n, m and D, the number of heroes, number of towers and the amount of Damage respectively. The next n lines consist of an integer representing the health of respective hero.

      Output Specification:

      Just a word “YES” if we can reach the opponent’s empire alive, else “NO”.

      Input Constraints:

      1<=t<=500

      1<=n<=500

      1<=m<=n

      1<=D,H<=20000


      Sample Input:

      3

      6 3 400

      500

      500

      500

      500

      500

      500

       

      6 5 400

      800

      800

      801

      200

      200

      200

       

      6 3 400

      401

      401

      400

      200

      400

      200


      Sample Output:

      YES

      NO 

      NO

       

      Explanation of test case 1:

      One of the possible solutions is
      First, three of the heroes can goes together. One of them receives 400 damage from the first tower and all of them cross it. Then while crossing the next tower, one of the heroes who is at 500 health gets 400 damage and all of them cross it. Then the third hero receives the damage when crossing the last tower. Similarly the other 3 heroes can reach the opponent’s base together without dying.

       


      Added by:cegprakash
      Date:2011-12-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10292. Shell game

      Problem code: SHELL

      Your program is to play the traditional "shell" game (http://en.wikipedia.org/wiki/Shell_game). The game is played as follows:

      There is a person called an operator; he/she has 3 identical, non-transparent hollow objects - shells, and a metal ball, which he/she places under one of these objects. Then, the operator quickly swaps pairs of shells several times; if shells at positions A and B are swapped, and the ball is under the shell at position A, it moves under the shell at position B. In the end, you have to guess which shell the ball is under.

      The shells are identical, and positions mean immediate position that you see (left will always denote the leftmost shell, not the shell that was leftmost in the beginning).

      Input

      The first line of input contains one string - "left", "center" or "right", denoting the position of the shell the ball is under in the beginning. The second line contains an integer N<=10, denoting the number of swaps. N lines follow, all of them contain 2 strings - positions of 2 shells which are swapped.

      Output

      Output position of the shell the ball is under after all swaps are performed.

      Warning

      Testing simulates the exact progress of an actual game! There are 10 testcases; in the last one only, N=10. You're likely to get a WA on this last test case, even if your program seems correct. Remember, it's like an actual game!

      Example

      Input:
      
      left
      2
      left right
      right center

      Output:


      center
      Explanation:
      in the beginning, the ball is under the left shell
      after swap 1, it's under the right shell
      after swap 2, it's under the center shell

      Added by:Jakub ©afin
      Date:2011-12-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:people.ksp.sk/~acm









      SPOJ Problem Set ()

      10293. FANCY NUMBERS

      Problem code: FANCY



      FANCY NUMBERS
       

      Girls usually give only missed calls to their boyfriends and they want them to call back. These boys are now busy with their engineering subjects and cannot remember all girl friends’ mobile number. Because of this, girls make it easy for them by having fancy mobile numbers. A fancy mobile number may contain many continuous digits in it.

      For example 9994442200 is a fancy mobile number because the boy can remember simply as triple nine, triple four, double two and double zero. As they are engineering students they do think different. One of the engineering students can spell the above number as double nine, nine, four, double four, two, two, double zero.

      The number 100 has only 2 possibilities as it can be spelt as either one, zero, zero (or) one, double zero

      Given a mobile number find the number of possibilities that the number can be remembered.


      Input Specification:

      The first line consists of an integer t denoting the number of test cases. Each test case consists of a mobile number of length <= 30 digits.

      Output Specification:

      For each test case output the number of possibilities the number can be remembered.

      Input Constraints: 1<=t<=100000
      Sample Input:

      3

      100

      12345

      11112


      Sample Output:

      2

      1

      8

      WARNING:  Huge data set! Make your I/O optimizations.

       


      Added by:cegprakash
      Date:2011-12-26
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10301. A jumpy cycle

      Problem code: JUMPY

      A cycle is a connected undirected graph with n vertices of degree 2. (Special cases: The cycle for n = 2 is a graph with two vertices and two parallel edges between them. For n = 1 the cycle is a graph with a single vertex and a loop. In all cases, you can imagine the cycle as a circle passing through n locations.)

      The distance d of two vertices is the number of edges on the shortest path that connects them.

      A labelling of a cycle is a function f that assigns a positive integer to each of its vertices.

      Given a labelling, we may pick a starting vertex and direction along the cycle and write down the labels in the order in which we encounter them. The n-tuple obtained in this way is called a label list.

      There may be multiple label lists corresponding to a single labelling. For example, the label lists (3,8,25,14,17) and (25,8,3,17,14) may come from the same labelling.

      A labelling is called jumpy if it has the following properties:

      • No two labels are equal.
      • For each pair of distinct vertices u,v the greatest common divisor of f(u) and f(v) is at most d(u,v).

      (In other words, neighboring vertices must have relatively prime labels, vertices at distance 2 may only have 2 as the common divisor of their labels, etc.)

      For example, a cycle with the label list (3,8,25,14,17) is a jumpy cycle.

      The upper bound of a labelling is the largest integer it uses.

      Given two distinct label lists of a given cycle, look at the first position where they differ. The one with the smaller value on this position is lexicographically smaller.

      Task

      Given is the number of vertices n. Find a jumpy labelling of a cycle with n vertices with the smallest possible upper bound. If there are multiple such labellings, pick the one that can produce the lexicographically smallest label list.

       

      Input

      Ignore the input.The file's empty, anyway.

      Output

      For each n from 1 to 20 output a single line with a sequence of n positive integers: the lexicographically smallest label list that determines a jumpy labelling with the smallest possible upper bound. Separate the integers by single spaces. (Do not print a space after the last integer on a line.)

       

      Example

      Input:
      
      
      Output:
      
      1
      ... and 19 more lines ...

      A cycle is a connected undirected graph with n vertices of degree 2. (Special cases: The cycle for n = 2 is a graph with two vertices and two parallel edges between them. For n = 1 the cycle is a graph with a single vertex and a loop. In all cases, you can imagine the cycle as a circle passing through n locations.)

      The distance d of two vertices is the number of edges on the shortest path that connects them.

      A labelling of a cycle is a function f that assigns a positive integer to each of its vertices.

      Given a labelling, we may pick a starting vertex and direction along the cycle and write down the labels in the order in which we encounter them. The n-tuple obtained in this way is called a label list.

      There may be multiple label lists corresponding to a single labelling. For example, the label lists (3,8,25,14,17) and (25,8,3,17,14) may come from the same labelling.

      A labelling is called jumpy if it has the following properties:

      • No two labels are equal.
      • For each pair of distinct vertices u,v the greatest common divisor of f(u) and f(v) is at most d(u,v).

      (In other words, neighboring vertices must have relatively prime labels, vertices at distance 2 may only have 2 as the common divisor of their labels, etc.)

      For example, a cycle with the label list (3,8,25,14,17) is a jumpy cycle.

      The upper bound of a labelling is the largest integer it uses.

      Given two distinct label lists of a given cycle, look at the first position where they differ. The one with the smaller value on this position is lexicographically smaller.

      Task

      Given is the number of vertices n. Find a jumpy labelling of a cycle with n vertices with the smallest possible upper bound. If there are multiple such labellings, pick the one that can produce the lexicographically smallest label list.


      Added by:Jakub ©afin
      Date:2011-12-27
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:people.ksp.sk/~acm









      SPOJ Problem Set (classical)

      10312. Concave quadrilaterals

      Problem code: CONCAVE


      Given is a grid consisting of r rows by c columns of grid points.

      Count the number of ways in which it is possible to draw a strictly concave quadrilateral with vertices in four of the given grid points.

      (A quadrilateral is strictly concave if and only if one of its two diagonals contains a point that is strictly outside the quadrilateral. Shifted and/or rotated copies of the same quadrilateral count as distinct ways of drawing it.)

      Input specification

      The input has a single line with the two integers r and c.

      You may assume that the total number of grid points is at most 3000.

      Output specification

      Output a single line with a single integer: the number of concave quadrilaterals with vertices on the grid.

      Examples

      input
      2 10
      
      output
      0
      
      input
      3 3
      
      output
      24
      


      Added by:Jakub ©afin
      Date:2011-12-30
      Time limit:1s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:people.ksp.sk/~acm, ACM ICPC selection round of Comenius University









      SPOJ Problem Set (classical)

      10328. TRIVIADOR

      Problem code: TWOKINGS


      TRIVIADOR

      Triviador is a war between two Kings. A king can attack an enemy region at each step. When a king attacks a region, he conquers all the enemy regions connected to it(not just the immediate ones). All the 8 regions around any region are connected to it. The kings get alternate chances to attack. King1 gets the chance to attack first. Assume both kings are intelligent and find who will conquer the whole territory at the end of the war. It can be proved that one of the Kings can win for sure if he is intelligent!

       

      Input Specification:

      The first line is an integer t, denotes the number of test cases. In each test case the first line consists of two integers denoting the number of rows and columns in the territory (each cell is a region). Then the description of each cell follows. Every region contains a character ‘X’ if it is owned by king1 or ‘O’ otherwise.


      Output Specification:
      For each test case output the result in a single line ‘X’ if king1 wins or ‘O’ if king2 wins.

       

      Input Constraints:

      T<=100

      1<=rows,columns<=10

       

      Sample input:


      3

      3 3

      XOX

      XXX

      XOX

       

      3 5

      XXXXX

      XXXOO

      XXXOO

       

      4 4

      XXXX

      OOOO

      XXXX

      OOOO


      Sample Output:

      O

      X

      X

       

      Explanation of testcase 1 and 2:

      Case 1: King1 has two possibilities to attack. But after attacking any of them, he will lose surely when king2 attacks back.

      Case 2: King1 can attack any of the four enemy positions. He conquers all the connected enemy positions. So this is a one step victory.


      Try the 1D version of this problem : http://spoj.com/problems/QWERTY04/
      Try the 3D version of this problem : http://spoj.com/KOPC13/problems/CONQUER/


      Added by:cegprakash
      Date:2012-01-02
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set ()

      10334. SOLDIERS

      Problem code: SOLDIERS


      Soldiers

      Problem Statement:

      How many maximum number of soldiers(chess) can be placed in a mxn board so that none of them attack the other.

      Input Specification:

      The first line is an integer t, denoting the number of test cases. Each test case is a single line with two integers m and n the number of rows and columns in the board.

      Output Specification:

      For each test case print the maximum number of soldiers that can be placed in a separate line.

      Input Constraints:

      1<=t<=100

      1<=m<=10^30

      1<=n<=10^30


      Sample Input:

      4

      10 10

      3 3

      5 5

      3 6

       

      Sample Output:

      50

      6

      15

      12


      Added by:cegprakash
      Date:2012-01-03
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10346. Streets of distortion

      Problem code: DISTO

      One day, Eloy the byte was walking at the square (1,1) of the big Matrix-shaped city... He was planning to go visit his mom at the square (N,N) when some meteors crashed at the city! Every byte doesn't know what to do... Eloy rapidly discovers that the meteors cause a distortion, multiplying by his hit expansion the streets affected... Eloy knows the matrix and what is contained in it and know the places where the meteor crash, given this, determine the resultant matrix of the city.

       

      Additional information: Every street in the initial matrix is filled with ASCII characters from '!' to '}' (from 33 to 125 in ASCII numbers).

      The hit expansion for the meteor starts with 5, as it expands will decrease by 1 until arrives to 1, this value will multiply the value of the matrix. This is a example of a hit expansion, (the meteor crashed at the position (3,3))

      Meteor expansion

       

      So, in the example of 'c' (position (3,3)) (99 in ASCII) you should multiply it by 5 (495). But in the magic digital world where Eloy lives, this number will be an ASCII symbol. More information on the output.

       

      INPUT:

      First line of input contains two integers N and K

      N Contains the size of the matrix (the matrix will be N^2) (3<=N<=500)

      K Contains the number of meteors that crashed in the city. (1<=K<=50)

      The next N lines contains N characters separated by a single space, this will be the content of the matrix at position (I,J)

      The next K lines contains two integers (Ki and Kj), (Rows,Columns) this two coordinates reveal the position where meteor Kn crashed.

       

      OUTPUT:

      The output must be the resultant matrix, so, N lines with N characters separated by a single space, as the distortion can get out of range some integers, you must output the ascii value of the number modulo 93 plus 33. That will decrease the number to a range from 33 to 125 as much. This final number must be turned into a character, then print it.

       

      SAMPLE:

      INPUT:

      3 1

      a a a

      b b b

      c c c

      2 2

       

      OUTPUT:

      1 1 1

      5 : 5

      9 9 9

       

      Because:

       

      The meteor crash at (2,2) having a starting value of 98, the value in the matrix is modified to 490, then transformed to the range 33~125 giving a result of 58, in ASCII value, 58 represents the “:”.

      later, the hit expansion moves to EVERY ADJACENT cell (that means diagonals too) modifying the values inside of it.

       

      ANOTHER SAMPLE DATA:

      INPUT:

      6 1
      a a a a a a
      b b b b b b
      c c c c c c
      d d d d d d
      e e e e e e
      f f f f f f
      1 6

      OUTPUT:

      % % ) - 1 5
      & & + 0 5 5
      ' ' - 3 3 3
      ( ( / / / /
      ) ) ) ) ) )
      * * * * * *

      Please have in consideration that if 2 meteors collide and affects the same zone (cell), the zone with the GREATEST value of modification should be modified.


      Added by:David Moran
      Date:2012-01-06
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      10354. Count Strings

      Problem code: CTSTRING

       

      A regular expression is used to describe a set of strings. For this problem the alphabet is limited to 'a' and 'b'. R is a regular expression if:
      1) R is "a" or "b"
      2) R is of the form "(R1R2)" where R1 and R2 are regular expressions
      3) R is of the form "(R1|R2)" where R1 and R2 are regular expressions
      4) R is of the form "(R1*)" where R1 is a regular expression.
      The set of strings recognised by R are as follows:
      1) If R is "a", then the set of strings recognised = {a}
      2) If R is "b", then the set of strings recognised = {b}
      3) if R is of the form "(R1R2)" then the set of strings recognised = all strings which can be obtained by a concatenation of strings s1 and s2 where s1 is recognised by R1 and s2 by R2.
      4) if R is of the form "(R1|R2)" then the set of strings recognised = union of the set of strings recognised by R1 and R2.
      5) If R is of the form "(R1*)" then the the strings recognised are the empty string and the concatenation of an arbitrary number of copies of any string recognised by R1.
      Given a regular expression and an integer L, you need to count how many strings of length L are recognized by it.
      Input:
      The first line contains the number of test cases T. T test cases follow. 
      Each test case contains a regular expression R and an integer L.
      Output:
      Output T lines one corresponding to each test case containing the required answer for the corresponding test case. As the answers can be very big, output them modulo 1000000007.
      Constraints:
      1 <= T <= 50
      1 <= length(R) <= 100
      1 <= L <= 10^9
      You are guaranteed that R will conform to the definition provided above.
      Sample Input:
      3
      ((ab)|(ba)) 2
      ((a|b)*) 5
      ((a*)(b(a*))) 100
      Sample Output:
      2
      32
      100
      Explanation:
      For the first case, the only strings recognized are "ab" and "ba".
      For the second case, the regex recognizes any string containing only a's and b's. So the number of strings of length 5 recognized by it is 2^5 = 32.
      For the third case, the regex recognizes any string having one b, preceeded and followed by any number of a's. Clearly, there are 100 strings of length 100 which have a single b in them.

       

      A regular expression is used to describe a set of strings. For this problem the alphabet is limited to 'a' and 'b'. R is a regular expression if:

      1) R is "a" or "b"

      2) R is of the form "(R1R2)" where R1 and R2 are regular expressions

      3) R is of the form "(R1|R2)" where R1 and R2 are regular expressions

      4) R is of the form "(R1*)" where R1 is a regular expression.

       

      The set of strings recognised by R are as follows:

      1) If R is "a", then the set of strings recognised = {a}

      2) If R is "b", then the set of strings recognised = {b}

      3) if R is of the form "(R1R2)" then the set of strings recognised = all strings which can be obtained by a concatenation of strings s1 and s2 where s1 is recognised by R1 and s2 by R2.

      4) if R is of the form "(R1|R2)" then the set of strings recognised = union of the set of strings recognised by R1 and R2.

      5) If R is of the form "(R1*)" then the the strings recognised are the empty string and the concatenation of an arbitrary number of copies of any string recognised by R1.

       

      Given a regular expression and an integer L, you need to count how many strings of length L are recognized by it.

       

      Input:

      The first line contains the number of test cases T. T test cases follow. 

      Each test case contains a regular expression R and an integer L.

       

      Output:

      Output T lines one corresponding to each test case containing the required answer for the corresponding test case. As the answers can be very big, output them modulo 1000000007.

       

      Constraints:

      1 <= T <= 50

      1 <= length(R) <= 100

      1 <= L <= 10^9

      You are guaranteed that R will conform to the definition provided above.

      All inputs will be randomly generated.

       

      Sample Input:

      3

      ((ab)|(ba)) 2

      ((a|b)*) 5

      ((a*)(b(a*))) 100

       

      Sample Output:

      2

      32

      100

       

      Explanation:

      For the first case, the only strings recognized are "ab" and "ba".

      For the second case, the regex recognizes any string containing only a's and b's. So the number of strings of length 5 recognized by it is 2^5 = 32.

      For the third case, the regex recognizes any string having one b, preceeded and followed by any number of a's. Clearly, there are 100 strings of length 100 which have a single b in them.

       

       


      Added by:Varun Jalan
      Date:2012-01-09
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint 2 - InterviewStreet Contest









      SPOJ Problem Set (classical)

      10355. Coin Tosses

      Problem code: COINTOSS

       

      You have an unbiased coin which you want to keep tossing till you get N consecutive heads. You've already tossed the coin M times already and surprisingly, all tosses resulted in heads. What is the expected number of tosses needed till you get N consecutive heads?
      For example, if N = 2 and M = 0. You need to keep tossing the coin till you get 2 consecutive heads. It is not hard to show that on an average, 6 coin tosses are needed.
      As another example, if N = 2 and M = 1. You need 2 consecutive heads and have already got 1. In your first toss, if you get get a heads, you are done. Otherwise, you need to keep tossing the coin till you get 2 consecutive heads. The expected number of coin tosses is thus 1 + (0.5 * 0 + 0.5 * 6) = 4.0
      Input:
      The first line contains the number of cases T. Each of the next T lines contains two numbers N and M.
      Output:
      Output T lines containing the answer for the corresponding test case. Print the answer rounded to exactly 2 decimal places.
      Constraints:
      1 <= T <= 100
      1 <= N <= 1000
      0 <= M <= N
      Sample Input:
      4
      2 0
      2 1
      3 3
      3 2
      Sample Output:
      6.00
      4.00
      0.00
      8.00
      Explanation:
      The first two samples are explained above. For the third case, you already have got 3 heads, so you do not need any more tosses.

       

      You have an unbiased coin which you want to keep tossing till you get N consecutive heads. You've already tossed the coin M times already and surprisingly, all tosses resulted in heads. What is the expected number of tosses needed till you get N consecutive heads?

       

      For example, if N = 2 and M = 0. You need to keep tossing the coin till you get 2 consecutive heads. It is not hard to show that on an average, 6 coin tosses are needed.

       

      As another example, if N = 2 and M = 1. You need 2 consecutive heads and have already got 1. In your first toss, if you get get a heads, you are done. Otherwise, you need to keep tossing the coin till you get 2 consecutive heads. The expected number of coin tosses is thus 1 + (0.5 * 0 + 0.5 * 6) = 4.0

       

      Input:

      The first line contains the number of cases T. Each of the next T lines contains two numbers N and M.

       

      Output:

      Output T lines containing the answer for the corresponding test case. Print the answer rounded to exactly 2 decimal places.

       

      Constraints:

      1 <= T <= 100

      1 <= N <= 1000

      0 <= M <= N

       

      Sample Input:

      4

      2 0

      2 1

      3 3

      3 2

       

      Sample Output:

      6.00

      4.00

      0.00

      8.00

       

      Explanation:

      The first two samples are explained above. For the third case, you already have got 3 heads, so you do not need any more tosses.

       

       


      Added by:Varun Jalan
      Date:2012-01-09
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem used for CodeSprint 2 - InterviewStreet Contest









      SPOJ Problem Set (classical)

      10366. Play with Dates

      Problem code: CODEIT03


      Play with dates

      Problem Statement:

      Given the date, month and year, find the day.

      Input Specification:

      The first line consists of an integer t, the number of test cases. Then for each test case there are three integers the date, month and year.

      Output Specification:

      For each test case print the day in words in a separate line(The first character should be caps followed by small letters).

      Input Constraints:

      1<=t<=100

      Date/month/year >= 11/1/2012

      Date/month/year<=31/12/3000

      The given date will always be a valid date

      Sample Input:

      3

      11 1 2012

      12 1 2012

      13 1 2012

      Sample Output:

      Wednesday

      Thursday

      Friday


      Added by:cegprakash
      Date:2012-01-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10376. String Factorization!

      Problem code: ABA12B

      Jaiganesh and Siddharth were discussing about integer factorization. Suddenly Jai, who always thinks differently, thought, when it is possible to factorize numbers, why not factorize strings? Siddharth argued that it is impossible! So, now Jai wants to prove to Sid that it is possible for all strings. He decides to write a program that when given a string as input will factorize it. He then realised that there are many ways to factorize a string. So he decided to write a program that will maximize the sum of powers of the factors.

       

      Jai defined the nth power of a string as same string repeated n times. For example, (abc) ^ 2 = abcabc, and (abc) ^ 4 = abcabcabcabc.

       

      So, now this is what you have to do. Given a string as input, factorize the string such that the sum of powers is maximum and print that value of sum. An additional constraint is that the string should be factorized such that the power of each factor is always even. It is guaranteed that such a solution will always exist.

      Input

      The first line of input consists of C, the number of test cases. Then C lines follow each containing a string s, the length of which is always even.

      1 < |s| < 100000

      1 < C < 50

      Output

      The output consists of a single line for each test case, denoting the maximum sum of even powers that can be obtained.

      Example

      Input:
      1
      abcabcababababacac
      
      Output:
      8

      Explanation of test case: 

      The string can be factorized as (abc) ^ 2 * (ab) ^ 4 * (ac) ^ 2.

      The sum of powers is 2 + 4 + 2 = 8.


      Added by:Kashyap Krishnakumar
      Date:2012-01-10
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      10377. project groups

      Problem code: MECGROUP

      HOD of CSE Dept. of MMMEC, asked the students to form the groups for their final year project.

      He said that there will be t students per team and there will be atleast 4 boys and atleast 1 girl per group.

      A curious student Rajesh want to know the total number of ways by which the groups can be made.

      Because he is busy in forming his group so you, write a program to find the total ways and help him.

      Input

      First line contains an integer n which itself indicates number of test cases.

      Each test case comprises of three space separated integers "B G t" . Where B denotes numer of boys ,G denotes number of girls in the class. And t denotes number of students in a group.

      Constraints:

      1<=n<=20

      4 <= B <=30

      1<=G<=30

      5<=t<=B+G

      Output

       

      For each test case print total number of ways per line.

      Example

      Input:
      2
      4 1 5
      30 30 20
      Output:
      1
      4191318957352590

      Added by:bristy
      Date:2012-01-10
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict JAVA NODEJS PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:own









      SPOJ Problem Set (classical)

      10380. prayatna PR

      Problem code: CAM5


       

      help the Prayatna pr team
      Well, the annual technical symposium of Department of Computer Technology is around the corner. All that we need, to make it a grand success is Publicity among the peer groups ( ofCourse the sponsors too :P ). We dicided to share the job between the student groups. As per the plan we decided to meet people in person and influence them to attend Prayatna. But to meet them we have to go to various student groups. To do so, we had to cut our classes. But being studious ( ahem.. else just a BrutForce will pass ;) ) students refused to cut more classes. Instead of meeting every one in person we decided to meet few people such that the person to whom we pass the news will spread it to all his friends. And those friends will pass it to other friends and so on. Your task is to find the number of people to be met by the organizers to spread the news. 

       

                  help the Prayatna pr team

       

      Well, the annual technical symposium of Department of Computer Technology is around the corner. All that we need, to make it a grand success is Publicity among the peer groups ( ofCourse the sponsors too :P ). We dicided to share the job between the student groups. As per the plan we decided to meet people in person and influence them to attend Prayatna. But to meet them we have to go to various student groups. To do so, we had to cut our classes. But being studious. students refused to cut more classes. Instead of meeting every one in person we decided to meet few people such that the person to whom we pass the news will spread it to all his friends. And those friends will pass it to other friends and so on. Your task is to find the number of people to be met by the organizers to spread the news. 

       

      caution: large I/O

      Input

       

      First line of input is 't' - Test cases. Follwed by N, the number of peers in the testcase ( 0 to N-1 ). followed by the no.of friend description 'e'. Following are 'e' descriptions of type  

      " a b " denoting 'a' friends with 'b' . if 'a' is friends with 'b' then 'b' is firends with 'a'.

       

      Output

      Output contains t line, the number of people, the organizers have to meet in person for each test case.

      Example

      Input:
      2

      4
      2
      0 1
      1 2


      3
      0

      Output:
      2
      3
      Test case Expalained: 

      case 1 : 0 is friends with 1; 1 is friends with 2 ; so if we pass the news to 0 & 3 , news will pass it to the entire N peers
      case 2 : no one is friends with any one. So we have to meet every one in person.
      Constraints: 

      t=10
      2 <= N <= 100000
      0 <= e <= N/2

      Added by:karthikeyan
      Date:2012-01-11
      Time limit:3s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      10381. Search in the dictionary!

      Problem code: DICT


          Eloy the byte is helping his son, Marcos the little one, with the homework, which consists on: Given one or more words you should search in the dictionary which word contains the proper prefix of the word given, for example
          set is a prefix of setter, but also of setting.
          Now, neither Eloy nor Marcos wants to search the words in the dictionary (they just won’t do it)… Marcos will give you the words in the dictionary and the words to find the prefix of… You should make a program that given this, output the list of words that contains as a prefix the word given, Marcos can make mistakes sometimes, so, be careful! Marcos won’t always be telling the real prefixes all the time, in addition, sometimes Marcos can repeat the same word (while reading the dictionary), in this case, the word should be treated as it was mentioned just one time.

          INPUT:
          The input will consist in an integer N (1<=N<=25.000), next, N lines will follow containing a single word (maximum of 20 characters (all lowercase letters)), after that, there will be an integer K (1<=K<=22.000) containing the number of words to look in the dictionary, then, K lines containing the prefix-word.

          OUTPUT:
          The output will consist in displaying the words that are composed from the word given, you should output “Case #i:” where i is the i-th case, then, at the next line, output the list of the composed words (lexicographical-ordered), if there is none, you should output “No match.”

      SAMPLE DATA:

      INPUT:

      5

      set

      lol

      setter

      setting

      settings

      2

      set

      happy

      OUTPUT:

      Case #1:

      setter

      setting

      settings

      Case #2:

      No match.


      Added by:David Moran
      Date:2012-01-12
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      10394. Buying Apples!

      Problem code: ABA12C

      Harish went to a supermarket to buy exactly ‘k’ kilograms apples for his ‘n’ friends. The supermarket was really weird. The pricing of items was very different. He went to the Apples section and enquired about the prices. The salesman gave him a card in which he found that the prices of apples were not per kg. The apples were packed into covers, each containing ‘x’ kg of apples, x > 0 and ‘x’ is an integer. An ‘x’ kg packet would be valued at ‘y’ rupees. So, the placard contained a table with an entry ‘y’ denoting the price of an ‘x’ kg packet. If ‘y’ is -1 it means that the corresponding packet is not available. Now as apples are available only in packets, he decides to buy atmost ‘n’ packets for his ‘n’ friends i.e he will not buy more than n packets of apples.

      Harish likes his friends a lot and so he does not want to disappoint his friends. So now, he will tell you how many friends he has and you have to tell him the minimum amount of money he has to spend for his friends.

      Input

      The first line of input will contain the number of test cases, C.

      Each test case will contain two lines.

      The first line containing N and K, the number of friends he has and the amount of Apples in kilograms which he should buy.

      The second line contains K space separated integers in which the ith integer specifies the price of a ‘i’kg apple packet. A value of -1 denotes that the corresponding packet is unavailable.

      0 < N <= 100

      0 < K <= 100

      0 < price <= 1000

      Output

      The output for each test case should be a single line containing the minimum amount of money he has to spend for his friends. Print -1 if it is not possible for him to satisfy his friends.

      Sample I/O:

      Input:

      2

      3 5

      -1 -1 4 5 -1

      5 5

      1 2 3 4 5

      Output:

      -1

      5

      Explanation of test cases:

      1) As there are only 3 and 4kg packets in the shop, he will not be able to satisfy his friends as he would not be able to buy exactly 5kg of apples.

      2) He can buy five 1kg packet as he has to buy 5 kg. So the min money he should spend is 5.


      Added by:Kashyap Krishnakumar
      Date:2012-01-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      10395. Sum of divisors!

      Problem code: ABA12D

      Note: 
      If you really want to learn something by solving this problem, don't hard code! 
      There is a nice logic behind this!

      ---

      Kartheeswaran was recently reading an article on perfect numbers, whose sum of divisors equals twice the number. He was intrigued by them and decided to generate them but to his disappointment they turned out to be quite rare. So he decided to look out for a different property related to sum of divisors. What is more interesting than a number being a prime? So he decided to look out for numbers whose sum of divisors is a prime number and he was the inventor of these special numbers he gave them the name K-numbers.
      Given a range [A,B] you are expected to find the number of K-numbers in this range.

      Input

      The first line of input indicates the number of test cases T.
      Then in the following T lines there will be a pair of integers A and B.

      Output

      Output T lines each containing a single integer ‘c’ which denotes the number of K-numbers which lie in the interval [A,B] inclusive of the end points.
      Constraints:
      1<=T<=10000
      1<=A<=B<=10^6

      Example

      Input:
      2
      1 5
      9 10
      Output:
      2
      1
      Explanation of sample case:
      1) In the range [1,5] the K-numbers are 2 and 4 because
      Divisors of 2 are 1 and 2 which sum up to 3, which is a prime.
      Divisors of 4 are 1,2 and 4 which sum up to 7, which is a prime.
       
      2) The K-number in the range [9,10] is 9.

      Added by:Kashyap Krishnakumar
      Date:2012-01-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PYTH 3.2.3 n
      Resource:Own problem









      SPOJ Problem Set (classical)

      10399. Conga line

      Problem code: CONGA

      Conga is a traditional dance in which people make a line, grab each other by the waist and start dancing around.

      You are at a party and your favorite Conga song starts playing. Since you want to make the most of it, you'd like to organize everybody and start dancing as soon as possible.

      The dance floor is modeled as an infinite straight line with people standing on positive integer coordinates. There is at most one person at each point. Every second, a person can move one unit to the left or one unit to the right, as long as no one else is standing there. However, since it's a crazy party and people are already drunk, at most one person can move every second (in other words, no two people can move simultaneously).

      Nobody will start dancing until everybody is organized in a perfect line. You want to find the minimum amount of time it takes to start dancing, i.e. the time it takes to make people stand in such a way that there are no empty spaces between them.

      For example, imagine there are 4 people at the party, standing at positions 2, 4, 5 and 8:

      Conga line

      In this case, it takes at least 3 seconds to form the Conga line:

      • On second 1, the person standing at position 2 moves to position 3.
      • On second 2, the person standing at position 8 moves to position 7.
      • On second 3, the person standing at position 7 moves to position 6.
      • After three seconds, people are standing on positions 3, 4, 5, and 6 and they can start dancing!

      Start dancing

      Input

      The input contains several test cases.

      The first line of each case contains a single integer number n, the number of people in the party (1 ≤ n ≤ 106). The next line contains n distinct integers xi separated by single spaces sorted in ascending order — the coordinates where people are initially standing (1 ≤ xi ≤ 109).

      The last line of the input contains a single 0 and should not be processed.

      Output

      For each test case, output one integer number on a single line — the minimum time it takes to start dancing.

      Example

      Input:
      4
      2 4 5 8
      1
      10
      4
      20 24 25 26
      2
      1 2
      2
      1 1000000000
      0 Output: 3
      0
      3
      0
      999999998

      Added by:Paulo Costa
      Date:2012-01-14
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Universidad EAFIT (Colombia) - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set (classical)

      10401. Aliens at the train

      Problem code: ALIEN

      The aliens have arrived to Earth and everything is in harmony, the two races can live together. However, one specific Female Alien does not want to see humans on her way to the university, the alien must use the train as every human does. But she can choose any train station such she doesn’t see more than B humans, however, the Alien wants to go as far as possible with the train. Please, help her in this task

                              INPUT:
      You will receive one integer T denoting the number of test cases, then, the next line will contain two integers At Bt where At and Bt is the number of stations in the train (1<=At<=100,000) and the number of people that the alien wants to see as maximum (1<=Bt<=10,000,000), after that, one line containing At integers separated by a single space will denote the number of people the Alien can find in the At-i-th station. (For each station there will be as much 100 people)
                              OUTPUT:
      Your output should consist on T pair of numbers denoting the number of people the alien will see and the number of stations she will pass respectively.

      SAMPLE:


      INPUT:
      1
      5 100
      20 15 30 80 100


      OUTPUT
      65 3

       

      Output note:
      The alien takes the train at station 1 (with 20 people) and goes to station 2, then the 3rd station, at this point, she have seen 65 people, if she decides to go to station 4 she will see 145 people… Then she exits the station.

      The alien, however, can start at station 2 with 15 people, then continue up to the 4th station, then, she would have seen 125 people, but, as she wants to see the minimum people possible and this number of people exceeds what she wants to see, she decides to choose the way from the 1st to the 3rd station.

      Clarification: The alien will be moving always forward (remember, she can choose any station as a start), NEVER backwards, and you should choose the best path that satisfies the output specification.


      Added by:David Moran
      Date:2012-01-14
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      10405. Shooting the balloons!

      Problem code: ABA12E

      Dhinakaran is very fond of games. Shooting the balloons is his favourite. In this game, there are ‘n’ balloons which are arranged in a line. Every balloon has a unique number which is the number of points earned if that balloon is shot. A constraint here is that you should shoot contiguous balloons. So, Dhinakaran wanted to find the maximum number of points he could earn. He sought help from a friend who told him that it was the famous maximum contiguous sum problem. So Dhinakaran learnt about it and was happy. But Dhinakaran is not someone who gets satisfied so easily. He wanted to find the k-th smallest possible contiguous sum! Now, his friend was not able to solve this. So he came to me. I suggested that he approach you. You are a great coder, aren’t you? Help him out.

       

      There will be atleast 1 balloon and atmost 50000 balloons, and each balloon can have atleast 1 point and atmost 1e9 points.

      Input

      The first line of each data set contains the number of balloons and value of k.

      1 <= k <= (n * (n + 1)) / 2

      The second line contains N space separated integers.

      Output

      The output for each test case should be a single line containing the k-th smallest possible contiguous sum of points that could be achieved.

      Example

      Input:
      

      5 3

      1 2 3 4 5

      Output:

      3

      Explanation of sample case:

      The first 5 smallest contiguous subsequences are 1, 2, 3, 1 + 2, 4


      Added by:Kashyap Krishnakumar
      Date:2012-01-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      10415. Dracula

      Problem code: DRACULA

      In Transylvania, 1753, Dracula has returned from his long sleep, now, of course, all the citizens of Transylvania want to escape from the city. The only way out of the island is famous boat Hellman, and Petr is the ticket seller.

      All tickets available are numbered from A to B, inclusive, with 0 < A, B < 1018.
      The cost of a ticket is the sum of the digits of it's numbers in gold coins, so, for an example the ticket 14 costs coins 5 (1+4).

      Van Helsing has X gold coins, but he does not know which tickets to buy, or how many tickets he can buy at most. Since you are the mathematician of the city, you were charged with solving this problem.

      Input

      The input contains an integer T, number of test cases. Each test case contains three integers 0 < A, B, X < 1018 as described in the statement.

      Output

      For each test case print one line containing an integer, the number of tickets to Van Helsing
      can buy at most.

      Example

      Input:
      1
      2 5 5 Output: 2

      Added by:Paulo Costa
      Date:2012-01-16
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IME/USP 2 - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set (classical)

      10416. Van Helsings gun

      Problem code: VHELSING

      In Transylvania, 1753, Dracula has returned from his long sleep, now, of course, someone needs to face it or humanity will be utterly destroyed by the evil bloodthirsty Dracula.

      The only one with enough courage to face Dracula is Van Helsing. The only weapon that can defeat him is the silver gun, but Van Helsing does not know the exact amount of powder required for a deadly shot.

      The magazine of gunpowder has the form given by intersection of three cylinders of radius r and infinite height, mutually orthogonal, and centered on the axes $X$, $Y$ and $Z$ in $R^3$, as shown below. Your task is to help Van Helsing calculate the exact amount of gunpowder that he will need, ie, the volume of the powder magazine.

      Input

      The first line of input contains an integer 1 ≤ T ≤ 100 representing the number of test cases. For each of the following
      lines contain an integer 0 ≤ R ≤ 100, as shown above.

      Output

      For each case print one line containing the amount of gunpowder that Van Helsing needs, with 4 decimal places.

      Example

      Input:
      2
      0
      1 Output: 0.0000
      4.6863

      Added by:Paulo Costa
      Date:2012-01-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IME/USP 2 - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set ()

      10419. Polish Language

      Problem code: POLISH

      Russell can't wait to know Poland. As he waits he decided to learn a little of the Polish Language. To do this in a funny way he intends to use an old Polish dictionary and play a game he learned from the old Carl.

      Given a word s in the dictionary, Russell is interested in sequences of suffixes of s. But not just any one! Russell considers amusing sequences of suffixes with the following properties:

      • The suffixes appear in increasing sizes.
      • The suffixes appear in lexicographic order.

      As an example, if s = ABACA then the sequences (ABACA), (A, CA) and (A, ACA, BACA) please Russell but (ABACA, ACA) or (CA, ACA) doesn't.

      Help Russell find the number of amusing sequences of suffixes of a given word s modulo 1000000007 (10^9 + 7).

      Input

      The input consists of several test cases. Each test case consists of only one line containing a string S with 1 to 100000 (10^5) uppercase latin letters (A - Z).

      Output

      For each test case output a single line containing the number of amusing sequences of suffixes of S modulo 1000000007 (10^9 + 7).

      Example

      Input:
      ABACA
      NIE
      PIJ
      WODY
      CAMPINAS Output: 11
      7
      5
      8
      20

      Added by:Paulo Costa
      Date:2012-01-17
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IME/USP 1 - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set (classical)

      10420. Hardware upgrade

      Problem code: IOPC1200

      It is after years that Dystopian Institute of Technology has got funds for upgrading their computers. However, the people in charge of the upgrade have decided to make this a chance to fill their own pockets rather.

      There are N computers in the DIT network, numbered 0 to N-1. Computer 0 is the main server which connects the network to the outer world. Some pairs of the computers are directly connected in the network. For other pair of computers to communicate with each other, they have to do it via some other computer. For example, if there are only 3 computers in the network and the only direct connections are 0-1 and 0-2, then 1 communicates with 2 using 0 as intermediate. There is no limit on the number of intermediate computers to be used for communication between a pair. Now, since the DIT network was built on the principle of minimum expenditure, the N computers have been made pairwise connected by using the minimum number of direct connections - ie, N-1.

      The upgrade contractor has decided to not do the work properly but pocket the entire funds instead. However, to show that he has done something, he will rearrange the computers. For example he could move the computer number 3 to where 2 was earlier, 2 to 1, 1 to 3, 4 to 5 and 5 to 4. The computer number 0 is special and cannot be moved. Direct connections between computers depend on the locations though. Hence if there was a direct connection earlier between 3 and 5, it will now be between 1 and 4 (since they have been placed at the locations 3 and 5 were at earlier). However, he has noticed something strange : the new direct connection between computers i and j works if and only if there was a direct connection between i and j earlier. Hence he wants to rearrange the computers in such a way that the pairs of computers which are connected directly now are the same pairs which were connected earlier.

      Given the computer network, count the number of ways the computers can be rearranged satisfying the conditions.

      Input

      The first line of the input contains T, the number of test cases (T ≤ 10). Following this are the descriptions of the test cases. Each description starts with a line containing the integer N, the number of computers in the network (1 ≤ N ≤ 10000). This is followed by N-1 lines, each containing a pair of integers i and j, denoting that computer i is directly connected to computer j. It is assured that these N-1 direct connections will make every pair of computers connected (via intermediates if needed).

      Output

      For each test case, output the number of rearrangements of the computers. A rearrangement (p0,p1,p2...pN-1) of (0,1,2...N-1) is valid if the following conditions are satisfied:

      • p0=0
      • If there is a direct connection between i and j, there should also be a direct connection between pi and pj

      Notice that (0,1,2...N-1) is considered a valid rearrangement of itself. Also, since the answer could be very big, output it modulo 1000000007

      Example

      Input:
      1
      6
      0 1
      0 2
      0 3
      3 4
      3 5
      
      Output:
      4
      

      Added by:Raziman T V
      Date:2012-01-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://www.codechef.com/IOPC2012/









      SPOJ Problem Set ()

      10421. Run, Snipe, Run

      Problem code: SNIPE

      Kevin, the Snipe, and her children (apparently Kevin is a girl) were reunited, all thanks to Russell and Mr. Fredricksen! Now the two humans have embarked to their next adventure, towards Poland, but Kevin just noticed her children stole Mr. Fredricksen's cane without him realizing. It must be returned before they go too far away!

      Kevin is not sure where they are now, but knows they went with their flying house somewhere to the northeast, and has narrowed it down to a few points where they might be resting. She will send some of her children to warn them of the missing cane. Each snipe can check multiple places, but since the house should be flying again soon, they can't waste any time and should always move to the north and/or to the east. Additionally, she wants to send the minimum number possible as long as every location on her list is visited.

      Your job is to help her determine this number.

      Input

      Input consists of several test cases. 

      Each test case begins with a single integer N (1 ≤ N ≤ 1000), the number of places the house can be.

      N lines follow, each containing two integers, ei and ni, the distance (in miles) to the east and to the north, respectively of the ith place related to Kevin's position. 0 ≤ei, ni ≤= 10000.

      Input is terminated by a line containing a single integer zero.

      Output

      For each test case output a single integer: the minimum number of snipes needed to reach every place.

      Example

      Input:
      5
      1 1
      2 2
      3 3
      4 4
      5 5
      5
      1 5
      2 4
      3 3
      4 2
      5 1
      5
      0 1
      1 1
      1 2
      2 2
      2 3
      0 Output: 1
      5
      1

      Added by:Paulo Costa
      Date:2012-01-17
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IME/USP 1 - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set (classical)

      10422. Rubiks cube

      Problem code: IOPC1201

      The Rubik's cube is perhaps the world's most popular intellectual toy. More than just the joy of solving, there is a lot of mathematics to it too.

      Consider a solved Rubik's cube. The six faces of the cube are named FRONT, BACK, UP, DOWN, LEFT and RIGHT respectively. An elementary move of the Rubik's cube is rotating a face by 90 degrees clockwise, 90 degrees anticlockwise or 180 degrees about an axis from the centre of the face to the centre of the cube. Any valid state of the Rubik's cube can be reached by applying these elementary operations one after the other.

      An elementary move is denoted in the following fashion. If a given face is rotated by 90 degrees clockwise about the axis passing from the centre of the face to the centre of the cube, the move is denoted by the first letter of the name of the face. If the rotation is anticlockwise by 90 degrees, the letter is followed by an apostrophe ('). If the rotation is by 180 degrees, the letter is followed by a 2.

      For example, a 90 degree clockwise rotation of the right face is denoted by R, a 90 degree anticlockwise rotation of the back face by B' and a 180 degree rotation of the top face by U2. The elementary moves are explained with the help of animations in the "Face turns" section of this page. The elementary moves can be combined to get a compound move of the cube. For example, URF2 denotes rotating the top face by 90 degrees clockwise, then the right face by 90 degrees clockwise followed by the front face by 180 degrees.

      In this problem you will be given a string describing a sequence of elementary moves on a solved Rubik's cube. Your task is to find out the number of times the sequence should be applied repeatedly to the cube to get back the original cube.

      Input

      The first line of input gives T, the number of test cases (1≤T≤1000). Following this are T lines, each containing a string denoting a sequence of moves on the Rubik's cube. The string will contain only the characters U, D, L, R, F, B, ' and 2, and will be at most 1000 characters long. It is assured to be a valid sequence of elementary moves.

      Output

      For each test case, output the minimum number of times (≥1) the move sequence must be applied to a solved Rubik's cube to get back the solved cube again.

      Example

      Input:
      4
      R
      RR2
      RU
      R2R'R'
      
      Output:
      4
      4
      105
      1
      

      Added by:Raziman T V
      Date:2012-01-17
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://www.codechef.com/IOPC2012/









      SPOJ Problem Set ()

      10424. To Poland

      Problem code: TOPOLAND

      Little Russell and Mr. Fredricksen are embarking in a new journey with their balloon house. After visiting South America and helping Kevin, the Snipe, they decided to travel to Warsaw, Poland where new specimens of birds might be found.

      Their trip is divided into several parts. Due to pressure levels and wind speed, each part of their journey requires that their house is equipped with a minimum number of balloons. As a good boy scout, Russell has already figured out how many balloons are necessary to go through each of the parts. The problem is that atmosphere conditions change and Russel is having trouble determining how many balloons the house should be equipped with to go through continuous parts of the journey, so they don't have to fill up more balloons than necessary.

      To help out Russell, you are to develop a program that must deal with the following queries:

      • Russell has added or removed balloons from the house
      • The minimum number of balloons at certain part has changed
      • How many balloons should be added or removed so that the house goes through continuous parts of the journey with the minimum necessary number of balloons?

      Input

      The first line contains a number T (T ≤ 100), the number of testcases.

      Each testcase starts with numbers N (1 ≤ N ≤ 105) and M (0 ≤ M ≤ 103) where N is the number of parts in the journey and M  is the initial number of balloons in the house. Then N numbers follow, one per line, where each number Ni (0 ≤ Ni ≤ 109, 0 ≤ i < N) represents the initial number of balloons necessary to go through part i.

      On the next line there is a number Q (1 ≤ Q ≤ 105), the number of queries that you should answer. Each of the next Q lines contains a query in one of the following formats:

      • "A K" -  where A is the actual character 'A' (quotes for clarity) and K (-103K ≤ 103) is the number of balloons that have been added or removed from the house.  It is assured that the total number of balloons in the house is never negative;
      • "B J K" - where B is the actual character 'B' (quotes for clarity), J (0 ≤ J < N) is the number of the part of the journey (0-indexed) and K (0 ≤ K ≤ 109) is the new minimum number of balloons required to go through part J;
      • "C I J" - where C is the actual character 'C' (quotes for clarity), and [I, J], 0 ≤ IJ < N$ is the range that Russell would like to query. For each query of this type, print the difference between the number of balloons currently in the house and the minimum necessary to go through all the parts between I and J inclusive. Note that this query doesn't change the number of balloons in the house.

      Output

      For each testcase print one line with "Testcase X:" (quotes for clarity) where X is the number of the testcase (0-indexed). For each query of the type "C I J" print one line with the difference between the number of balloons currently in the house and the minimum necessary to go through all the parts between I and J inclusive.

      Print one blank line after each testcase.

      Example

      Input:
      2
      3 11
      5 2 4
      1
      C 0 2
      3 11
      16 2 17
      5
      C 0 2
      A -2
      C 1 2
      B 0 0
      C 0 1 Output: Testcase 0:
      6

      Testcase 1:
      6
      8
      7

      Added by:Paulo Costa
      Date:2012-01-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IME/USP 1 - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set (classical)

      10425. Security System

      Problem code: SECSYS

      Jose is a very rich man who loves to collect precious pieces. As he is not naive, all their riches are well kept in banks he trust. However, from time to time, he keeps in his home some valuable objects to show to friends and relatives. Jose knows that is a big risk to keep items of great value stored at home, so he came up with a security system to confuse anyone trying to find something valuable in his home.

      At Joses house are C safes, all with numerical combinations. The valuable piece is stored in one of these safes. Jose sets a six-digit numeric password for one of the safes. The security system (common to the safes) sums the digits of the password and displays the result on the display box that received the combination. Jose, then know that to find the safe where the part is stored, the person should go to the cashier which number is the remainder from dividing the net profit shown on the display of the safe amount of current for the safe house (C). The system records for each of the C - 1 coffers remaining two numbers, A and B, which are coefficients of a linear equation of the form Y = AX + B.

      The number X is inserted as a combination and its value should be the number printed on the display above the vault. The remainder of the division of the value of Y by the amount of safe house indicates the number of the next safe to be "visited".

      Starting from the first vault, the piece should be safe if the ith the diagram is followed properly. So anyone who wants to find the piece must know the first safe, their combination and go to the ith safe, where is the piece.

      Consider any safe only opens if it is the ith in the sequence of trials, that is, if you get the number produced by the ith a-safe. Therefore, if the safe of matches in which the piece is stored be visited before the ith attempt, he will not open and the person will not know that the piece is there.

      As the coefficients of the safes are constantly changed by the security system, Joseph did not want to have to follow the circuit every time you want to open the safe in which the piece is saved (it does not know what the value of Y that opens the safe that kept the piece). His work is therefore to write a program for the security module that, given a safe home, their combination, the safe amount of intermediate circuit and the coefficients A and B of each of the boxes (known by the system), discover the safe in which the part is stored and the combination that opens.

      Input

      The input consists of several test cases. Each test case consists of several lines as described below. The first line of a test case consists of three integers separated by single spaces: C, P and I, representing the number of vaults, the number of the first safe vaults and the amount of the intermediate circuit (not counting the first and last) , respectively. Consider: 3C10, 0 < IC - 2. Each of the following C lines contains two integers separated by a single space representing the coefficients A and B of a safe. Consider the lines represent the coffers of coefficients ordered from 0 to C-1. Consider also that 0A, B100. The last line of the test case containing a string of six digits (each digit can take values ​​from 0 to 9) which represents the combination of the safe P.

      The last line of the input file contains three zeros separated by single spaces.

      Output

      For each test case your program should print one line containing the number of safe in which the piece is stored and open the final combination separated by a single space.

      Example

      Input:
      6 3 2
      10 25
      4 45
      10 99
      8 7
      0 0
      1 81
      908710
      10 5 8
      100 100
      100 100
      100 100
      100 100
      100 100
      100 100
      100 100
      100 100
      100 100
      100 100
      999999
      0 0 0 Output: 1 625
      0 550101010101010100

      Added by:Paulo Costa
      Date:2012-01-17
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:EACH/USP - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set (classical)

      10437. Quadrilaterals

      Problem code: IOPC1202

      You are given the coordinates of the vertices of a square in the 2-d plane. All vertex coordinates will be integers.

      Now consider all convex quadrilaterals which also have integer coordinates for their vertices such that the midpoints of their edges are the vertices of the original square. Find the sum of areas of all such quadrilaterals.

      Input

      The first line of input gives T, the number of test cases (1≤T≤25000). Following this are the descriptions of the individual testcases. Each testcase consists of four lines, each line containing two space separated integers - the x and y coordinates of a distinct vertex of the square. The coordinate limits are -1000000000≤xi,yi≤1000000000. It is assured that the four vertices will correspond to a square.

      Output

      For each testcase output the total area of quadrilaterals with the given property. Since the answer could be very large, give the answer modulo 100000007.

      Example

      Input:
      2
      0 0
      1 1
      1 0
      0 1
      0 1
      1 0
      0 -1
      -1 0
      
      Output:
      0
      4
      

      Added by:Raziman T V
      Date:2012-01-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://www.codechef.com/IOPC2012/









      SPOJ Problem Set (classical)

      10438. Crazy texting

      Problem code: IOPC1203

      You must be familiar with the use of numeric keys to enter alphabets in mobile phones. A single numeric key when pressed gives a character. When pressed again, it changes to another and so on. Once the set of characters mapped to the key is exhausted, the key wraps around to the original character.

      The key mapping in this problem is the T9 mapping, restricted to lowercase english characters. The characters corresponding to the individual keys are:

      • 2: a,b,c
      • 3: d,e,f
      • 4: g,h,i
      • 5: j,k,l
      • 6: m,n,o
      • 7: p,q,r,s
      • 8: t,u,v
      • 9: w,x,y,z

      For example, if you press the key 2 once, it prints the character 'a'. On pressing it again, it becomes 'b', then 'c', then back to 'a' and so on.

      Consider a string made of lowercase letters only. To enter this string into a mobile phone, a certain key sequence has to be entered with sufficient gaps in between. Suppose that the key sequence entered is correct but the gaps between keypresses are made arbitrarily. This can result in very different strings being printed.

      For example, let the string to be input be "mod". The key sequence corresponding to this is 6_6663 where '_' denotes a gap between the keypresses. Suppose the keys are pressed in the same order, but with gaps between keypresses arbitrary. This can result in 8 different strings: "mod", "nnd", "omd", "mmmmd", "mnmd", "mmnd", "nmmd" and "md".

      Given an input string, Find the number of possible strings printed by the key sequence corresponding to it.

      Input

      The first line of the input consists of T, the number of testcases (1≤T≤10). Following this are T lines, each containing a string. The string will consist only of lowercase letters and will have a maximum length of 100000

      Output

      For each string, output the number of strings corresponding to its key sequence. Since the answer can be very big, output it modulo 100000007

      Example

      Input:
      2
      mod
      iopc
      
      Output:
      8
      64
      

      Added by:Raziman T V
      Date:2012-01-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://www.codechef.com/IOPC2012/









      SPOJ Problem Set (classical)

      10439. Walking Robot

      Problem code: WALKROBO

      Walking Robot

      Leonard is a student of robotics, and his teacher, Dr. Cooper, asked his class to build a robot to interact with the environment and change its behavior upon certain events. The environment, behavior changes and the events are up to the student, so Leonard decided to make a robot that walks in a grid with a set of movements. There are downloading spots in the grid in which the robot can learn new movements. The task of the robot is to go from one point of the grid to another in as fewest steps as possible.

      The grid is composed of M rows and N columns of squares. The botton-left square is position (0,0) and the top-right square is position (N-1,M-1). A movement is defined as a tuple (X,Y). Where X denotes the movement on the x axis and Y on the y axis. A movement is considered as 1 step. The robot can not make a movement that will end outside the boundaries of the grid.

      There are K possible movements for the robot to learn. The robot stars with T movements on its memory. If the robot is in a downloading spot, he can choose to learn the movement available at that spot, this takes 1 step. The robot can not learn new movements while he is moving. The robot starts at position (0,0) and should move to position (N-1,M-1).

      Input

      The first line has four integers M, N (2 <= M,N <= 15), K (1 <= K <= 12) and T (0 <= T <= K). After this line there will be K lines. The Kth line contains two integers (X,Y) (-10 <= X,Y <= 10) which describe the Kth movement. Movements are indexed from 1 to K inclusive. Afterwards there will be a line with T numbers separed by spaces, which describe the movements that are initially known by the robot. Then there is the description of the grid: there will be M lines with N integers each. 0 indicates a free square, a positive number means there is a downloading spot for the movement with that number index. The numbers of the grid will always be between 0 and K inclusive. The last case is followed by a line containing four zeros. This case should not be processed.

      Output

      For each test case print a single line with "Case #X: S" where X is the number of the test case (starting from 1) and S is the lowest number of steps to achieve the destination. If it is not possible for the robot to achieve the destination, print -1 instead of the number of steps.

      Example

      Input:

      4 3 2 1
      1 0
      0 1
      1
      0 0 0
      0 0 0
      0 0 0
      0 0 2
      5 5 4 1
      2 1
      -1 1
      -1 0
      -1 -2
      1
      0 4 3 0 0
      0 0 0 0 0
      0 0 0 0 2
      0 0 0 0 0
      0 0 0 0 0
      5 5 4 1
      2 1
      -1 1
      -1 0
      -1 -2
      1
      4 0 3 0 0
      0 0 0 0 0
      0 0 0 0 2
      0 0 0 0 0
      0 0 0 0 0
      7 7 3 0
      1 1
      2 2
      4 4
      0 0 0 0 0 0 0
      0 0 0 0 0 0 0
      0 0 0 0 0 0 0
      0 0 0 0 0 0 0
      0 0 3 0 0 0 0
      0 2 0 0 0 0 0
      1 0 0 0 0 0 0
      0 0 0 0
      Output:
      Case #1: 6
      Case #2: 11
      Case #3: -1
      Case #4: 5

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:1s-30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFPE









      SPOJ Problem Set ()

      10440. Friends

      Problem code: FRNDS

      Friends

      A group of N people are going to the movies, some pair of them are friends and according to the famous saying that "The friends of my friends are my friends, too" it follows that if A and B are friends and B and C are friends then A and C are friends, and do not forget that every friendship is mutual, if A is friend of B, then B is also friend of A.
      They will all sit in the first row at the cinema, there are N seats in each row, a way is good if there is at least one pair of of people that are friends and at the same time they are sitting in adjacent seats. So that is your task, to count how many assignments of those N people in the N seats are good.

      Input

      Input starts with an integer T (1 <= T <= 600), denoting the number of test cases. Each test case starts with a line containing two integers N (2 <= N <= 40) and M (0 <= M <= 800). Each of the next M lines will contain 2 integers A B (1 <= A,B <= N, A != B) meaning that A and B are friends.

      Output

      For each test case print a single line with "Case #X: P" where X is the number of the test case (starting from 1) and P is the number of ways modulo 1000000007. Look at the sample output for more details.

      Example

      Input:
      
      3
      2 1
      2 1
      3 2
      2 1
      1 3
      4 0 Output:

      Case #1: 2
      Case #2: 6
      Case #3: 0

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:60s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFPE









      SPOJ Problem Set (classical)

      10442. Candy Distribution

      Problem code: CADYDIST

      Alice is a teacher that loves her students. As the school year reaches its end, she wants to reward all her students with candies for all their hard work.

      Since each of her classes is unique, she decided she’ll give a different kind of candy for each class, and in order to avoid students being mad at others in their class, she wants to make things fair by giving all students in the same class the same kind of candy.

      Happily, she went to the candy shop, and fortunately found out that it had N different types of candy, exactly the same number of classes of students she taught!

      Looking at the prices and paying close attention to the number of students in each class, Alice noted that she could save some money by assigning the types of candy to certain classes. Because she’s a teacher, her income is not that big and saving money is very important to her, so she asked you to write a program to determine the least amount of money she must spend.

      Input

      Each test case consists of three lines. The first line contains a positive integer N (1≤N≤100000). The second line contains N integers Ci, the ith integer indicates the number of students in Alice’s i-th class. The third and last line also contains N integers Pi the ith integer indicates the price of the ith type of candy (1 ≤ Ci, Pi  ≤ 100000).

      The input ends with a line consisting of a 0, which indicates end of input.

      Output

      For each test case, output a line containing the least amount of money Alice must spend.

      Example

      Input:
      4
      1 1 1 1
      2 2 2 2
      5
      10 80 37 22 109
      6 8 8 20 15
      0 Output: 8
      2120

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ITA - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set (classical)

      10443. Bridges

      Problem code: BRDGS

      A new planet full of rivers was discovered and is being prepared for colonization. We want to connect every piece of land by bridges, the cost of building a bridge is its width.

      Input

      The first number in the input file is T < 200, the number of test cases. Each test case starts with a line with a integer, N <= 500, the number of rivers. N lines are followed with 5 integers each, Di1, Fi1, Di2, Fi2 and Wi <= 1000000, the coordinates of the extremities and the width of the i-th river. Every D is between -90 and 90, and every F is between 0 and 359, they are measured in degrees and correspond to the spherical coordinates (latitude and longitude respectively).
      The two extremities of a river can be seen from above in a distance less than infinite, a course of a river is always the smallest possible and two rivers intersect in at most 1 point.

      Output

      For each test case print a single line with "Case #X: C" where X is the number of the test case (starting from 1) and C is the minimum cost to build the bridges so the islands and continents are connected directly or indirectly to each other.

      Example

      Input:

      3
      4
      0 0 90 0 4
      90 0 0 179 2
      0 0 -90 0 1
      -90 0 0 179 1
      6
      0 0 10 90 3
      0 0 -20 90 3
      0 179 10 90 5
      0 179 -20 90 1
      0 0 0 179 10
      -20 90 20 90 1
      1
      0 2 0 3 1 Output:
      Case #1: 1
      Case #2: 6
      Case #3: 0

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:130s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFPE









      SPOJ Problem Set ()

      10444. Coding

      Problem code: CODING2

      A binary code for an alphabet of 2N symbols is a bijection between the 2N symbols and 2N binary codewords. For example, in the table below 3 different binary codes are presented for a 4-symbol alphabet (a,b,c,d).

      Symbol Code 1 Code 2 Code 3
      a 00 0 1
      b 01 10 10
      c 10 110 100
      d 11 111 1000

      A code is said to be prefix-free if none of the codewords is a prefix of another codeword. For example, in the table above, codes 1 and 2 are prefix-free. However, code 3 is not prefix-free. Prefix-free codes are widely used, as encoding and decoding becomes very simple.
      For this problem, given N and a message containing M alphabet symbols, the task is to find a prefix-free code for the entire alphabet (including symbols possibly not present in the message) that minimizes the number of necessary bits to represent the message. For example, let N=2, with symbols (a,b,c,d), and the message "a a a a b b b b a a a a c c d d"

      The message encoded with codes 1 and 2 above becomes, respectively:

      • 00 00 00 00 01 01 01 01 00 00 00 00 10 10 11 11, for a total of 32 bits.
      • 0 0 0 0 10 10 10 10 0 0 0 0 110 110 111 111, for a total of 28 bits.

      It is possible to show that no prefix-free code can encode the message above in less than 28 bits.

      Input

      The input contains several test cases. Each test case has two lines. The first line of a test case contains two integers N, M separated by a single space (1 ≤ N ≤ 15, 1 ≤ M ≤ 106, D ≤ 15).

      On the second line are M integers Xi, 0 ≤ Xi ≤ 2N – 1, representing the message to be encoded. The end of the input is marked by a case with N=M=0. This case must not be processed.

      Output

      For each test case, print a single line with one integer, the minimum number of bits necessary to encode the message using a prefix-free code.

      Example

      Input:
      2 16
      0 0 0 0 1 1 1 1 0 0 0 0 2 2 3 3
      0 0 Output: 28

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ITA - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set (classical)

      10446. Sicrano

      Problem code: SICRANO

      Sicrano has a problem ... a geometry problem. He is not a very good in this area,
      so he's asking for your help.
      Given a set of points and a set of segments, tell, for each segment, how much
      points lie in it.

      Input

      The first integer T (T <= 20) in the input says that there are T test cases in the input.
      Each test case begins with two integer N and M (1 <= N, M <= 50). N means how many points
      exists in that test case, and M means how many segments exists in that test case. The next N pairs of
      integers represents the points. Each pair describes the coordinates x and y of a point. (0 <= x, y <=
      100).
      After that, the segments will be listed. Each segment is described by the coordinates of its two
      extreme points.
      All values in the input are integers. See the sample input for clarification.

      Output

      For each segment, print how many points are in it.

      Example

      Input:

      1

      4 3

      1 1
      2 2
      3 3
      4 4

      0 0 5 5
      3 3 4 4
      0 0 1 0 Output: 4
      2
      0

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFPE









      SPOJ Problem Set (classical)

      10447. Contaminated City

      Problem code: CONTCITY

      In a far away country there is a city facing a big problem. The city is plagued by a deadly gas. Many
      people have died, but there are groups of survivors at places around the city. Between these places
      there are roads connecting two distinct places that can still be traversed safely. These roads can be
      traversed in both directions. It's known the number of days necessary to traverse each road and the
      two places that it connects. It's also known the number of survivors at each location. Each survivor
      can get to other places following a sequence of roads.
      The mayor will send several helicopters to rescue these people, each having a capacity, a limit on
      the number of crew (people that it can rescue). Each helicopter will land on a certain day and place.
      You should answer an important question for the mayor. How many days are needed to rescue all
      survivors? If it's not possible to rescue all people you should answer how many of them can be
      rescued.

      Input

      The first line of input file have the number of test cases T (T <= 40).
      The first line of each test case have N, M, and H, the number of places considered, the number of
      roads between the places and the number of helicopters that will be sent, respectively. Each place is
      uniquely identified by a number between 1 and N. The next N lines will have N integers, the i-th
      line have the number of survivors in place i, Xi. Each of next M lines will have three numbers Aj,
      Bj and Dj, meaning that there is a way between places Aj and Bj that last Dj days to traverse. The
      input can contain several roads between the same pair of places. Each of next H lines will have
      three integers Dh, Ph, and Ch (in this order), meaning that a helicopter with capacity Ch will arrive
      at place Ph at day Dh. The sum of survivors will not be more than 200. If a survivor can get a
      helicopter following a sequence of roads, the total time to get the helicopter will not be more than
      1000.


      Constraints:
      1 <= N, H <= 50
      1 <= M <= 1500
      1 <= Aj, Bj, Ph <= N
      1 <= Dj, Dh <= 1000
      1 <= Ch <= 200
      0 <= Xi <= 200

      Output

      For each test case there is one line in output. If all people can be rescued "All people can be rescued
      in D day(s) ." should be printed, where D is the minimum number of days to rescue all people. If it
      is impossible to rescue all people "X survivor(s) can be rescued." should be printed, where X is the
      maximum number of survivors that can be rescued.

      Example

      Input:
      2
      4 4 4
      3
      4
      5
      6
      1 2 7
      2 3 3
      3 4 3
      4 1 4
      4 4 7
      6 3 2
      5 2 3
      3 1 6
      4 2 3
      2
      2
      3
      1
      1 4 3
      2 3 3
      2 4 2
      3 2 4
      3 3 2 Output: All people can be rescued in 6 day(s).
      7 survivor(s) can be rescued.

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10449. Resource Management

      Problem code: RESOURCE

      Aventuras, Caminhadas e Montanhas (ACM) is a park known around the world for its vast mountain range. Recently, an infrastructure of cable cars has been built so that locomotion throughout the park becomes easier. The cable car stations are distributed in a rectangular network consisting of N rows and M columns, and the fee to go from one station to any of the others is D dollars.

      There are also several hiking trails along the park, for those who appreciate walking in natural environments. The trails connect every horizontally or vertically adjacent station (but not diagonally adjacent ones). Alfredo and his family are visiting the park this summer vacation, and they wish to visit all of the stations in the park.

      However, they consider the charged fee as overtly high. Therefore, they plan to mix walking on foot with the use of the cable cars. The route may begin on any of the cable car stations. Alfredo does not do a lot of physical exercise, and for that reason he wishes to only walk in downward slopes. The effort of a walk is proportional to the slope of the trail, that is, walking from a station with a height of H1 to another with a height of H2 represents an effort of (H2H1) calories.

      As there are many possibilities for such routes, Alfredo asked his son João to determine the optimal route. João, in turn, asked his friend in Campinas, who was studying for the ICPC, to determine the minimal cost and effort of a visit to the ACM park.

      Input

      The input contains several test cases. The first line of a test case contains three integers N, M, D (1 ≤ N, M, D ≤ 15).

      Each of the next N lines contains M integers. The ith integer in the jth line, Hij, is the height of the ith station on the jth line of the cable
      car network (Hij ≤ 100). The last test case is followed by one line with three zeros.

      Output

      For each test case, print a line with two integers, separated by spaces. The first corresponds to the minimal cost of the visit to the park, in dollars. The second represents the effort of the route that has minimal cost.

      If there is more than one such route, choose the one with the least effort.

      Example

      Input:
      2 2 1
      1 2
      4 3
      3 3 7
      1 2 1
      4 5 3
      1 2 1
      0 0 0 Output: 0 3
      21 8

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ITA - Brazilian ICPC Training Camp, Jan-Feb/2012









      SPOJ Problem Set ()

      10450. Amoeba

      Problem code: AMOEBA

      Dr. Fulano found a new species of microorganism, the fast-growing-amoeba. The colony of this
      kind of amoeba grows vary fast. To find out the exacty rate of growth of the colony, Dr. Fulano
      wrote down for several days, the number of amoebae in the colony. Soon he realized that each
      individual generate daily, 6 new individuals. As the number of amoebae grew very quickly, Dr.
      Fulano noted only the last K digits. When he realized that the numbers noted were repeated, it was
      too late! The research was already well advanced and there was no time to recount. The solution
      was to ask for help from you.


      Doctor Fulano will give to you a number of K digits (0 < K < 10), possibly with leading zeroes. You
      should answer the first day he wrote down that number. Consider that in day 1, the colony was
      composed of 1 amoeba. Consider also that an amoeba does not disappear when generating his
      descendants.
      If there is no answer to the number given, print -1.

      Input

      The input is composed by various numbers, each in one line.

      Output

      For each line in input, print a line in output. The line should contains the required answer without
      leading zeroes.

      Example

      Input:
      01
      143
      743
      600 Output: 1
      20
      12
      -1

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:UFPE









      SPOJ Problem Set (classical)

      10451. Stun Boosting

      Problem code: STUN

      People in Nloglônia are very addicted to video games as they spend hours playing every day. As they are a very competitive community, everyone competes to see who has more gaming achievements or trophies. Every time someone starts a new game, they spend some time playing the single player portion of the game, but what they really like is the multiplayer.

      There's a game that became very famous in the city envolving some assassins and their creed. Anyway, the objective of the multiplayer game is to hunt and assasinate others assassins. The player's skill is measured by how much experience (XP) he has, which can be accumulated by doing various actions in the game, i.e. killing or poisoning a target, running away from who wants to kill you or stunning someone, and so on.

      But there's a problem, everyone wants to complete the game as fast as they can, in order to start a new one. To complete this game, there's an achievement that's obtained when a player reaches X experience points. You possibily need to play a lot of multiplayer rounds to reach that amount of XP, and that's why a group of friends decided to boost their XP, it consists of helping everybody in the group to reach a desired amount as fast as possible.

      Here's how this match goes. There are always 6 players separated in 3 teams with 2 players each. Let's give each player an identi er from 1 throught 6, and assume that the teams are organized as follows: players 1 and 2 in the fi rst team, players 3 and 4 in the second
      team, and players 5 and 6 in the third team. The game is separated in rounds, each taking 4 minutes to complete.

      To boost their experiences, the players agreed that an easy and fast way to do it is throught the stun boosting. This boosting method consists of stunning each other instead of killing. It's true that killing will give you more XP points, but the dead player end up spending too much time to respawn and to meet with the someone else again. The boosting will happens as follows. Everyone must meet at the center of the map to start stuning each other. Two groups with one player from each team will be formed in this location. The players takes di fferent amount of time to reach the center of the map (depending on where they first spawned) so the group that reaches the center fi rst will start boosting first. If both players from the same team gets to the center at the same time, the one with lower identi er must be choosen to be part of the fi rst group.

      As soon as a group meet at the center of the map they start stun boosting. Every time a player gets stunned he lands on the ground for some time, and then gets up. A stun round consists of all players in the group stunning and getting stunned. An example of a stun round:

      player 1 stuns player 2, player 3 stuns player 1, player 2 waits to get up and stuns player 3. In this problem, a stun round takes 7 seconds. This happens over and over until the round is over.

      If this wasn't enough, the players are following these two guidelines that they created to raise the experience even faster, and be as fair as possible with everyone in the group. First, if two players from oposing teams meet up at the center, they must wait for the third one to
      come, and then start boosting (they hold still until the group has three members). Second, if they know there's no time left in the round to complete a stun round, they will not do it, instead, if there's 2 or more seconds remaining they have time to poison each other, getting some extra and welcome XP.

      For each stun the player gets 300XP, and for each poison kill the player gets 1800XP. Note that the XP earned stuning will be granted to the player at the end of the stun round (that takes 7 seconds) and the XP earned poisoning will be granted in the end of the 4 minutes round. Also, you must note that when poisoning, the three players are able to poison someone else because it takes some time for it to really kill them. The players will choose to poison each other if and only if there's no time left for a stun round (even though poisoning should work better to raise the experience).

      You are given the amount of XP the players want to reach, the number of rounds they played and the initial amount of experience the players had before starting boosting. For each round, you are given the time that each player takes to reach the center of the map. The
      players want to know who was the player that reached the experience goal rst, and in which round he did. If no player reached the goal, they want to know the experience of everyone after they played all the rounds.

      Input

      The input contains several test cases. The first line of a test case contains two integers, X and R (1 ≤ X ≤ 650000, 1 ≤ R ≤ 1000), which represents the amount of experience the players want to achieve and the number of rounds they played, respectively.

      The second line of a test case contains six integers Xi (1 ≤ i ≤ 6) that represents the initial experience of the ith player. Then R lines follows, each containing six integers Ti (1 ≤ i ≤ 6; 0 < Ti < 240) representing the time that the ith player reached the center of the map on that round.

      The end of the input is marked by X = R = 0.

      The input should be read from the standard input.

      Output

      For each test case your program should output one line. If some player reached the desired experience, you should output two integers indicating the identi er of the rst player to reach the desired experience, and the numbers of rounds necessary to this player to do so. If more than one player reached the desired experience at the same time, output the one with lower identi er. In the case that no player reached the desired experience, you should output "-1" and then six integers containing the amount of experience each player had after playing all the rounds.

      The output should be write in the standard output.

      Example

      Input:
      10000 1
      1000 12345 50000 9000 100 1
      30 10 20 20 10 30
      650000 1
      100 200 300 400 500 600
      20 10 30 20 20 30
      0 0 Output: 2 0
      -1 9100 11300 9300 11500 11600 9600

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10452. Caprica Cities

      Problem code: CAPRICA

      Caprica is one of the 12 colonial planets, but it was completely destroyed by the cylons, robots made
      by humans that had rebelled. Before the attack, Doctor Gaius Baltar had the following problem.
      Caprica has N cities, numbered from 0 to N − 1, and M bidirectional roads connecting them, in
      a way that exists a path between every pair of cities. Let X and Y be two disjoint and non-empty
      subsets of this N cities. The problem is to find the smallest path length between any cities x and y
      where x ∈ X and y ∈ Y . A path length is the sum of the distance of each road in this path.

      Input

      Each test case is described using several lines. The first line contains four integers N , M , A and B
      representing respectively the number of cities (2 ≤ N ≤ 1000), the number of roads (1 ≤ M ≤ 104 ),
      the number of cities in X (2 ≤ A ≤ 1000), and the number of cities in Y (2 ≤ B ≤ 1000), where
      A + B ≤ N.
      The second line contains A integers and the third line contains B integers, representing the cities
      in X and Y respectively. Each of the next M lines describes a road using three integers, u, v, and d,
      indicating that there is a road between the cities u and v with distance d (1 ≤ d ≤ 104 ).
      The last test case is followed by a line containing four zeros.

      Output

      For each test case output, in a single line, the integer representing the smallest path length between
      x and y where x ∈ X and y ∈ Y .

      Example

      Input:
      4 4 2 2
      0 1
      2 3
      0 1 10
      0 2 20
      1 3 10
      2 3 10
      0 0 0 0

      Output: 10

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10453. Spring Loaded

      Problem code: SPRING

      Bob have just got a new toy from his Physics teacher to play with. It is called the Super Coiled
      Spring Loaded String (SCSLS for short) and it involves coiled springs, but unfortunately no magnets.
      The complex structure of the trinket is made of N bars (numbered from 0 to N − 1) and M springs
      (numbered from 0 to M − 1), each of which connects two different bars. All springs are laid out
      longitudinally to the entire string while the bars are perpendicular to them.
      The bars can be positioned freely along the longitudinal axis, but when two bars connected by a
      spring are pulled away from each other, a restoring force appears at the spring. Bob knows that this
      elastic force is given by Hooke’s Law, which states that |F | = kx, where k is a spring constant, x
      is the displacement of the spring and |F | is the absolute value of the force. Because the SCSLS is a
      very strange device, its springs are also special since they are Zero-length springs, each with a specific
      constant ki . This kind of spring have infinitesimal length so that when it is stretched, its length is
      equal to its displacement.
      Bob wants to leave his new toy displayed in his bedroom and he will do so by nailing the bars to
      the wall. He needs to position them horizontally such that bars 0 and N − 1 are D units distant from
      each other and the remaining bars are between them (in any relative order). Being a very meticulous
      kid, he always takes good care of all his toys. So, he wants to achieve a configuration such that the
      maximum force exerted on any spring is the lowest possible (because this way the springs are supposed
      to have greater durability).

      spring example

      For example, in the figure above we have N = 4 bars and M = 4 springs showed at the left in their
      initial configuration. Suppose the spring constants are k0 = 10, k1 = 20, k2 = 10 and k3 = 1 and Bob
      wants a total distance of D = 10. The best configuration is showed at the right, in which the springs
      are subject to forces |F0 | = 40, |F1 | = 40, |F2 | = 40 and |F3 | = 6, all of which are no greater than 40.

      Input

      Each test case is described using several lines. The first line contains three integers N , M and D
      representing respectively the number of bars (2 ≤ N ≤ 100), the number of springs (1 ≤ M ≤ 104 )
      and the needed distance between bars 0 and N − 1 (1 ≤ D ≤ 105 ). Each of the next M lines describes
      a spring using two distinct integers A, B and an integer K, indicating that there is a spring connecting
      bars A and B (0 ≤ A, B ≤ N − 1) with spring constant K (1 ≤ K ≤ 105 ).
      The last test case is followed by a line containing three zeros.

      Output

      For each test case output a line with the lowest possible value of the maximum elastic force in a valid
      configuration. Your answer should be rounded to two decimal digits.

      Example

      Input:
      3 2 5
      1 0 1
      1 2 1
      3 3 5
      1 0 1
      1 2 1
      0 2 2
      4 4 10
      0 2 10
      1 2 20
      1 3 10
      2 3 1
      0 0 0

      Output: 2.50
      10.00
      40.00

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Unicamp









      SPOJ Problem Set (classical)

      10454. Greens Land

      Problem code: GREENLAN

      Mr. Green has a large portion of land divided into square units that are either field or lake areas.
      He wants to fence a rectangular portion of his lands to use for livestock.
      The lake areas have a very soft soil and any fence built near those areas have a chance to fall (and
      then the animals could escape), so no fence should be built near a lake area.

      Green's Land

      Mr. Green wants to know of how many ways he can fence a rectangular area of his lands without
      any portion of the fence having a common border with a lake area.
      In the example above, for a 3x3 land with a lake area in the center, we have 5 possibilities of fence.

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:
      One line with a integer N (1 ≤ N ≤ 300): the size of the land (N xN ).
      N lines, each with N characters. Each character is either ‘.’ or ‘X’. The j − th character on the
      i − th line is a ‘X’ if position (i, j) is a lake area, and ‘.’ if it is a field area.

      Output

      For each test case output a line with the number of different valid ways wich Mr. Green can fence his
      lands.

      Example

      Input:
      4
      3
      ...
      .X.
      ...
      3
      X..
      ...
      X..
      6
      ......
      ......
      ......
      ......
      ......
      ......
      5
      .....
      ....X
      .X...
      .....
      ...XX
      Output: 5
      8
      441
      23

      Added by:Paulo Costa
      Date:2012-01-19
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10460. A function over factors

      Problem code: IOPC1204

      A function f is defined over natural numbers as:

      f(N) = ∑ di μ(di)

      Here the summation is over di, all positive integers which are factors of N.

      μ(n) is the Möbius function defined in the following way: If there exists a prime p such that p2 is a factor of n, then μ(n)=0. Otherwise, if n has an odd number of prime factors, μ(n)=-1. If not, μ(n)=1. Thus the first few values for μ(n) (starting from 1) are 1, -1, -1, 0, -1, 1, -1, 0...

      Given an integer X (0 <= X <= 1012), find the smallest natural number N such that |f(N)|>X.

      Input

      The first line of the input contains T, the number of test cases (T <= 1000). Following this are T lines, each containing an integer X (0 <= X <= 1012) corresponding to the test case.

      Output

      For each test case in the input, output the smallest natural number N such that |f(N)|>X.

      Example

      Input:
      2
      1
      2
      
      Output:
      3
      5
      

      Added by:Raziman T V
      Date:2012-01-20
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://www.codechef.com/IOPC2012/









      SPOJ Problem Set (classical)

      10461. The magical escape

      Problem code: IOPC1205

      The nasty king of Dystopia has captured a group of travellers from Utopia. The king wants to toy with them, so he makes them play a little "game":

      The king will place everyone in solitary confinement. He has placed a bulb in a separate room which is controlled by a switch. Initially the bulb is off. Each day he picks a prisoner at random and takes him to the room. He can see whether the bulb is on or not, and choose whether to toggle the state of the bulb. This continues day after day. Now the king says that, once a prisoner realises that all of them have visited the special room at least once, he can convey it to the king and he will set everyone free. However, if someone makes such a claim wrongly, everyone will be executed. Before locking everyone up, the king would allow all prisoners to get together and decide a strategy.

      This would usually be a very diabolic game to play - However, among the prisoners there were some magicians who could communicate with each other telepathically. So they come up with this strategy. All magicians start counting from 0. Every time a non-magician who has never toggled the state of the bulb before enters the room and finds the lamp off, he turns it on. However if he finds it on already, or if he has toggled the state of the bulb before, he leaves it as is. Whenever a magician enters the room, he does the following:

      • If he is entering the room for the first time, he increases his counter by 1 and telepathically communicates this to all other magicians who update their counter as well.

      • If he finds the lamp on, whether or not he is a first timer, he turns it off and all magicians increase their counter by one.

       

      Finally when the magicians' counter reaches the total number of prisoners, they declare that everyone has been in the room at least once.

      Find the expected number of days that pass before this declaration occurs.

      Input

      The first line of the input contains T, the number of test cases (T ≤ 100). Following these are T lines corresponding to the test cases. Each line will contain two space separated integers N & M, the total number of prisoners and the number of magicians among them respectively (1 ≤ N ≤ 109, 1 ≤ M ≤ min(100,N))

      Output

      For each test case, output the expected number of days before the magicians declare that all prisoners have entered the room at least once. The output has to be formatted in the following fashion: #.######E+## That is, one nonzero digit before the decimal point, six digits after the decimal point and two digits for the exponent. See the sample test case for a formatting example.

      Example

      Input:
      2
      100 10
      1 1
      
      Output:
      1.408258E+03
      1.000000E+00
      

      Added by:Raziman T V
      Date:2012-01-20
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://www.codechef.com/IOPC2012/









      SPOJ Problem Set ()

      10463. COUNT PAREN

      Problem code: PAREN

      You are given a boolean expression consisting of a string of the symbols 'true', 'false', 'and', 'or', and 'xor'. Count the number of ways to parenthesize the expression such that it will evaluate to true.

      "and" "or" and "xor" are of the same priority.

      Input

      An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a space seperated string consisting of T,F,and,or and xor of length less than 100 characters

      Output

      For each string given at input, display a line with the number of ways to parenthesize the expression such that it will evaluate to true.

      Example

       Sample input:

      1
      T and F

       Sample output:

        0

       


      Added by:priyamehtanit
      Date:2012-01-21
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8
      Resource:mit tutorial









      SPOJ Problem Set ()

      10464. Reverse Engineering

      Problem code: RE1

      Sorting is a fascinating topic in computer science and mathematics. Once you get in depth with the sorting algorithms, you will be able to witness some NATURAL beauty. Lots of research has been done in this area. A beautiful but old problem related to sorting is to find the minimum number of adjacent swaps needed to sort some given numbers. But, those golden days of brainstorming are gone. Now almost everyone out there knows the solution to the problem; whether they properly understand sorting or not. Thus, researchers are sad and have decided to come up with a new problem. The problem is given below:

      You have N distinct integers. How many ways can you arrange the integers so that the minimum number of adjacent swaps needed to sort them in ascending order is K?

      Researchers cannot yet rate the toughness of this new problem but they believe that solving this problem will require good understanding of sorting algorithms. I do not agree with these researchers and want to join you all to prove them wrong. So I pass you the problem, can you solve it?

      Input

      Input starts with an integer T (<200000), denoting the number of test cases.

      Each case contains two integer N (1 ≤ N ≤ 100) and K (0 ≤ K ≤ 10000).

      Output

      For each case, print the desired result modulo 1000000007. 

      Example

      Input:
      

      3

      3 1

      10 45

      100 56 Output:

      Case 1: 2

      Case 2: 1

      Case 3: 904490303

      Added by:Samir Ahmed
      Date:2012-01-21
      Time limit:2s-3s
      Source limit:30000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem (Samir's Contest 2 @Lightoj)









      SPOJ Problem Set ()

      10465. One Theorem, One Year

      Problem code: OTOY1


      A number is Almost-K-Prime if it has exactly K prime numbers (not necessarily distinct) in its prime factorization. For example, 12 = 2 * 2 * 3 is an Almost-3-Prime and 32 = 2 * 2 * 2 * 2 * 2 is an Almost-5-Prime number. A number X is called Almost-K-First-P-Prime if it satisfies the following criterions:

      1.      X is an Almost-K-Prime and

      2.      X has all and only the first P (P ≤ K) primes in its prime factorization.

      For example, if K=3 and P=2, the numbers 18 = 2 * 3 * 3 and 12 = 2 * 2 * 3 satisfy the above criterions. And 630 = 2 * 3 * 3 * 5 * 7 is an example of Almost-5-First-4-Pime.

      For a given K and P, your task is to calculate the summation of Φ(X) for all integers X such that X is an Almost-K-First-P-Prime.

      In mathematics Φ(X) means the number of relatively prime numbers with respect to X which are smaller than X. Two numbers are relatively prime if their GCD (Greatest Common Divisor) is 1. For example, Φ(12) = 4, because the numbers that are relatively prime to 12 are: 1, 5, 7, 11.

      Input

      Input starts with an integer T (≤ 10000), denoting the number of test cases.

      Each case starts with a line containing two integers K (1 ≤ K ≤ 500) and P (1 ≤ P ≤ K).

      Output

      For each case, print the case number and the result modulo 1000000007.

      Example

      Input:

      3

      3 2

      5 4

      99 45

      Output:

      Case 1: 10

      Case 2: 816

      Case 3: 49939643

       


      ID RESULT TIME
      code...



      Added by:Samir Ahmed
      Date:2012-01-21
      Time limit:2s
      Source limit:30000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10466. Enough of analyzing, let’s play

      Problem code: EALP1

      All of must you know the game of Nim. For those who don’t know, I will describe the game in brief:

      There are two players and there are N piles. Each pile contains some stones. Player 1 takes the first turn, than player 2, than again player 1 and so on. At each turn, the player chooses any ONE pile, and removes at least one stone from it. The player who makes the last move wins.

      Now given N piles, your task is to find the number of ways Player 1 can start the game so that after his first move, he is in the winning position.  That means after Player 1 has removed some stones from any ONE pile, he will surely win the game if he plays optimally no matter how well Player 2 plays the game.

      Input

      Input starts with an integer T (≤ 1000), denoting the number of test cases.

      Each case starts with an integer N (1 ≤ N ≤ 1000). The next line contains N integers all less than 1000. The ith integer denotes the number of stones in the ith pile.

      Output                                       

      For each case, print the desired result. 

      Example

      Input:
      

      2

      3

      11 15 8

      3

      11 15 7

      Output:

      Case 1: 3

      Case 2: 3


      ID RESULT TIME
      code...



      Added by:Samir Ahmed
      Date:2012-01-21
      Time limit:2s
      Source limit:30000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem (Samir's Contest 2 @Lightoj)









      SPOJ Problem Set (classical)

      10471. Aliens at the train, again!

      Problem code: ALIEN2

      The Alien who doesn’t like to see humans has moved to an Urban City (Yes, a little ironic) and now she’s facing a double-train system, but still, the alien hates humans, so she wants to see the minimum quantity of people possible in her way to the university at the two trains.

      The Alien has some sort of anthropophobia, this means she has a phobia to the people or the society, knowing this, she tells you that can only see K persons in the train, if she sees more than that, she will have a panic attack.

      With her special powers, the alien knows how much people is on every station of the train A and the train B, she asked you to make a program that, given the number of people in the stations of the train A and B and the maximum number of people she wants to see, you give her the number of stations she will have to cross and the minimum persons found in those stations. Knowing that:

      • The Alien starts from train A or B (she can choose where to start) but from the station 1.
      • She can switch from train A or B or viceversa, if she does this, she will see Ai+Bi people, being “i” the station she’s at that moment.
      • If she sees strictly more persons than the specified, she will automatically exit the train.

      INPUT:

      The input will contain two integers N (1<=N<=10,000) and K (1<=65,000) being the number of stations and the maximum number of people that the alien wants to see, then, 2 lines will follow, each containing N integers separated by a single space denoting the number of people found in the j-th station of the i-th train. (1<=Ni<=100)

      OUTPUT:

      Two single numbers denoting the number of stations passed and the people seen.

       

      SAMPLE DATA:

      INPUT:

      3 10

      9 2 4

      1 2 9

      OUTPUT:

      3 9

      INPUT2:

      5 10

      1 7 1 1 1

      2 2 2 2 2

      OUTPUT2:

      5 9

       

      Explanation I/O 1: The alien starts at the train B station 1, she sees 1 people, she continues to the station 2 and then decides to change the train, the alien have seen 4 more people, and then she continues at the train A up to the station 3. At this point the Alien will see (1+4+4) people (9) and has passed 3 stations.


      Added by:David Moran
      Date:2012-01-22
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10476. Fair bases

      Problem code: IOPC1206

      Consider integers N and K such that 2 ≤ K ≤ N. Write all the numbers 0 ≤ i < N in base K, adding leading zeros where necessary so that all the numbers are of equal length in base K. The score of an integer i (0 ≤ i < N) in the list is defined in the following fashion : Consider the first digit of i in base K. Count the total number of times this digit occurs as first digit of some integer in the list. This is the score of the first digit of i. The number of times the second digit of i appears as the second digit of some integer in the list is the score of the second digit of i, and so on. The sum of scores of all digits of i is the score of i.

      As an example, suppose N=4 and K=3. Then the numbers in the list are 00,01,02 and 10. Let us find the score of i=00. The first digit of i appears as the first digit thrice (00,01,02) and the second digit of i appears as second digit twice (00,10). Thus the score of 00 is 3+2=5.

      An integer K (2 ≤ K ≤ N) is called a fair base of N if the scores of all i (0 ≤ i < N) are equal for base K. The number of fair bases in the range 2 ≤ K ≤ N is termed the fairness factor of the integer N.

      Given integers a and b (2 ≤ a ≤ b ≤ 1012), find the sum of fairness factors of all i such that a ≤ i ≤ b.

      Input

      The first line of input contains T, the number of test cases (T ≤ 20). Following these are T lines, each containing two space separated integers a and b (2 ≤ a ≤ b ≤ 1012).

      Output

      For each (a,b) pair in the input, output the sum of fairness factors of i in the range a ≤ i ≤ b.

      Example

      Input:
      2
      4 8
      20 30
      
      Output:
      9
      27
      

      Added by:Raziman T V
      Date:2012-01-25
      Time limit:6s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://www.codechef.com/IOPC2012/









      SPOJ Problem Set (classical)

      10477. GM plants

      Problem code: IOPC1207

      The latest attraction for Techkriti 2112 is is a huge display of genetically modified plants. The arrangement consists of a cuboidal box of size Nx × Ny × Nz made of unit cubes. Each unit cube is identified using (x,y,z) coordinates - x ranges from 0 to Nx-1 and so on - and contains a plant genetically modified to show fluorescence. The natural colour of the plants is green. However, on exposing a plant to laser light, it changes colour to red. What is more interesting is that on exposing a red plant to laser light again, it changes back to green and this continues.

      The organisers have realised that they can use the display to make many coloured patterns. They have with them a laser light sheet which they can place along an axis and move in one direction, exposing many plants to light at once. For example, if the plane of the light sheet is kept as the y axis and it is moved from a to b, every plant with the y coordinate between a and b inclusive will turn from green to red or red to green. Every time the laser is operated, it is only the plants with one specific coordinate in a certain range which are affected.

      You are told that initially all plants were green. Given the sequence of exposing plants to laser light, your task is to find the number of red coloured plants in certain cuboidal subregions of the display

      Input

      The first line of the input contains T, the number of test cases (T ≤ 10). Following this are the descriptions of the T test cases. The description of each test case starts with a line containing four space separated integers : Nx, Ny, Nz and Q (1 ≤ Nx,Ny,Nz ≤ 100000; Q ≤ 5000). The first three are the extents of the display in the three dimensions while Q is the number of queries which are to follow. Following this are Q lines, each describing a query. A query will be of one of the following forms :

      • 0 i j : expose all plants with x coordinates i ≤ x ≤ j to laser light
      • 1 i j : expose all plants with y coordinates i ≤ y ≤ j to laser light
      • 2 i j : expose all plants with z coordinates i ≤ z ≤ j to laser light
      • 3 x1 y1 z1 x2 y2 z2 : Report the number of red plants in the cuboidal region with (x1,y1,z1) and (x2,y2,z2) as diagonally opposite cells - ie, all red plants with x1 ≤ x ≤ x2, y1 ≤ y ≤ y2 and z1 ≤ z ≤ z2

       

      All individual coordinates will be valid - ie, every x coordinate will be such that 0 ≤ x ≤ Nx-1 and so on. Also, i ≤ j; x1 ≤ x2; y1 ≤ y2 and z1 ≤ z2

      Output

      For every query of the form 3 x1 y1 z1 x2 y2 z2 in the input, output the number of red plants with coordinates constrained by x1 ≤ x ≤ x2, y1 ≤ y ≤ y2 and z1 ≤ z ≤ z2

      Example

      Input:
      1
      3 4 5 5
      0 1 2
      1 2 3
      3 0 0 0 1 2 3
      2 3 4
      3 1 1 1 2 2 2
      
      Output:
      12
      4
      

      Added by:Raziman T V
      Date:2012-01-25
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://www.codechef.com/IOPC2012/









      SPOJ Problem Set ()

      10500. Haybale stacking

      Problem code: HAYBALE

       

      Feeling sorry for all the mischief she has caused around the farm recently,
      Bessie has agreed to help Farmer John stack up an incoming shipment of hay
      bales.  
      She starts with N (1 <= N <= 1,000,000, N odd) empty stacks, numbered 1..N.
      FJ then gives her a sequence of K instructions (1 <= K <= 25,000), each of
      the form "A B", meaning that Bessie should add one new haybale to the top
      of each stack in the range A..B.  For example, if Bessie is told "10 13",
      then she should add a haybale to each of the stacks 10, 11, 12, and 13.
      After Bessie finishes stacking haybales according to his instructions, FJ
      would like to know the median height of his N stacks -- that is, the height
      of the middle stack if the stacks were to be arranged in sorted order
      (conveniently, N is odd, so this stack is unique).  Please help Bessie
      determine the answer to FJ's question.

       

      Feeling sorry for all the mischief she has caused around the farm recently,

      Bessie has agreed to help Farmer John stack up an incoming shipment of hay

      bales.  

       

      She starts with N (1 <= N <= 1,000,000, N odd) empty stacks, numbered 1..N.

      FJ then gives her a sequence of K instructions (1 <= K <= 25,000), each of

      the form "A B", meaning that Bessie should add one new haybale to the top

      of each stack in the range A..B.  For example, if Bessie is told "10 13",

      then she should add a haybale to each of the stacks 10, 11, 12, and 13.

       

      After Bessie finishes stacking haybales according to his instructions, FJ

      would like to know the median height of his N stacks -- that is, the height

      of the middle stack if the stacks were to be arranged in sorted order

      (conveniently, N is odd, so this stack is unique).  Please help Bessie

      determine the answer to FJ's question.

      INPUT

       

      * Line 1: Two space-separated integers, N K.

       

      * Lines 2..1+K: Each line contains one of FJ's instructions in the

              form of two space-separated integers A B (1 <= A <= B <= N).

       

      SAMPLE INPUT 

      7 4

      5 5

      2 4

      4 6

      3 5

       

      INPUT DETAILS:

       

      There are N=7 stacks, and FJ issues K=4 instructions.  The first

      instruction is to add a haybale to stack 5, the second is to add haybales

      to stacks 2..4, etc.

       

      OUTPUT FORMAT:

       

      * Line 1: The median height of a stack after Bessie completes the

              instructions.

       

      SAMPLE OUTPUT 

      1

       

      OUTPUT DETAILS:

       

      After Bessie is finished, the stacks have heights 0,1,2,3,3,1,0.  The median

      stack height is 1, since 1 is the middle element in the sorted ordering

      0,0,1,1,2,3,3.

       

       

       

       

       


      Added by:სვანიძე
      Date:2012-01-29
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:Usaco 2012 January bronze









      SPOJ Problem Set (classical)

      10502. Video game combos

      Problem code: VIDEO


      Bessie is playing a video game! In the game, the three letters 'A', 'B', and 'C' are the only valid buttons. Bessie may press the buttons in any order she likes. However, there are only N distinct combos possible (1 <= N <= 20). Combo i is represented as a string S_i which has a length between 1 and 15 and contains only the letters 'A', 'B', and 'C'.

      Whenever Bessie presses a combination of letters that matches with a combo, she gets one point for the combo. Combos may overlap with each other or even finish at the same time! For example if N = 3 and the three possible combos are "ABA", "CB", and "ABACB", and Bessie presses "ABACB", she will end with 3 points. Bessie may score points for a single combo more than once.

      Bessie of course wants to earn points as quickly as possible. If she presses exactly K buttons (1 <= K <= 1,000), what is the maximum number of points she can earn?

      Input description

      * Line 1: Two space-separated integers: N and K.
      * Lines 2..N+1: Line i+1 contains only the string S_i, representing combo i.

      Output description

      * Line 1: A single integer, the maximum number of points Bessie can obtain.


      Example

      Input:
      3 7
      ABA
      CB
      ABACB
      
      Output:
      4
      

      Example details

      The optimal sequence of buttons in this case is ABACBCB, which gives 4 points:
      1 for ABA, 1 from ABACB, and 2 from CB.


      Added by:სვანიძე
      Date:2012-01-29
      Time limit:0.5s-100s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Usaco 2012 January gold division. belongs to NEAL WU









      SPOJ Problem Set (classical)

      10506. Prendonians

      Problem code: PRENDON

       

      The ancient civilization of the Prendonians, who lived in Jutland from 5000 BC to 4500
      BC, is well known. A Prendonian name is composed of three non empty words formed by
      lowercase letters from a to z: an unique first name, one of their parents’ fist name with a
      suffix and the other parent’s name with the same suffix. The unique first name always comes
      first, but there is no specific order for the other two.
      The suffix denotes the gender of the bearer of the name, jk for male and gvw for female,
      for example, if ric is igo and malte’s son, his full name would be ric igojk maltejk, but had
      ric been a girl, his name would have been ric igogvw maltegvw.
      All the Prendonians were monogamic and faithful to their partners. There are no registers
      of male homosexual couples, but it was common for two women to be married, and there has
      not been a single case of married siblings in Prendonian history. A couple was not considered
      married until they had given birth to a child or adopted one.
      Given N 3 word names, write a program that prints Y ES if they are all valid and part of
      a valid Prendonian family tree and everyone is related to everyone else, print N O otherwise.

       

      The ancient civilization of the Prendonians, who lived in Jutland from 5000 BC to 4500

      BC, is well known. A Prendonian name is composed of three non empty words formed by

      lowercase letters from a to z: an unique first name, one of their parents’ fist name with a

      suffix and the other parent’s name with the same suffix. The unique first name always comes

      first, but there is no specific order for the other two.

      The suffix denotes the gender of the bearer of the name, jk for male and gvw for female,

      for example, if ric is igo and malte’s son, his full name would be ric igojk maltejk, but had

      ric been a girl, his name would have been ric igogvw maltegvw.

      All the Prendonians were monogamic and faithful to their partners. There are no registers

      of male homosexual couples, but it was common for two women to be married, and there has

      not been a single case of married siblings in Prendonian history. A couple was not considered

      married until they had given birth to a child or adopted one.

      Given N 3 word names, write a program that prints Y ES if they are all valid and part of

      a valid Prendonian family tree and everyone is related to everyone else, print N O otherwise.

       

       

      Input

       

      The first line consists of a single integer T (1 ≤ T ≤ 30), which is the number of test

      cases. Each test case begins with a line with only the integer N (1 ≤ N ≤ 1000), the number

      of names, followed by N lines with 3 word (a-z lowercase only, each word not longer than 103

      characters), the first word is garanteed to be unique.

       

      Output

       

      For each test case print YES if the names are all valid and part of a valid Prendonian

      family tree and are all related to each other, print NO otherwise.

       

      Example

      Input:
      1
      3
      docs afegvw fegvw
      draw rridajk cajk
      pito docsjk drawjk
      
      Output:
      YES

      Added by:Paulo Costa
      Date:2012-01-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFPR









      SPOJ Problem Set ()

      10507. Cheese-rolling World Cup

      Problem code: CHEESE

       

      Nlogonian people is very excited about the event that will occur in the next year: the
      Cheese-rolling World Cup Nlogonia 2013! The event is organized by the Modern Cheeserolling Association (MCA or ACM, as spelled in Nlogonish) every four years, and this will be
      the first time that such an event is held in Nlogonia.
      The project, however, is still being worked on. ACM didn’t announce the list of host
      cities yet, but, instead, it announced how the cities will be chosen. It’s worth mentioning
      that Nlogonia was attacked by some kind of giant cannon in 2009, so the facilities in the cities
      are damaged and can’t be fully considered (at least not now). Instead, a city will be chosen
      according to how easy its name is pronounced.
      Let’s define the pronunciation power (pp) of a city name S as the sum of the lengths of
      all its palindromic contiguous substrings with even positive length. For example, consider the
      name abbaxx. Its substrings with even positive length are {ab, bb, ba, ax, xx, abba, bbax, baxx,
      abbaxx}. Of these, the palindromic ones are {bb, xx, abba} and thus pp(abbaxx) = |bb| +
      |xx| + |abba| = 8. Repeated substrings should be considered as many times as they occur (so
      pp(aaa) = |aa| + |aa| = 4, since aa occurs twice). Also, letter comparisons are case insensitive
      (so pp(aBbAxX) = 8, too), since the pronunciation is independent of the letter case.
      Nlogonia has N cities. Let K be a number given by ACM. The cities whose names have a
      pronunciation power equal or greater than the K th unique highest power of all N cities will be
      chosen. Notice that it’s possible to choose more than K cities. For example, consider K = 3
      and N = 6 cities whose names have the powers 2, 4, 4, 8, 8 and 16. The first 3 unique higher
      powers are 16, 8 and 4, so all cities except the first one will be chosen.
      The 2009 cannon attack also damaged the roads between the cities. There’are only M
      one-way roads available to use in Nlogonia (if a road connects city A to B, it can’t be used to
      go from B to A). Also, due the damages made by the cannon, each road has a traffic flow limit.
      Nlogonia’s capital is the only city with an airport, so all the foreign people will come to
      Nlogonia via the capital and go to the host cities using the road network cited above. Your
      task is to help the Nlogonian people know the list of cities that will be chosen, and, for each
      one, know what is the maximum traffic flow possible from the capital to the city, so they
      know if the roads will handle the traffic well during the event. During the World Cup, each
      match will be played in a different date and city, so consider the chosen cities independently
      (in other words, calculate the flow between the capital and the first chosen city as if it was
      the only chosen one; then do the same with the second chosen one, and so on).

       

      Nlogonian people is very excited about the event that will occur in the next year: the

      Cheese-rolling World Cup Nlogonia 2013! The event is organized by the Modern Cheeserolling Association (MCA or ACM, as spelled in Nlogonish) every four years, and this will be

      the first time that such an event is held in Nlogonia.

      The project, however, is still being worked on. ACM didn’t announce the list of host

      cities yet, but, instead, it announced how the cities will be chosen. It’s worth mentioning

      that Nlogonia was attacked by some kind of giant cannon in 2009, so the facilities in the cities

      are damaged and can’t be fully considered (at least not now). Instead, a city will be chosen

      according to how easy its name is pronounced.

      Let’s define the pronunciation power (pp) of a city name S as the sum of the lengths of

      all its palindromic contiguous substrings with even positive length. For example, consider the

      name abbaxx. Its substrings with even positive length are {ab, bb, ba, ax, xx, abba, bbax, baxx,

      abbaxx}. Of these, the palindromic ones are {bb, xx, abba} and thus pp(abbaxx) = |bb| +

      |xx| + |abba| = 8. Repeated substrings should be considered as many times as they occur (so

      pp(aaa) = |aa| + |aa| = 4, since aa occurs twice). Also, letter comparisons are case insensitive

      (so pp(aBbAxX) = 8, too), since the pronunciation is independent of the letter case.

      Nlogonia has N cities. Let K be a number given by ACM. The cities whose names have a

      pronunciation power equal or greater than the K th unique highest power of all N cities will be

      chosen. Notice that it’s possible to choose more than K cities. For example, consider K = 3

      and N = 6 cities whose names have the powers 2, 4, 4, 8, 8 and 16. The first 3 unique higher

      powers are 16, 8 and 4, so all cities except the first one will be chosen.

      The 2009 cannon attack also damaged the roads between the cities. There’are only M

      one-way roads available to use in Nlogonia (if a road connects city A to B, it can’t be used to

      go from B to A). Also, due the damages made by the cannon, each road has a traffic flow limit.

      Nlogonia’s capital is the only city with an airport, so all the foreign people will come to

      Nlogonia via the capital and go to the host cities using the road network cited above. Your

      task is to help the Nlogonian people know the list of cities that will be chosen, and, for each

      one, know what is the maximum traffic flow possible from the capital to the city, so they

      know if the roads will handle the traffic well during the event. During the World Cup, each

      match will be played in a different date and city, so consider the chosen cities independently

      (in other words, calculate the flow between the capital and the first chosen city as if it was

      the only chosen one; then do the same with the second chosen one, and so on).

       

       

      Input

       

      The input will consist of one or more test cases. Each test case starts with a line containing

      three integers N (1 ≤ N ≤ 200), M (1 ≤ M ≤ N (N − 1)) and K(1 ≤ K ≤ 10). The cities are

      numbered from 0 to N − 1, and the capital is the city number 0. Each of the N next lines

      contains the names of the cities, in increasing order of their numbers. Each name will contain

      only upper and lower case English letters, and its length will not exceed 30000. Each of the

      M next lines will describe the road network of the country. Each line will be in the form A

      B C (0 ≤ A, B < N, A = B, 1 ≤ C ≤ 109 ) and indicates a road connecting city A to city

      B with traffic flow limit C. There won’t be more than one road connecting a pair of cities

      in the same direction, and it will always be possible to go from the capital to any other city.

      The last test case will be followed by a line containg three zeros.

       

      Output

       

      For each test case, print one line with k - the number of chosen cities. Then, print k

      lines in the format n (pp) f , where n is a city name, pp is its pronunciation power and f is

      the maximum flow from the capital to the city. Print the cities in increasing order of their

      numbers. Also, if the capital is a chosen city, use f = 0. You may assume that k ≤ 2K for

      each test case.

       

      Example

      Input:
      3 4 2
      Curitiba
      LalLal
      Idappadi
      0 1 2
      2 1 1
      0 2 3
      1 2 6
      4 5 3
      heeymacarena
      haay
      abbaxx
      ddxdd
      0 3 20
      0 2 10
      2 3 5
      3 1 10
      2 1 20
      0 0 0
      
      
      Output:
      2
      LalLal (12) 3
      Idappadi (20) 5
      4
      heeymacarena (2) 0
      haay (2) 20
      abbaxx (8) 10
      ddxdd (4) 25
      

      Added by:Paulo Costa
      Date:2012-01-30
      Time limit:35s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFPR









      SPOJ Problem Set ()

      10508. Buttons

      Problem code: BTTNS


      Luis has a new toy, is a weird board with NxM cells. The cells can be white or
      black.
      Each cell has a button inside, when you press a button every cell with Manhattan
      distance equal or less than K to the cell with the button pressed change of color
      ( white to black, or black to white ).
      At the beginning, every cell is white but somebody pressed some buttons and now
      the board has some black cells.
      Help Luis to find how many buttons were pressed.
      You can assume that no button will be pressed two or more times.
      There will be always only one configuration of buttons pressed that generate the
      final board.

      Input

      The first line of input contains an integer t<=10, the number of test cases. It is
      followed by t test cases, each consisting of N+1 lines. The first line of each case
      contains three integers N,M,K separated by space (1<=N,M<=20 , 0<=K<=20).
      The next N lines contains M integers, each integer can be 0 or 1, the final state of
      each cell. ( 0 is white, 1 is black )

      Output

      For each case, output a single line consisting of the number of buttons pressed.

      Example

      Input:
      2
      2 2 0
      1 0
      0 1
      2 2 1
      1 1
      1 1 Output: 2
      4

      Added by:Paulo Costa
      Date:2012-01-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UGTO









      SPOJ Problem Set (classical)

      10509. Cards

      Problem code: CRDS

      Maricruz have a lot of cards, she always uses her cards to build pyramids as shown
      in the following image:
      A pyramid card of 3 leves.
      She always wonder how many cards does she need to make a pyramid card of N
      levels. Your task is to answer that question.
      Input
      The first line of the input contains an integer 1<= T <= 1,000. Each of the
      following T lines will have an integer 1<= N <= 1,000,000.
      Output
      For each case, output a single line consisting of the number of cards needed to
      build a pyramid card of level N modulo 1,000,007.


      Input Example
      2

      3

      7
      Output Example
      15
      77


      Added by:Paulo Costa
      Date:2012-01-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UGTO









      SPOJ Problem Set (classical)

      10510. Sorting Machine

      Problem code: SRTMACH

      Once upon a time, there was a machine, a sorting machine called Conchita, she
      was not very efficient, most of the times she even couldn't sort the data correctly,
      and she only could process a list of 2<=N<=10 numbers, her algorithm was the
      following,
      she was programmed with 2 permutations of N numbers, each permutation F is
      given by N numbers, f1,f2...fN, such that 1<=fi<=N, fi!=fj for i!=j and means that
      if she apply F to the given list, she gets a list where the fi element, corresponds to
      the i element on the original list, then she forms a set of rearrangements of the
      original list, applying any of these permutations any number of times, in any order
      to the given list, so she forms all possible rearrangements using the given
      permutations, then she chooses to output the one that minimize the first element, if
      there is any tie, she chooses the one that minimize the second element and if there
      is any tie, she looks at the third element, and so on...
      Her creator, a robot called Robotina, was very curious about Conchita's behavior,
      she chooses an integer 1<=M<=10, an then she tries all possible lists, a1,a2..aN,
      such that 1<=ai<=M, and then for each input, she sends it to Conchita, and
      receives an output, then she asks herself, how many possible different outputs does
      Conchita can compute? (Two outputs are considered different if at least one
      element differs).
      Your task, find this number MOD 98765431.

      Input
      The first line of input contains an integer T<=10, the number of test cases. It is
      followed by T test cases, the first line of each test case contains 2 integer numbers,
      N, M, then is followed by K lines, each one consisting on N numbers.
      Output
      For each case, output a single line consisting of the number of different outputs
      MOD 98765431.

      Input Sample
      2
      2 2
      1 2
      2 1
      3 3
      2 1 3
      3 1 2
      Output sample
      3
      10


      Added by:Paulo Costa
      Date:2012-01-30
      Time limit:50000s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UGTO









      SPOJ Problem Set (classical)

      10514. K12 - Building Construction

      Problem code: KOPC12A

       

               Given N buildings of height h1,h2,h3...hn, the objective is to make every building has equal height. This can be done by removing bricks from a building or adding some bricks to a building.Removing a  brick or  adding  a brick is done at certain cost which will be given along with the heights of the buildings.Find the minimal cost at which you can make the buildings look beautiful by re-constructing the buildings such that the N buildings satisfy 

      h1=h2=h3=..=hn=k ( k can be any number).

      For convenience, all buildings are considered to be vertical piles of bricks, which are of same dimensions. 

       

               Given N buildings of height h1,h2,h3...hn, the objective is to make every building has equal height. This can be done by removing bricks from a building or adding some bricks to a building.Removing a  brick or  adding  a brick is done at certain cost which will be given along with the heights of the buildings.Find the minimal cost at which you can make the buildings look beautiful by re-constructing the buildings such that the N buildings satisfy 
      h1=h2=h3=..=hn=k ( k can be any number).

      Input

       

      The first line of input contains an integer T which denotes number of test cases .This will be followed by 3*T lines , 3 lines per test case. The first line of each test case contains an integer n and the  second line contains n integers which denotes the heights of the buildings [h1,h2,h3....hn] and the third line contains n integers [c1,c2,c3...cn] which denotes the cost of adding or removing one unit of brick from the corresponding building.

      T<=15;n<=10000;0<=Hi<=10000;0<=Ci<=10000;

      Output

       

      The output must contain T lines each line corresponding to a testcase.

       

      Example

      Input:
      1
      3
      1 2 3
      10 100 1000
      
      
      Output:
      120


      Added by:Radhakrishnan
      Date:2012-01-31
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      10515. K12-Combinations

      Problem code: KOPC12B

       

      (nC1)^2+2*(nC2)^2+3*(nC3)^2+4*(nC4)^2+............+n*(nCn)^2.   % MOD
      where MOD=10^9+7;
      Input Format:
      The first line of input file contains T which denotes number of testcases.Each of the following line contains an integer n. T<=1000 && n<=10^6.
      Output Format:
      The output must contain T lines each line corresponding to a testcase.
      Input
      2
      1
      2
      Output:
      1

      Given n  find the value of ((nC1)2+2*(nC2)2+3*(nC3)2+4*(nC4)2+............+n*(nCn)2)% MOD

      where MOD=10^9+7.

      Note: nCr is the number of ways of choosing r items from n items.

      Input

      The first line of input file contains T which denotes number of testcases.Each of the following line contains an integer n. T<=1000 && n<=10^6.

      Output

      The output must contain T lines each line corresponding to a testcase.

      Example

      Input:
      2
      1
      2
      
      
      Output:
      1
      6

      Added by:Radhakrishnan
      Date:2012-01-31
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10517. K12-Generating Big Numbers II

      Problem code: KOPC12D

       

      You are given the count of each digits and you have to create a number with these available digits.Let the number be X. In X each digit should not occupy any position which is divisible by the digit. 2 shouldn't occupy 2,4,6,8.. th positions and 7 shouldn't occupy 7,14th positions. Position of unit's place is 1, hundreds' place is 2. Suppose X =abcdef, f is in position 1 ,e is in position 2,d is in position 3, a is in position 6.
      Now Find the length of smallest X as possible while filling the remaining postions with zeros.
      Example: Count of 2=2,Count of 4 =2.
      X can  be  40242,20442. But we need only the length of the number which is 5.

       

      You are given the count of each digits and you have to create a number with these available digits.Let the number be X. In X each digit should not occupy any position which is divisible by the digit. 2 shouldn't occupy 2,4,6,8.. th positions and 7 shouldn't occupy 7,14th positions. Position of unit's place is 1, hundreds' place is 2. Suppose X =abcdef, f is in position 1 ,e is in position 2,d is in position 3, a is in position 6.

      Now Find the length of smallest X  possible while filling the remaining postions with zeros.Minimize the length of the number generated.

      Example: Count of 2=2,Count of 4 =2.

      X can  be  40242, 20442. But we need only the length of the number which is 5.

       

      Input

       

      The first line of input file contains T which denotes the number of test cases.This is followed by T lines where each of these T lines contains 8 space seperated integers which denotes the count of 2's , count of 3's,count of 4's .. upto count of 9's.

      Note: Count of 1's will not be given as 1 divides every position of the number and Zeros can be placed in any position.

      T<=50,count of each digit<=20.

       

      Output

       

      The output should contain T lines each line with the answer  corresponding to a test case.

       

      Example

      Input:
      2
      2 0 2 0 0 0 0 0 
      20 20 20 20 20 20 20 20
      
      
      Output:
      5
      160
      
      

      Added by:Radhakrishnan
      Date:2012-01-31
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10519. K12-Bored of Suffixes and Prefixes

      Problem code: KOPC12G

       

      You are given an alphabetical matrix of size NxN .You have to perform two kinds of operations 1) Update and 2) query.The matrix contains only Uppercase English alphabets.
      Update operation is to replace a row or  column of the matrix with the given string.
      Query Operation returns the count of each alphabest in the query region.
      The operations are given as
      A) 0  x y str -> Replace  y th row with string str if x=0 or update yth column with string str (top to bottom) if (x=1)
      B) 1   x1 y1 x2 y2 -> Count the number of each alphabets in the rectangular region where (x1,y1) is topleft point of the rectangle and (x2,y2) is the bottom right point of the rectangle.
      For count operation Print Output;
      where Output=1*number  of A's + 2*number of B's + ...... 26*number of Z's;

      You are given a matrix of size NxN containing only upper case alphabets .You have to perform two kinds of operations: 

      Replace operation is to replace a row or column of the matrix with the given string.

      Count Operation returns the count of each alphabet in the required region.

      The operations are given as

      0 x y str -> Replace  y th row with string str, if x=0 or update yth column with string str (top to bottom), if x=1

      1 x1 y1 x2 y2 -> Count the number of each alphabets in the rectangular region of the matrix where (x1,y1) is top-left point of the rectangle and (x2,y2) is the bottom-right point of the rectangle.

      For every Count operation output the value of (1*number of A's + 2*number of B's + ...... 26*number of Z's).

       

      Input

       

      The first line of the input file contains T  which denotes the number of test cases.

      The first line of each test case contains two integers N and q where N denotes size of the matrix and q denotes the number of queries. This is followed by NxN alphabetic matrix. The matrix is followed by q lines of queries, in the above given format. 

      T<=10

      N<=500, Q<=10000

      0<=x1<N, 0<=x2<N, 0<=y1<N, 0<=y2<N 

      x1<=x2, y1<=y2

      Warning: Huge I/O

      Output

      Print the output for each query line by line.

      Example

      Input:
      1
      4 3
      ABCD
      ABCD
      ABCD
      ABCD
      1 0 0 3 3 
      0 0 2 PQRS
      1 0 2 3 3
      
      
      Output:
      40
      58

      Added by:Radhakrishnan
      Date:2012-01-31
      Time limit:1s-6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      10522. K12-OE Numbers

      Problem code: KOPC12H

       

      Rishi loves numbers  and number patterns very much.He is  interested in finding OE numbers in a range[a,b].An OE number is a number whose sum of even digits [0,2,4,6,8] is  greater than sum of odd digits [1,3,5,7,9].Help him to count how many OE numbers are in range [a,b] { a and b inclusive }
      Example: 4563, O=5+3=8, E=4+6 =10, E>O   so 4563 is an OE number
                          1233, O=1+3+3, E=2,             E<O    so 1233 is not an OE number 
                          10  ,    O=1, E=0         E<O   so 10 is not an OE number

       

      Rishi loves numbers  and number patterns very much.He is interested in finding OE numbers in a range[a,b].An OE number is a number whose sum of even digits [0,2,4,6,8] is  greater than sum of odd digits [1,3,5,7,9].Help him to count how many OE numbers are in range [a,b] { a and b inclusive }

      Example: 4563, O=5+3=8, E=4+6 =10, E>O   so 4563 is an OE number

                          1233, O=1+3+3, E=2,     E<O    so 1233 is not an OE number 

                          10  ,    O=1, E=0         E<O   so 10 is not an OE number

       

       

      Input

         The first line of the input file contains T which denotes the number of Test cases.The next T lines contains two space seperated integers a and b [a<=b] 1<=a<=b<=10^8];T<=35

       

      Output

       

      Print the number of OE numbers in range [ a,b] { one number per line}

       

      Example

      Input:
      3
      1 1
      2 10
      1 100000000
      
      
      Output:
      
      0
      4
      38379932

      Added by:Radhakrishnan
      Date:2012-01-31
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set ()

      10537. Edit Distance Again

      Problem code: EDIT

       

      As any experienced programmer must know the famous problem of "Edit Distance", however this
      problem is considered an “alternating chain” if you have alternately made case sensitive.
      Example:
      "AaAaAbB" "B" "a" "aBaCdEf"
      Alternating chains are considered in our problem.
      We only have one operation that is permitted in exchange for a lower or upper case Latin letter.
      Given a string giving the minimum number of changes to be considered an alternating chain.

       

      As any experienced programmer must know the famous problem of "Edit Distance", however this

      problem is considered an “alternating chain” if you have alternately made case sensitive.

      Example:

      "AaAaAbB" "B" "a" "aBaCdEf"

      Alternating chains are considered in our problem.

      We only have one operation that is permitted in exchange for a lower or upper case Latin letter.

      Given a string giving the minimum number of changes to be considered an alternating chain.

       

       

      Input

       

      A string with no spaces line containing only uppercase and lowercase letters, one for each line of

      maximum length 10 ^ 3 until end of file

       

      Output

       

      For each line print the minimum number of changes to the chain is a "chain alternately"

       

      Example

      Input:
      AaAaB
      ABaa
      a
      
      Output:
      0
      2
      0

      Added by:Paulo Costa
      Date:2012-02-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL
      Resource:PUCP









      SPOJ Problem Set (classical)

      10538. Derp

      Problem code: DERP

       

      Usually, producing methanphetamine is somewhat laborous and boring. There are
      some TV series who assume that there is a new way to produce it, being way cheaper
      than actually is. Nonsense. The fact is there is a new drug around, called Krokodil.
      This drug is a variation of morphine, which gives 8 to 10 times more hallucination
      than “meth”, costing up to 10 times less than it.
      Your friend Derp works in a “meth lab” and, while he was doing some tests,
      looking at the microscope, he found an interesting property: if he isolates the most
      far away pair of atoms in it, he will produce a substance as powerful (perhaps even
      more) as Krokodil is. This happens because one of the electron moves from one
      atom to the other.
      But, most of the times, there are hundreds, maybe thousands of particules in
      each sample, each of them using several layers, making kinda hard to find out
      which is the longest distance. There’s an unusual fact about this distance calculus:
      Each electron from these particules are kinda dumb; they are only able to move in
      horizontal and vertica axis. Also, since there are nanometrical layers, and distance
      is also considered for calculation between layers (which is the same), and a electron,
      in the layer L, with position (x, y), can only move to layers L + 1 and L − 1, if any
      of those exist, in the same relative position as in layer L.

       

      Usually, producing methanphetamine is somewhat laborous and boring. There are

      some TV series who assume that there is a new way to produce it, being way cheaper

      than actually is. Nonsense. The fact is there is a new drug around, called Krokodil.

      This drug is a variation of morphine, which gives 8 to 10 times more hallucination

      than “meth”, costing up to 10 times less than it.

      Your friend Derp works in a “meth lab” and, while he was doing some tests,

      looking at the microscope, he found an interesting property: if he isolates the most

      far away pair of atoms in it, he will produce a substance as powerful (perhaps even

      more) as Krokodil is. This happens because one of the electron moves from one

      atom to the other.

      But, most of the times, there are hundreds, maybe thousands of particules in

      each sample, each of them using several layers, making kinda hard to find out

      which is the longest distance. There’s an unusual fact about this distance calculus:

      Each electron from these particules are kinda dumb; they are only able to move in

      horizontal and vertica axis. Also, since there are nanometrical layers, and distance

      is also considered for calculation between layers (which is the same), and a electron,

      in the layer L, with position (x, y), can only move to layers L + 1 and L − 1, if any

      of those exist, in the same relative position as in layer L.

       

       

      Input

       

      Each input contains several test cases. The first line of every test case contains a

      number N , which is the number of particules of that sample (2 ≤ N ≤ 100, 000).

       

      After there are N lines to follow. Each of them contains 3 integers, li , xi , yi , which

      are the actual layer, the position corresponding corresponding to the X-axis, and

      the position corresponding to Y-axis (1 ≤ li , xi , yi ≤ 1, 000, 000, 000).

       

       

      Output

       

      For each output you print one integer, DIST AN CE, which corresponds to the value

      of the farthest distance between particules in the that sample.

       

      Example

      Input:
      5
      
      112
      
      341
      
      257
      
      411
      
      333
      
      Output:
      12

      Added by:Paulo Costa
      Date:2012-02-01
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:PUCP









      SPOJ Problem Set (classical)

      10539. Bunnies

      Problem code: BUNNIES

       

      Pompom bunny has N strange eggs. The i-th egg is broken by tapping it exactly Ai times. Pompom
      needs to break K eggs as soon as possible for cooking a rice omelet. However she has been put in an
      uncomfortable situation. Someone has shuffled the eggs! Pompom knows the values Ai, however she
      doesn't know which egg is which. She'd like to minimize the worst-case number of taps. What is the
      minimal number?

       

      Pompom bunny has N strange eggs. The i-th egg is broken by tapping it exactly Ai times. Pompom

      needs to break K eggs as soon as possible for cooking a rice omelet. However she has been put in an

      uncomfortable situation. Someone has shuffled the eggs! Pompom knows the values Ai, however she

      doesn't know which egg is which. She'd like to minimize the worst-case number of taps. What is the

      minimal number?

       

       

      Input

       

      The first line contains an integer T, the number of test cases. Then T test cases follow. The first line for

      each test case has 2 integers N and K. Then next line has N integers A1, A2, ..., AN.

       

      Output

       

      For each test case, print the minimal number of taps for the worst-case.

       

      Constraints

      1 <= T <= 10

      1 <= K <= N <= 3000

      1 <= Ai <= 1000000 (106)

       

       

       

      Example

      Input:
      3
      2 1
      5 8
      2 1
      5 58
      3 2
      1 2 3
      Output:
      8
      10
      5
      Output details
      In the first case, if a egg isn't broken after 5 taps, she should continue to tap the same egg.
      In the second case, if a egg isn't broken after 5 taps, she should tap another egg 5 times.
      

      Added by:Paulo Costa
      Date:2012-02-01
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:PUCP









      SPOJ Problem Set (classical)

      10547. Delivery Route

      Problem code: DELIVER


      After several years of record milk production, Farmer John now operates an entire network of N farms (1 <= N <= 100). Farm i is located at position (x_i, y_i) in the 2D plane, distinct from all other farms, with both x_i and y_i being integers. FJ needs your help planning his daily delivery route to bring supplies to the N farms. Starting from farm 1, he plans to visit the farms sequentially (farm 1, then farm 2, then farm 3, etc.), finally returning to farm 1 after visiting farm N. It tames FJ one minute to make a single step either north, south, east, or west. Furthermore, FJ wants to visit each farm exactly once during his entire journey (except farm 1, which he visits twice of course). Please help FJ determine the minimum amount of time it will take him to complete his entire delivery route.

      INPUT FORMAT: * Line 1: The number of farms, N. * Lines 2..1+N: Line i+1 contains two space-separated integers, x_i and y_i (1 <= x_i, y_i <= 1,000,000).

      Example:

      4

      2 2

      2 4

      2 1

      1 3

      OUTPUT FORMAT: * Line 1: The minimum number of minutes FJ needs to complete his delivery route, or -1 if it is impossible to find a feasible delivery route that visits every farm exactly once (except farm 1).

      output example:

      12

      Output Details: FJ can complete his delivery route in 12 minutes: 2 minutes to go from farm 1 to farm 2, 5 minutes to go from farm 2 to farm 3 (circumventing farm 1), 3 minutes to go from farm 3 to farm 4, and then 2 minutes to return to farm 1.


      Added by:Ikhaduri
      Date:2012-02-03
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: BF
      Resource:USACO JAN12









      SPOJ Problem Set (classical)

      10557. MINI IN DANGER!!!

      Problem code: MINI


      There is a n x n board.
      Tom is playing a game in which there are n*n blocks which can be filled with numbers from 0 to n-1 in some arbitrary way.
      The rule of the game is that the board should be filled in such a way that the sum of each row and column should be divisible by n.
      Tom has set the board in the winning configuration.But now the intelligent and notorious daughter of Tom, Mini comes and changes the configuration of the board.
      But she is scared now as her dad is about to come home.She realizes that dad will get angry if he sees that the board is not in the winning configuration and
      he will scold her.Mini wants to know the number of ways in which the board can be restored to a winning configuration.Please help her out.

      INPUT

      First line consits of an integer T and then T test cases follow.
      Having the value of N  

      OUTPUT

      For each test case you have to output the ways%1000000009 in a seperate line.

      Constraints:
      T <= 10^6
      N will be between 1 and 2^64-1 and not a multiple of 1000000009

      SAMPLE EXAMPLE
      Input:
      1
      1

      Output:
      1


      Added by:anuj
      Date:2012-02-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set ()

      10565. Alice Sieve

      Problem code: ALICESIE

       

      Alice has recently learned to use the Sieve of Eratosthenes, an ancient algorithm for finding all
      prime numbers up to any given limit. As expected, she was really impressed by it's simplicity and
      elegancy.
      Now, she has decided to design her own sieve method: The Sieve of Alice, formally defined by the
      following procedure, which determines the Sieve of Alice up to a given limit N.
      1. Create a list of consecutive integers from N to 2 (N, N-1, N-2, ..., 3, 2). All of those N-1
      numbers are initially unmarked.
      2. Initially, let P equal N, and leave this number unmarked.
      3. Mark all the proper divisors of P (i.e. P remains unmarked).
      4. Find the largest unmarked number from 2 to P – 1, and now let P equal this number.
      5. If there were no more unmarked numbers in the list, stop. Otherwise, repeat from step 3.
      Unfortunately, Alice has not found an useful application for it's Sieve. But she still wants to know,
      for a given limit N, how many integers will remain unmarked.

       

      Alice has recently learned to use the Sieve of Eratosthenes, an ancient algorithm for finding all

      prime numbers up to any given limit. As expected, she was really impressed by it's simplicity and

      elegancy.

      Now, she has decided to design her own sieve method: The Sieve of Alice, formally defined by the

      following procedure, which determines the Sieve of Alice up to a given limit N.

      1. Create a list of consecutive integers from N to 2 (N, N-1, N-2, ..., 3, 2). All of those N-1

      numbers are initially unmarked.

      2. Initially, let P equal N, and leave this number unmarked.

      3. Mark all the proper divisors of P (i.e. P remains unmarked).

      4. Find the largest unmarked number from 2 to P – 1, and now let P equal this number.

      5. If there were no more unmarked numbers in the list, stop. Otherwise, repeat from step 3.

      Unfortunately, Alice has not found an useful application for it's Sieve. But she still wants to know,

      for a given limit N, how many integers will remain unmarked.

       

       

      Input

       

      The first line contains an integer T, the number of test cases (1 ≤ T ≤ 10^4) . Each of the next T lines

      contains an integer N ( 2 ≤ N ≤ 10^6).

       

      Output

       

      Output T lines, one for each test case, containing the required answer.

       

      Example

      Input:
      3
      2
      3
      5
      Output:
      1
      2
      3

      Added by:Paulo Costa
      Date:2012-02-06
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UNI









      SPOJ Problem Set (classical)

      10568. Graph Cut

      Problem code: GRAPHCUT

      Given a graph G, and a subset of its vertices X. The associated cut of X is the set of edges
      associated to X is the subset of all edges in G such that exactly one of the two vertices it joins
      belongs to X.
      In thinks, you will be given a graph and a subset of its edges, and you will have to determine
      whether there exists a subset of the vertices of the graph for which the given subset of the edges
      is its associated cut.

      Input

      The first line contains an integer T, the number of test cases (1 ≤ T ≤ 40). Each test case, consists of
      a line which contains three integers N (2 ≤ N ≤ 500),E (1 ≤ E ≤ 104),K (1 ≤ K ≤ E), the number of
      vertices in the graph, and the number of edges in the subset for which we want to know whether
      it is an associated cut or not. Then, E lines follow, each of them contains two integers u,v (1 ≤ u,v ≤
      N) which are the vertices joined by the edge, the first K of these E lines represent the asked subset.

      Output

      Output T lines, one for each test case. If the asked subset is an associated cut, then print “YES”,
      otherwise print “NO”.

      Example

      Input:
      2

      3 3 1
      1 2
      2 3
      1 3

      12 17 6
      3 4
      5 6
      10 11
      1 5
      6 10
      4 8
      1 2
      2 3
      6 7
      7 8
      9 10
      11 12
      5 9
      2 6
      3 7
      7 11
      8 12 Output: NO
      YES

      Added by:Paulo Costa
      Date:2012-02-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UNI









      SPOJ Problem Set ()

      10570. Longest Common Substring

      Problem code: LONGCS

      Substrings are consecutive parts of a string. A problem usually solved with dynamic programming
      is to find the longest common substring problem is to find the longest string (or strings) that is a
      substring (or are substrings) of two strings.
      Your task is to find the length of the longest common substring of K strings.

      Input

      The first line contains an integer T, the number of test cases (1 ≤ T ≤ 20) . Each test case, consists
      of one line containing an integer K (1 ≤ K ≤ 10), and K lines, each containing a string (length of
      s <= 10^4), the strings only contain the character ‘a’ – ‘z’.

      Output

      Output T lines, one for each test case, containing the required sequence, with a blank space
      between consecutive terms. It is guaranteed that all terms in the sequence are integers.

      Example

      Input:
      2 
      2
      aaabbb
      bbaabb
      3
      icode
      coder
      contest Output: 4
      2

      Added by:Paulo Costa
      Date:2012-02-07
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UNI









      SPOJ Problem Set (classical)

      10571. Soccer Challenge

      Problem code: SOCCERCH

      A soccer field is divided into squared plots, like a grid of N rows and M columns. The length of a plot
      side is equal to 1. Fernando likes to practice running only through the boundaries of the plots, he
      does not like to go inside the plots.
      Some of the plots are muddy, and some others have been selected by Fernando as target plots. A
      plot may neither be muddy nor a target one.
      Starting at the top left corner, he would like to go through the field and return back to the starting
      point. All plots that lie inside the cycle of his path are considered to be inspected. To make things
      more interesting he would like his path not to intersect with itself in any point different than the
      starting point. Luckily, the plots boundaries are so wide that Fernando can go along the same
      boundary multiple times without intersecting his own path.
      Fernando would like to inspect all target plots, but not any muddy plots. Martin, who plays in the
      opposing team, challenged Fernando that he could do a shortest path starting from the lower right
      corner. Can you help Fernando to get his shortest path, and decide weather it is shorter than the one

      Input

      Input consist of many test cases.
      First line of input starts with two integers R and C (1<=R,C<=50), which defines the rows and
      columns the soccer field has been divided into.
      Next, the soccer field is described in R rows, each containing C characters. Chars I, X, and O,
      represents target plots (to inspect), muddy plots, and common plots respectively. The quantity of
      target plots plus the quantity of muddy plots will not exceed 10.
      There will be not spaces between the C characters of each line describing the soccer field.
      End of the input is indicated by a line containing two zeros, and should not be processed.

      Output

      The output of each test case should be a separate line consisting of the name of the player who has
      the shortest path to inspect the target plots but not the muddy plots, or the word “Tie” in case of a tie,
      followed by a number representing the length of the shortest path for that player. The examples may
      clarify the format.

      Example

      Input:
      1 1 
      I
      2 2
      XX
      XI
      2 2
      XI
      IX
      3 3
      III
      IXI
      III
      2 2
      IO
      OO
      0 0 Output: Tie 4
      Martin 4
      Tie 10
      Tie 18
      Fernando 4

      Added by:Paulo Costa
      Date:2012-02-07
      Time limit:300s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FAMAF-UNC









      SPOJ Problem Set (classical)

      10572. Cheating on the contest

      Problem code: CHEATCON

      For the first time the Skyrim Free School of Mathematics, Philosophy and Linguistics will host
      the Regular Expressions (regex) Contest (RegExCon). The contest happens this way: participants
      compete always against 1 opponent. One wins one loses. Only one will remain, the champion. In one
      dispute both participants receive a list with several regular expressions and for each regex the
      participants must calculate if several given words are recognized or not by the regex. As a member of
      the School you are participating, and want to win.
      So, to guarantee your victory, you have to write a program to solve the problem and let it
      executing in your Cool Stuff Calculator Machine at home. As a mage, expert in Alteration and Illusion,
      you can easily control your machine with your mind, so you can use your program while in the contest.
      It's forbidden to use magic in the contest, but coincidentally the Winterhold School will host some
      Mage Congress, so you don't need to worry, use your magic.
      A regular expression is used to describe a language (a set of words). Consider that the alphabet
      of all languages in this problem is {a, b}.
      A regex R is valid if:
      1) R is “a” or “b”;
      2) R is “(P.S)” where P and S are regular expressions;
      3) R is “(P|S)” where P and S are regular expressions;
      4) R is “(P*)” where P is a regular expression;
      Regular expressions can be nested. There is no ternary operation with operators “.” and “|”,
      neither binary operation with operator “*”. Words always start with “(“ and finish with “)”.
      Set L of words recognized by R is formed following next rules:
      1) If R is “(a)”, L = {a};
      2) If R is “(b)”, L = {b};
      3) If R is “(P.S)”, L = all words that can be obtained from a concatenation of words p and s,
      where p is recognized by P and s by S;
      4) If R is “(P|S)”, L = union of the sets of words recognized by P and S;
      5) If R is “(P*)”, R recognizes the concatenation of 0 or more words recognized by P.

      Input

      Input file contains several test cases. First line of a test case contains a regex (defined before, between 1 and 150). Next line
      contain an integer P (1 ≤ P ≤ 100). Each one of the next P lines contains a word formed by 'a's and 'b's (<= 50)
      that represents the following question: “Is this word recognized by the given regex?”.

      Output

      For each question described before, answer “Y” (no quotes) if the answer is “yes” or “N” (no quotes) if
      the answer is “not”. At the end of each test case print a blank line.

      Example

      Input:
      (a)
      3
      a
      b
      aa
      (a.b)
      3
      a
      ab
      b
      (a|b)
      4
      a
      b
      ab
      ba
      (a*)
      3
      a
      aaaaaaaaaaa
      aaaaabaaaaa
      ((a*).(b*))
      3
      bbbaaa
      aaabbb
      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb Output: Y
      N
      N
      N
      Y
      N
      Y
      Y
      N
      N
      Y
      Y
      N
      N
      Y
      Y

      Added by:Paulo Costa
      Date:2012-02-07
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFU









      SPOJ Problem Set ()

      10573. Problem Offensive Strategy

      Problem code: OFFSTRAT

       

      Foo Football Club is a very offensive soccer team. Its coach is planing a new attack strategy.
      In order not to change its image of offensive team, the coach wants to be sure that the new attack strategy is going to be strongly offensive. He is a very grumpy coach so he does not allow the players to make a pass that is not in the strategy sheet. In fact he is so mad that he does not allow the player who holds the ball to move.

      A attack strategy is strongly offensive if each football pass position inside the field goes to another football pass position inside the field which is in the same distance or closer to the enemy line of goal, and also it should be possible to reach the enemy goal from every pass position described in the strategy sheet.

      Input

       

      The first line of input consist of a number T (T<=20) representing the number of test cases, then T test cases follow describing a strategy.

       

      Each test case begins with two integers W and H (1<W,H<=100 , also W and H are even integers) representing the width and high of the soccer field. The goal lines is the line x = w and the goal is gotten form a pass point (x,y) if it is possible reach the point (w,h/2) from (x,y).

      These are followed by an integer number M (1<=M<1000000) the number of available passes in the strategy. The next M lines consist of four integer numbers x0, y0, x1, y1 (0<= x0,x1 <= W and 0<=y0,y1<=H). representing the start position (x0,y0), and the end position (x1,y1) of an available pass in.

       

      Output

       

      For each test case the output should consist of a single line containing “Yes” (without quotes) if the strategy is strongly offensive or “No” (without quotes) otherwise.

      Example

      Input:
      
      

      2

       

      2 2 1

      0 1 2 1

       

      2 2 4

      0 1 2 1

      0 0 1 1

      0 2 1 1

      1 1 2 1

      Output:
      
      

      Yes

      Yes

      Problem Offensive Strategy


      Added by:Paulo Costa
      Date:2012-02-07
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FAMAF-UNC









      SPOJ Problem Set (classical)

      10574. Soccer Ceremony

      Problem code: SCCCER

      There are four popular football teams in the region of Sao Paulo : Corinthians, Palmeiras, Santos and Sao Paulo. Exactly n players among those football teams were pre-selected for an award regarding their performance on the championship.

      Today is the big day when one of them will be awarded as the ultimate champion. The players have now arrived, and everyone remembered their seats row (which is the same for all the n players) but not their column number. And now, as one of the most basic and known rules about football ceremony's had been violated, you’re in a hurry to satisfy the rule by switching as few players as possible.

      This rule, which I guess you should be familiar with but we are going to state it for the sake of completeness, states that there cannot be 3 or more players from the same team sitting in consecutive seats.

       

      Input

      You’ll first be given an integer T, which represents the total number of test cases.
      Each test case consist of a single integer N (1<= N <= 20) that represents the number of players invited to the ceremony. This is followed by a string S of length N representing the team at which each player belongs to. Each character S[i] of S will be one of the following C, P, N, S, meaning that the player seated at position i belongs to Corinthians, Palmeiras, Santos or Sao Paulo respectively.
      Each test case will be separated by a new line.

      Output

      The output should consist of a single number per test case. That number should be the minimum number of players that need to change their seats to satisfy the rule, if there is no way to satisfy the rule output -1 instead.

      Example

      Input:
      

      1
      8
      CCCCCCPN

      3

      CCC

      Output:

      4

      -1


      Added by:Paulo Costa
      Date:2012-02-07
      Time limit:75s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FAMAF-UNC









      SPOJ Problem Set ()

      10575. The Yellow Brick Road

      Problem code: YELBRICK

      After Dorothy’s memorable adventure in the Land of Oz, traffic along the Yellow Brick Road got really intense, making some sections of it nearly impossible to cross because of the holes along the road. The Land of Oz engineers are having trouble to pave this road, because the yellow stone is in short supply, forcing them to buy stones from different suppliers. As you already know, every road in the Land of Oz must be built using bricks that are perfect and identical cubes. To maximize the durability of the road, it also must be built using the least number of bricks possible. The problem is that each supplier provides stones of different sizes, that must be cut in order to make the bricks for the road.

      Can you help the engineers to find which is the best brick size to use to maximize the road durability?


      Input

      Each test case is given using several lines. The first line contains an integer N representing the number of different suppliers of yellow stone (2 ≤ N ≤ 1000). For simplicity, we assume that the engineers will buy exactly one stone from each supplier. Each of the next N lines contains three integers Ai, Bi, Ci (0 < Ai, Bi, Ci ≤ 1000, 1 ≤ i ≤ N) that describe, respectively, the width, height and depth of each stone provided by the i-th supplier. The last test case is followed by a line containing one zero.


      Output

      For each test case, print one line containing the minimum number of identical cubes that can be cut from the given stones.


      Example

      Input:
      
      2
      1 2 3
      4 5 6
      2
      4 4 4
      2 2 2
      0
      
      Output:
      
      126
      9
      

      Added by:Paulo Costa
      Date:2012-02-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ICMC-USP









      SPOJ Problem Set (classical)

      10576. Exclusive Security

      Problem code: EXCLSEC

      Ashton Carl McDonalds (known as A.C.M.) works at a company called XOR (XptO Revolution). The company has a simple rule for employee identification: each employee must have an integer id that must be unique (no two employees may have the same id).

      Recently, the employees were grouped into teams, in the following way: the teams are intervals on the XOR’s employees list. An employee can be part of more than one team.

      The company wants to hire new employees, and needs to generate id numbers for them. However, due to a security flaw in Human Resources software, the company can’t assign a new number that, if one executes Exclusive-Or operation with all numbers of any team, results in 0.

      McDonalds, as the leader lazy programmer of XOR, needs your help to determine if a given number can or can’t be assigned to a new employee.

      Input

      The input contains multiple test cases.

      The first line of each test case contains three numbers, N, T and Q, the number of employees in the company, the number of teams and the number of new numbers to be queried, respectively.

      The second line contains N numbers Xi, 1 <= i <= N, distinct, the employees id numbers.

      Each one of the following E lines contains two numbers, A and B, which represent an interval that forms a team. It means that the employees identified by XA, …, XB form one team.

      Each one of the following Q lines contains one number Yj, the queried number.

       

      Limits: 1 <= N, T, Q <= 105, 1 <= A <= B <= N. All Xi and Yj will be non-negative and fit into a signed 32 bit integer, and all queries must be treated as independent from others (just the initial employees and teams must be taken into account).

      Output

      For each test case, the program must print Q + 1 output lines. For each queried number, the program must print ‘Y’, if the number can be assigned to a new employee, or ‘N’, otherwise. The last line is a simple minus sign ‘-’.

      Example

      Input:
      3 2 4
      1 2 4
      1 2
      1 3
      3
      5
      6
      7
      0 0 0 Output: N
      Y
      Y
      N
      -

      Added by:Paulo Costa
      Date:2012-02-08
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFCG









      SPOJ Problem Set (classical)

      10579. Desrugenstein

      Problem code: DESRUG

      The city of Desrugenstein is a complete mess. Looking at the map, it seems organized, since it
      was created in a square grid form, but there is no directions standard. Each corner says the directions
      you can go from there (north, south, west, east). The mayor Daniel Snake is headstrong and lazy
      enough to let everything as it is and forbid any change attempt. Unable to do much, the Master
      Spiritual Counselor of Desrugenstein, Giordano Marfyn, asked you, Spiritual Counselor Level XVII of
      Desrugenstein, lead programmer of Desrugenstein, to write a program to calculate the cost of going
      from a corner (x, y) to another corner (z, w), considering the messy streets.

      Input

      Input file contains several test cases. First line of each test case contains an integer N (1 ≤ N ≤ 10) that
      represents height and width of the grid that maps the city (a N x N grid). The input file ends with N = 0,
      and it should not be processed. Each one of the next N lines represents a street of the city, starting from
      the further north (N – 1) until the further south. In each one of these lines there are 4*N integers, 4 for
      each corner: A (north) B (south) C (west) D (east). Each one is 0 if it is not possible to go on the
      respective direction, or 1 if it is possible.
      After the city map, your program should read an integer P (1 ≤ P ≤ 100). Next P lines contain 4 integers
      each, x0 y0 x1 y1 representing the question: “What is the minimum cost to go from corner (x 0 , y0) to
      corner (x1 , y1)?”. The cost to go from a corner to the nearest corner in any direction is 1.

      Output

      For each question, answer “Impossible” if there is no valid (respecting corners directions) path between
      the corners, or the minimum cost, if there is(are) path(s). Print a blank line after each test case.

      Example

      Input:
      4
      0 1 0 1 0 0 1 0 0 0 0 1 0 1 0 0
      0 0 0 0 1 0 0 1 0 0 0 1 0 1 0 0
      1 0 0 0 1 0 1 0 1 1 0 0 0 1 1 0
      0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0
      5
      1 3 0 3
      2 3 3 0
      2 3 0 0
      3 1 3 2
      0 3 0 0
      0 Output: 1
      4
      7
      3
      Impossible

      Added by:Paulo Costa
      Date:2012-02-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFU









      SPOJ Problem Set (classical)

      10581. Ball Stacking Again

      Problem code: BALLSAG

      The XYZ TV channel is developing again a new game show, where a contestant has to make a
      choice in order to get a prize. The game consists of a triangular stack of balls, each of them having an
      integer value, as the following example shows:

      The contestant must choose exactly one ball and his prize is the sum of the value of that ball and
      the balls directly on top of it. Notice that the prize can be negative!
      Your friend is going to participate on the game show, and he wants you to develop a program that
      can tell the maximum prize possible.

      Input

      Each test case is described using several lines. The first line contains an integer N representing
      the number of rows of the stack ( 0 < N < 1001). The i-th of the next N lines contains i integers Bij ( -
      1000 <= Bij <= 1000 for 1 <= j <= i <= N); the number Bij is the value of the j-th ball in the i-th row of
      the stack (the first row is the topmost one, and within each row the first ball if the leftmost one). After
      each test case there is a blank line.
      The last test case is followed by a line containing one zero.

      Output

      For each test case output a line with an integer representing the maximum prize a contestant can
      make from the stack.

      Example

      Input:
      2
      -2
      1 -10

      3
      1
      -5 3
      6 -4 1
      0

      Output: -1
      5

      Note:
      On the first test case, the optimal solution is to take the ball with value 1, making you remove the ball
      with value -2, resulting in -1.
      On the second test case the best option is to take the ball with value 1 on the bottom row, resulting in
      1+3+1 = 5.

      Added by:Paulo Costa
      Date:2012-02-09
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ICMC-USP









      SPOJ Problem Set (classical)

      10582. subarrays

      Problem code: ARRAYSUB

      Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.

      Input

      the number n denoting number of elements in the array then after a new line we have the numbers of the array

      and then k in a new line

      n<10^6

      k<10^5

      1 <= k <=n

      and each element of the array is between 0 and 10^6

      Output

      print the output array

      Example

      Input:
      9
      1  2  3  1  4  5  2  3  6
      3
      Output:
      3 3 4 5 5 5 6


      Added by:priyamehtanit
      Date:2012-02-09
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set ()

      10585. Searching God

      Problem code: SEAGOD

      Jesse is a biologist and he was studying some aspects of life when he discovered that certain
      species of sea animals tried to tell him some things about God. Those animals were using a certain
      language to speak with him. They wrote down in binary code (black and white) in the shell they have.
      As Jesse was the only one that this message was intended to be delivered, they encrypted the message
      in such way that there is a rule to decrypt every bit in the spherical-shaped shell looking at 3 other bit:
      the left, itself and the right in this order. So first they write the cyphered message and the rule to
      decrypt it in lexicographical order, so the rule space in the shell containing the bit to decrypt “101” will
      be rule's bit 5. To turn the cryptography more elaborated there is also the number of rounds that this
      must be done to the entire message. Jesse wants to hire you to write a program for him to decrypt the
      text and live in harmony forever and ever with the animals he loves and find out who is and what this
      God wants to do.

      Input

      The input has several test cases. The first line of a test case contains the message length L (0 < L ≤
      10000). The next line contains the message M, of length L bits. In the next line, your program should
      read the 8-bits rule R. In another line, the number of rounds 0 ≤ N ≤ 10000. Your program must read
      until the end of file.

      Output

      For each test case your program must write the message M after applying the rule R for N rounds.

      Example

      Input:
      5
      10111
      10101010
      1
      10
      1011010101
      11100010
      2 Output: 10000
      1011010101

      Added by:Paulo Costa
      Date:2012-02-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:UFU









      SPOJ Problem Set (classical)

      10586. Problems in Moria

      Problem code: PROBMOR

      Balin, in his last days, needed to put more workers on the tunnels of Moria to build a
      lot of shelters to his people and to discovery the depths of that land. However, he didn't know
      where to put a collection point in order to take all the rocks in the way and bring all of them
      outside of Moria. The only thing he knew was this collection point needed to be fix in a
      junction point that connects two independent parts. If there's no point with this feature, any
      junction point, that's not the source one, can be used.

      Input

      The input contains several test cases. Each test is given by a line with two integers
      X 0 X ≤100 and Y Y 0 . The first one is the number of points and the second, the
      number of tunnels. Then, the next Y lines are followed by three integers: A 0 A≤100 ,
      B 0B≤100 e C C0 , which means, there's a link between A and B with a
      capacity C of workers that can walk through there. After that, there's a line with only one
      integer which is the start point, in the other words, the point where the workers are divided.

      Output

      For each test case, display it's case number followed by a blank line. In the next line
      display the number Z of points that can be used as a collection point and, in the next Z
      lines shows in decreasing order the maximum number of workers that can be used.
      Each test case is separated by a blank line as the sample output.

      Example

      Input:
      45 
      125
      148
      233
      2 4 11
      346
      1
      56
      125
      148
      233
      2 4 11
      346
      4 5 12
      2 Output: Case 1
      Points: 3
      13
      13
      9
      Case 2
      Points: 1
      19

      Added by:Paulo Costa
      Date:2012-02-10
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFAM









      SPOJ Problem Set ()

      10587. Enemies

      Problem code: ENEM

      Gangs are a big problem for every metropolis. Individuals that are member of some
      gang usually make enemies. When enemies meet each other they always want to fight, which
      makes the city a dangerous place to live. These gang members are also known as fighters.
      The local Police Department received anonymous information about a huge meeting
      between fighters at the central park, but the police chief, as always, wants to know if it is
      worth to send some of his men there. He knows that a fighter will fight one of his enemies only
      if all of them are in front of him. If one of the fighters doesn’t want to fight, then the meeting
      will be canceled. Moreover, each fighter can fight just one enemy at a time, and during this
      fight his other enemies wait, because they all want to beat him alone. He also knows that one
      police officer is enough in order to prevent two fighters from start a fight.
      Given these conditions and the enemy’s relationships of the fighters that will be at the
      central park, your job is to tell the chief if the meeting will happen or will be canceled. If it is
      going to happen, then the chief wants to know the minimum number of policemen he needs
      to send in order to prevent the fights at any moment of the meeting.

      Input

      Each test case is described using several lines. The first line contains two integers F (1 ≤ F ≤ 60)
      and R (1 ≤ R ≤ 1770) representing the number of fighters at the meeting and the number of
      enemy relationships, respectively. The fighters are identified by different integers from 0 to F-
      1. Each of the next R lines contains two integers A e B representing an enemy relationship
      between the fighters A and B, you can consider that each enemy relationship will appear once
      in each test case and that if a fighter A is enemy of a fighter B then B is also enemy of A.
      The last test case is followed by a line containing F = 0 and R = 0.

      Output

      For each test, output in a line the minimum number of policemen necessary in order to
      prevent the fights or output ‘The meeting will be canceled’ if the meeting is going to be
      canceled.

      Example

      Input:
      44
      02
      03
      12
      13
      67
      02
      03
      04
      05
      12
      13
      14
      33
      01
      12
      20
      00

      Output: 2
      2
      The meeting will be canceled

      Added by:Paulo Costa
      Date:2012-02-10
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:UFS









      SPOJ Problem Set (classical)

      10588. Portal

      Problem code: PORTALUN

      You, as the newly recruited mad scientist at Aperture Laboratories, has been challenged by GLaDOS to a game that will test a new type of Portal! The invention is a series of portals, to each of which is assigned a priority.

      One can only move from a portal with higher priority to another with lower priority. The game consists of moving the test subjects through the rooms of Aperture Science Enrichment Center. You and GLaDOS alternate turns: at each turn a player must move one of the subjects to a new room using the new portal prototype. Since her disastrous experiment with Chell, GLaDOS has decided not to hand over handheld portal devices to guinea pigs, so the portals have already been placed in the rooms, and their priority is the same priority associated to their room. This way, one can only move from a room to another if there are portals connecting them and the priority of the destiny room is lower than the current room's. The loser will be the player who has no valid move and thus, is doomed to receive no cake and possibly die in a fire.

      Input

      The input consists of several test cases.

      The rst line of each test case will begin with two integers N, M denoting the number of rooms and the number of portal connections, 0 < N ≤ 1000 and 0 ≤ M ≤ N (N − 1)/2. Rooms are numbered from 0 to N − 1, and their priority is the same as their number.

      Then follows M lines describing the connections between two rooms. Each line contains two integers corresponding to rooms connected by portals.

      The next line contains an integer K , 1 ≤ K < N , denoting the number of test subjects. Two or more subjects may occupy the same room.

      Next K lines contain the room numbers where the subjects have been alocated.

      Output

      For each test case, assuming both you and GLaDOS play perfectly and you are the first player to
      make a move, print "I win" if you are victorious and "I lose" otherwise.

      Example

      Input:
      9 14
      0 1
      0 2
      0 3
      1 2
      2 3
      1 4
      2 5
      5 3
      4 5
      4 3
      5 6
      6 7
      7 8
      8 6
      3
      3
      5
      8 Output: I lose

      Added by:Paulo Costa
      Date:2012-02-10
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Unicamp









      SPOJ Problem Set (classical)

      10589. King

      Problem code: KING

      The Nlogonia Kingdom needs a new king. Differently from other monarchy kingdoms,
      where the king’s choice is hierarchical, at Nlogonia any citizen can apply for the post and the
      whole population can vote on those who applied. However, with these conditions, a big
      problem arises: every citizen would probably apply and vote for itself.
      In order to solve this problem the Nlogonia council decided to split the voting process
      in two phases. In the first phase, known as constraint phase, every citizen must write two
      constraints about another two candidates. A constraint can be of one of the following two
      types: a reliability constraint, which means that the citizen trusts another citizen and wishes
      that it takes place in the second phase of the voting process; an unreliability constraint, which
      means that the citizen doesn’t trust another one and wishes that he doesn’t take place in the
      second phase of the process. The council decided that at least one of the constraints of every
      citizen must be satisfied in order to choose the group of candidates that can go forward to the
      second phase. The citizen cannot give itself a reliability constraint.
      The second phase of the process is a simple voting process where every citizen
      chooses between one of the candidates that remained from the first phase.
      Your job is to determine if it is possible to satisfy at least one of the two constraints of
      every citizen, even if it means that no candidate remains for the second phase, in this case the
      council decides who must be the king.

      Input

      Each test case is described using several lines. The first line contains one integer N
      representing the number of citizen in the Nlogonia Kingdom (3 ≤ N ≤ 1000). The candidates are
      identified by different integer from 0 to N-1. Each of the next N lines describes the two
      constraints of a citizen, and each one starts with an uppercase letter that is either ‘R’ or ‘U’,
      where ‘R’ indicates a reliability constraint and ‘U’ indicates a unreliability constraint, followed
      by a integer C (0 ≤ C < 1000) representing the candidate that the citizen gave the constraint.
      The two constraints will be separated by single space.
      The last test case is followed by a line containing one zero.

      Output

      For each test, use the output uppercase ‘Y’ if it is possible to satisfy at least one
      constraint for each citizen and ‘N’ if it is not.

      Example

      Input:
      3
      R1U0
      U2R1
      R2R0
      4
      R1U0
      R0U1
      R0R1
      U0U1 Output: Y
      N

      Added by:Paulo Costa
      Date:2012-02-10
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10594. Decoding Number Stations with Dr Whooves

      Problem code: PONY2

      Dr. Whooves has been holed up in his laboratory, analyzing radio transmissions. Specifically, he has been listening to a very odd transmission - it is just somepony reading a bunch of numbers! There are several of these stations, and Dr. Whooves wants to know what they are trying to hide. He is going to try to decrypt the messsages, and after a lot of study, he has discovered a special number N for each transmission, which will let him discover the true message. He knows that numbers correspond to letters in exactly the following way: a = 1, b = 2, c = 3, ..., z = 26. So for a message, there are many possible decodings, just based off of that. This is where the special number comes in. If Dr. Whooves sorts all the possible decodings lexicographically, then the secret message is the Nth lexicographic decoding. For a given input, output the Nth lexicographic decoding. However, Dr. Whooves realized that he can't type very quickly, so you'll have to make the program yourself.

      Input Format

      An integer T, followed by T lines of the form S N where S is a string of digits, and N is an integer for which you are to report the Nth lexicographic possibility. You are guaranteed that S can be parsed in at least 1 way, and that N is a valid number. That is, if there are only 5 ways to parse S, then N will be between 1 and 5. It is further guaranteed that the total number of ways to parse S will fit into a 64 bit signed integer, and that the length of S will be less than or equal to 100.

      Output Format

      On T separate lines, output the N_i'th lexicographic valid string.

      Example

      Input:
      2
      1111 4
      1111 5
      
      Output:
      kaa
      kk
      

      Added by:Alex Anderson
      Date:2012-02-11
      Time limit:1s-1.299s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Extended version of well-known problem









      SPOJ Problem Set (classical)

      10596. Monkey and apples

      Problem code: MON2012

      Monkey Chris loves apples. That's why he has planted lots of apple trees. He does two types of operations on this trees.Second operation (described "2" x y in input(without quotes)) means that all apples on interval x+c y+c get ripe(edible). First operation (described by "1" x y(without quotes) in input) means counting ripe apple trees on interval x+c y+c. C=0 in the beginning and becomes the answer of each query("1" operation). Input begins with M(1<=M<=10^5) the number of operations. Afterwards M lines each of them is an operation ("1" or "2"). 1<=X+C; Y+C<=10^9.
      Input

      3

      2 5 8

      2 7 10

      1 1 10

      Output

      6

      Input explanation:

      3 queries. Apples gets ripe on intervals 5-8 and 7-10.

      There are totally 6 ripe apple-trees on interval 1-10 so answer to query is 6.


      Added by:Ikhaduri
      Date:2012-02-11
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 HASK JAR JAVA NODEJS PAS fpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n RUBY WSPC
      Resource:izho 2012









      SPOJ Problem Set (classical)

      10605. Counting Formations

      Problem code: FORMAT1


      With the coming release of Marcohard Balconies 100 operating system, people are more and more interested in its new UI (User Interface), code-named “Subway”.

      This UI presents your desktop as a grid that is divided into N rows and M columns (so you have N * M cells). In each cell, you can place one icon of an application of a certain type. Your applications can be of one of K types, numbered 1 through K. You’re an expert in this field, so it is assumed that there is an unlimited number of applications of each type.

      Any placement is called an icon formation. Some of the icon formations are beautiful. An icon formation is called beautiful if and only if no pair of rows are similar. Two rows are similar if and only if for each X that 1 <= X <= K, they contain exactly the same number of applications of type X.

      Given N, M, and K, you should solve for the number of different icon formations that are beautiful, modulo 109+7. Two formations are different if and only if there is a cell where the type of application in one formation is not the same as the type in another formation.

      You may assume that 1 <= N, M, K <= 50.

      Input

      There are several test cases. For each test case there are 3 integers, named N, M, K, in a single line. Please process until EOF (End Of File).

      Output

      For each test case, please print a single line with a integer, the corresponding answer to this case.

      Example

      Input:
      2 2 2
      5 3 2
      3 5 7
      
      Output:
      10
      0
      894953467
      

      Added by:[Trichromatic] XilinX
      Date:2012-02-12
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Not my own problem, used in ICPC Regional Contest, Chengdu 2012 Preliminary









      SPOJ Problem Set (classical)

      10606. Balanced Numbers

      Problem code: BALNUM

      Balanced numbers have been used by mathematicians for centuries. A positive integer is considered a balanced number if:

      1)      Every even digit appears an odd number of times in its decimal representation

      2)      Every odd digit appears an even number of times in its decimal representation

      For example, 77, 211, 6222 and 112334445555677 are balanced numbers while 351, 21, and 662 are not.

      Given an interval [A, B], your task is to find the amount of balanced numbers in [A, B] where both A and B are included.

      Input

      The first line contains an integer T representing the number of test cases.

      A test case consists of two numbers A and B separated by a single space representing the interval. You may assume that 1 <= A <= B <= 1019 

      Output

      For each test case, you need to write a number in a single line: the amount of balanced numbers in the corresponding interval

      Example

      Input:
      2
      1 1000
      1 9
      Output:
      147
      4

      Added by:Angel Paredes
      Date:2012-02-12
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:Cuban Olympiad in Informatics 2012 - Day 2 Problem A









      SPOJ Problem Set (classical)

      10607. Delivery

      Problem code: TWODEL

      Fast Delivery Corporation built one of its offices right in the middle of the longest straight street in Cuba in order to satisfy every order of those customers who live along that street.

      The addresses of the houses to which the merchandises are distributed are represented by integer numbers which represent the distance between the office and the corresponding houses. If we consider that the office is located at position 0, then the positive addresses are located to the right of the office, and the negative addresses are located to the left of the office. 

      The delivery orders are satisfied in the same order in which they were received.

      Fast Delivery Corporation has assigned two employees to the new office. Those employees are in charge of distributing the merchandises. At the beginning of the day, the orders are shared between both employees. 

      The corporation wants to share the orders between the two employees in such a way that the total distance required to deliver all the merchandise is minimized.

      Input

      Line 1: a single integer N (1 <= N <= 100,000) representing the number of orders

      The next N lines contain an integer representing an address where a merchandise will be delivered.

      The distance between the office and any house is not greater than 108

      Output

      A single line: the minimum distance the two employees have to travel to satisfy every order.

      Example

      Input:
       5
      1
      -1
      2
      -2
      3
      
      Output:
      5
      Note: The naive greedy doesn't work. Also remember that the deliveries must be satisfied in the same order they appear in the input.

      Added by:Angel Paredes
      Date:2012-02-12
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL 6
      Resource:Cuban Olympiad in Informatics 2011 - Day 1 Problem B









      SPOJ Problem Set (classical)

      10608. Unique Strings

      Problem code: UNICA

      Some people who love strings have decided to call a special group of strings as the “unique strings.”

      Let’s define a(S) as the number of characters “a” the string S contains, and b(S) as the number of characters “b” the string S contains.

      S is a unique string if:

      1)      S only contains the characters “a” and “b”

      2)      For every substring S’of S, | a(S’) – b(S’) | <= 3

      For example, “abbab” is a unique string. However, “abbbba” is not because it includes the substring “bbbb” for which | a(“bbbb”) – b(“bbbbb”) | = 4 > 3.

      Let’s say we sort the unique strings – first by length and then lexicographically. The Nth unique string is the string that appears in the position N in the sorted list. The first unique string is assigned the number 1.

      The first 12 unique strings in the sorted list are: a, b, aa, ab,ba, bb, aaa, aab,  aba, abb, baa, bab

      Input

      A single number N (1 <= N <= 1014). Your task is to find the Nth unique string in the sorted list.

      Output

      A single line: the Nth unique string in the sorted list.

      Example

      Input:
      10
      
      Output:
      abb
      _______
      Input:
      19
      Output:
      abab

      Added by:Angel Paredes
      Date:2012-02-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Cuban Olympiad in Informatics 2011 - Day 2 Problem A









      SPOJ Problem Set (classical)

      10611. Ranges

      Problem code: RRANGE

      There are N contiguous cells numbered from 1 to N. Initially, each cell contains a 0 in it. A sub-contiguous group of cells can be updated this way:

      1)      A range [i,j] is defined such that i < j

      2)      The cell numbered i is added 1; the cell numbered i + 1 is added 2, and so on until the cell numbered j is reached and added j – i + 1

      For example, if N = 7 and the updates [3, 6] and [4,7] were performed, this is what would happen.

      Initially: {0,0,0,0,0,0,0}

      Update [3,6]: {0,0,1,2,3,4,0}

      Update [4,7]: {0,0,1,3,5,7,4}

       

      After performing some update operations, it would be amazing to answer questions like the following:

      1)      A range [u,v] is defined such that u < v

      2)      The answer is the sum of every cell in the range [u,v] (both u and v are included) modulus 10,000

       

      Given N and U updates ranges. You have to write a program capable of answering Q questions.

       

      Input

      The first line contains three integers: N (1 <= N <= 1,000,000,000), U and Q (1 <= U, Q <= 1,000), representing the number of cells, the number of update operations, and the number of questions respectively.

       

      Each of the following U lines contains two integers i and j (1 <= i < j <= N) separated by a single space indicating an update operation.

      Each of the following Q lines contains two integers u and v (1 <= u < v <= N) separated by a single space indicating a question.

      Output

      For each question [u,v] you must print the sum of all contiguous cells starting at u and ending at v modulus 10,000.

      Example

      Input:
      7 2 2
      3 6
      4 7
      4 6
      1 7
      
      Output:
      15
      20

      Added by:Angel Paredes
      Date:2012-02-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Copa Lenin 2012 - Level 1









      SPOJ Problem Set (classical)

      10612. Funny Areas

      Problem code: FUNAREA

      There is an M x N matrix of integer numbers.  Both the rows and columns of the matrix are numbered starting at 0 and ending at M-1 and N-1 respectively.

      A funny area is defined by three integers i,j, and r, and it is composed for those cells [x,y] such that |i-x| + |j-y| <= r. As you might have probably guessed [i,j] is the center and r is the radius of the funny area.

      In this problem we are interested in finding the sum of every cell inside some given funny areas.

      Input

      The first line contains two integers 1 <= M, N <= 1000 representing the rows and columns of the matrix.

      Each of the following M lines contains N integers separated by single spaces. These numbers are non-negative and not greater than 1,000,000,000

      The next line contains a number F (1 <= F <= 100,000) which is the number of funny areas.

      Each of the following F lines contains three integers i,j, and r representing the center and the radius of a funny area.

      Output

      F lines: for each funny area print a single number -- the sum of all the cells inside of it.

      Example

      Input
      5 5
      1 2 3 4 5
      5 4 3 2 1
      1 1 1 1 1
      2 3 4 3 0
      7 8 9 6 5
      3
      1 0 0
      2 2 2
      3 1 1
      

       

      Output 5 36 18


      Added by:Angel Paredes
      Date:2012-02-13
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Copa Lenin 2012 - Level 2









      SPOJ Problem Set (classical)

      10620. KNJIGE

      Problem code: KNJIGE

       

      Mirko has a home library consisting of N books arranged one on top of the other in a narrow cabinet.
      Since being well trained in the secrets of alphabet in the previous task, he now wishes to arrange the
      books alphabetically, so that the book whose title comes first alphabetically ends up on top, and the
      alphabetically last one at the bottom of the pile.
      Mirko can easily pull a book out of the cabinet, but it is difficult to push it back into the pile, so the
      book can only be returned to the top of the pile. Thus, the only available method of sorting the books
      is repeatedly pulling a book out of the pile and placing it on top of the pile.
      The books are labelled with integers from 1 to N, in alphabetical order. Therefore, Mirko wants them
      to be ordered as (1, 2, ..., N), counting from the top. For example, if N = 3 and the starting order is (3,
      2, 1), two moves are sufficient. First, he pulls out the book number 2 and places it on top, so the pile
      becomes (2, 3, 1). After that, he does the same with book number 1, thus the pile becomes (1, 2, 3).
      Help Mirko by calculating the minimum number of moves needed to sort a given starting order.
      INPUT
      The first line of input contains the integer N (N ≤ 300 000).
      Each of the next N lines contains a single positive integer. These N integers represent the order of
      Mirko’s books from top to bottom of the cabinet. Each of the integers 1, 2, ..., N appears exactly once.
      OUTPUT
      The first and only line of output must contain the required minimum number of moves.

       

      Mirko has a home library consisting of N books arranged one on top of the other in a narrow cabinet. Since being well trained in the secrets of alphabet in the previous task, he now wishes to arrange the books alphabetically, so that the book whose title comes first alphabetically ends up on top, and the alphabetically last one at the bottom of the pile.

      Mirko can easily pull a book out of the cabinet, but it is difficult to push it back into the pile, so the book can only be returned to the top of the pile. Thus, the only available method of sorting the books

      is repeatedly pulling a book out of the pile and placing it on top of the pile.

      The books are labelled with integers from 1 to N, in alphabetical order. Therefore, Mirko wants them to be ordered as (1, 2, ..., N), counting from the top.

      For example, if N = 3 and the starting order is (3, 2, 1), two moves are sufficient. First, he pulls out the book number 2 and places it on top, so the pile becomes (2, 3, 1). After that, he does the same with book number 1, thus the pile becomes (1, 2, 3).

      Help Mirko by calculating the minimum number of moves needed to sort a given starting order.

       

      Input

      The first line of input contains the integer N (N ≤ 300 000).

      Each of the next N lines contains a single positive integer. These N integers represent the order of

      Mirko’s books from top to bottom of the cabinet. Each of the integers 1, 2, ..., N appears exactly once.

      Output

      The first and only line of output must contain the required minimum number of moves.

      Example

      Input:
      3 
      3 
      2 
      1 
      
      Output:
      2

      Added by:Omar ElAzazy
      Date:2012-02-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10621. MONO

      Problem code: MONO


       

      Mirko soon realised that number sequences are not the best career choice, and went right back to lettertable
      business.
      Mirko’s table has R rows and C columns and consists of lowercase letters.
      Each cell of the table is a square of equal size. We assign coordinates to vertices of those squares, so
      that upper-left corner of the table has coordinates (0, 0), upper-right (C,0), lower-left (0, R), and lowerright
      (C, R).
      We say that polygon within the table is monoliteral if the following holds:
      1. its vertices are from the described set of cell-square vertices,
      2. its edges are parallel to coordinate axes,
      3. all letters inside the polygon are equal.
      A simple polygon for which first two conditions are true (third one may or may not be true) is given.
      Mirko would like to know the number of monoliteral polygons that can be obtained by moving the
      given one up, down, left, or right or any combination thereof, but not rotating.
      INPUT
      The first line of input contains two space seperated integers R and C (1 ≤ R, C ≤ 500).
      Each of the next R lines contains exactly C lowercase letters, this is Mirko’s table.
      The following line contains integer V (4 ≤ V ≤ 500), number of vertices of given polygon.
      Each of the next V lines contains two integers X, Y (0 ≤ X ≤ C, 0 ≤ Y ≤ R). These are the coordinates
      of the vertices of the given polygon. Vertices are given in clockwise order.
      The given polygon will satisfy conditions 1 and 2 from above.
      OUTPUT
      In the first and only line of output, print expected number of polygons.

      Mirko soon realised that number sequences are not the best career choice, and went right back to lettertable business.

      Mirko’s table has R rows and C columns and consists of lowercase letters.

      Each cell of the table is a square of equal size. We assign coordinates to vertices of those squares, so that upper-left corner of the table has coordinates (0, 0), upper-right (C,0), lower-left (0, R), and lowerright (C, R).

      We say that polygon within the table is monoliteral if the following holds:

      1. its vertices are from the described set of cell-square vertices,

      2. its edges are parallel to coordinate axes,

      3. all letters inside the polygon are equal.

      A simple polygon for which first two conditions are true (third one may or may not be true) is given.

      Mirko would like to know the number of monoliteral polygons that can be obtained by moving the given one up, down, left, or right or any combination thereof, but not rotating.

      INPUT

      The first line of input contains two space seperated integers R and C (1 ≤ R, C ≤ 500).

      Each of the next R lines contains exactly C lowercase letters, this is Mirko’s table.

      The following line contains integer V (4 ≤ V ≤ 500), number of vertices of given polygon.

      Each of the next V lines contains two integers X, Y (0 ≤ X ≤ C, 0 ≤ Y ≤ R). These are the coordinates

      of the vertices of the given polygon. Vertices are given in clockwise order.

      The given polygon will satisfy conditions 1 and 2 from above.

      OUTPUT

      In the first and only line of output, print expected number of polygons.

      Example

       

      input

      3 3

      aaa

      aaa

      aaa

      4

      2 0

      2 2

      0 2

      0 0

       

      output

      4

       

      input

      3 3

      aaa

      aba

      aaa

      4

      2 0

      2 2

      0 2

      0 0

       

      output

      0

       

      input

      5 4

      xyyx

      xyyy

      xxyy

      xxxx

      xxxx

      8

      1 3

      1 2

      0 2

      0 0

      2 0

      2 1

      3 1

      3 3

      output

      2

       

       

       


      Added by:islam
      Date:2012-02-13
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2010/2011 Contest 3 by Luka Kalinovèiæ









      SPOJ Problem Set (classical)

      10622. DIFERENCIJA

      Problem code: DIFERENC

       

      Mirko discovered what Slavko did in previous task, and decided to deal with something completely
      opposite to tables of letters: sequences of numbers.
      Let’s define a value of a sequence as the difference between the largest and the smallest number within
      that sequence. For example, value of sequence (3, 1, 7, 2) is 6, and value of (42, 42) is 0.
      Find the sum of values of all subsequences of consecutive elements of a given sequence.
      INPUT
      The first line of input contains a single integer N (2 ≤ N ≤ 300 000), number of elements of the
      sequence.
      Next N lines contain elements of the sequence. Each element is a positive integer not greater than 100
      000 000.
      OUTPUT
      The first and only line of output must contain the requested sum.
      EXAMPLE TEST DATA
      input
      3
      1
      2
      3
      input
      4
      7
      5
      7
      5
      input
      4
      3
      1
      7
      2
      output
      4
      output
      12
      output
      31

       

      Mirko discovered what Slavko did in previous task, and decided to deal with something completely opposite to tables of letters: sequences of numbers.

      Let’s define a value of a sequence as the difference between the largest and the smallest number within that sequence. For example, value of sequence (3, 1, 7, 2) is 6, and value of (42, 42) is 0.

      Find the sum of values of all subsequences of consecutive elements of a given sequence.

      INPUT

      The first line of input contains a single integer N (2 ≤ N ≤ 300 000), number of elements of the sequence.

      Next N lines contain elements of the sequence. Each element is a positive integer not greater than 100 000 000.

      OUTPUT

      The first and only line of output must contain the requested sum.

      EXAMPLE TEST DATA

      input

      3

      1

      2

      3

       

      output

      4

       

      input

      4

      7

      5

      7

      5

       

      output

      12

       

      input

      4

      3

      1

      7

      2

      output

      31

       

       


      Added by:islam
      Date:2012-02-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2010/2011 Contest 3 by Adrian Satja Kurdija









      SPOJ Problem Set (classical)

      10623. ZNANSTVENIK

      Problem code: ZNANSTVE

       

      In this economy, we all know how hard it is to get a job. Mirko, a recent college graduate, however, got
      lucky - he is now employed as a runeologist by the Language Institute of Croatia. His friend Slavko
      believes runeology isn’t a science and is hence angry at Mirko for believing the opposite. One foggy
      Christmas day, Mirko’s laptop broke. Since he isn’t great with computers, he gave it to Slavko to repair
      it. Slavko, felling a little naughty, decided to mess up a particular file Mirko was working on.
      This file contains a matrix of R rows and C columns. Each element of the matrix is a single letter. No
      two columns of the matrix are equal. To have some fun with pseudo-scientist Mirko, Slavko decided
      he will delete as much rows as possible from the top of the table, without breaking the no-equalcolumn
      rule.
      INPUT
      The first line of input contains two integers R and C (2 ≤ R, C ≤ 1000), the number of rows and the
      number of columns, respectively.
      In each of the next R lines there are C small letters of the English alphabet. These R x C letters
      represent Mirko’s table (which does not have two same columns).
      OUTPUT
      Output a single integer, the maximum number of rows which can be deleted from the top of the table
      so that no two columns are equal.
      EXAMPLE TEST DATA
      input
      2 6
      dobarz
      adatak
      output
      0
      input
      3 4
      alfa
      beta
      zeta
      output
      2
      input
      4 6
      mrvica
      mrvica
      marica
      mateja
      output
      1

       

      In this economy, we all know how hard it is to get a job. Mirko, a recent college graduate, however, got lucky - he is now employed as a runeologist by the Language Institute of Croatia. His friend Slavko believes runeology isn’t a science and is hence angry at Mirko for believing the opposite. One foggy Christmas day, Mirko’s laptop broke. Since he isn’t great with computers, he gave it to Slavko to repair it. Slavko, felling a little naughty, decided to mess up a particular file Mirko was working on.

      This file contains a matrix of R rows and C columns. Each element of the matrix is a single letter. No two columns of the matrix are equal. To have some fun with pseudo-scientist Mirko, Slavko decided he will delete as much rows as possible from the top of the table, without breaking the no-equalcolumn rule.

      INPUT

      The first line of input contains two integers R and C (2 ≤ R, C ≤ 1000), the number of rows and the

      number of columns, respectively.

      In each of the next R lines there are C small letters of the English alphabet. These R x C letters

      represent Mirko’s table (which does not have two same columns).

      OUTPUT

      Output a single integer, the maximum number of rows which can be deleted from the top of the table

      so that no two columns are equal.

      EXAMPLE TEST DATA

      input

      2 6

      dobarz

      adatak

      output

      0

      input

      3 4

      alfa

      beta

      zeta

      output

      2

      input

      4 6

      mrvica

      mrvica

      marica

      mateja

      output

      1

       

       


      Added by:islam
      Date:2012-02-13
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2010/2011 Contest 1 by Adrian Satja Kurdija









      SPOJ Problem Set (classical)

      10628. Count on a tree

      Problem code: COT

      You are given a tree with N nodes.The tree nodes are numbered from 1 to N.Each node has an integer weight.

      We will ask you to perform the following operation:

      • u v k : ask for the kth minimum weight on the path from node u to node v

       

      Input

      In the first line there are two integers N and M.(N,M<=100000)

      In the second line there are N integers.The ith integer denotes the weight of the ith node.

      In the next N-1 lines,each line contains two integers u v,which describes an edge (u,v).

      In the next M lines,each line contains three integers u v k,which means an operation asking for the kth minimum weight on the path from node u to node v.

      Output

      For each operation,print its result.

      Example

      Input:
      
      8 5
      8 5 105 2 9 3 8 5 7 7 1 2 1 3 1 4 3 5 3 6 3 7 4 8
      2 5 1
      2 5 2
      2 5 3
      2 5 4
      7 8 2 
      Output:
      2
      8
      9
      105

      Added by:Fotile
      Date:2012-02-14
      Time limit:1s-4s
      Source limit:6000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PYTH 3.2.3 n
      Resource:Just for fun...









      SPOJ Problem Set (classical)

      10639. The Blind Passenger

      Problem code: MYQ1


      The seats of an Ultra Deluxe Semi-sleeper bus in Thuvax country are numbered according to the following rules:
       
      1. Seat number 1 is reserved for the bus conductor.
      2. Remaining seats are numbered as shown in the figure below:
       
      The seating arrangement is as shown below
       
      RowNo Left   Right  
            W  A   A  M  W
                       
            01
      1     02 03  04 05 06
      2     11 10  09 08 07
      3     12 13  14 15 16
      4     21 20  19 18 17
      5     22 ............
       
      A blind person enters the bus with a reservation ticket mentioning his seat number. He meets you at the start of the passage and shows you his ticket. Based on the seat number, help him find his seat by telling him the row number (1,2,...), seat position(window or aisle or middle), and the direction(left or right).

      Input

      First line contains a positive integer t(t<=10^5) denoting the number of test cases.
      Each of the next t lines contain a positive integer n(n<=10^9) denoting the blind person's seat number.

      Output

      Output one line for every test case in the following format:
      If the seat number is same as the conductor's seat, print "poor conductor" else,
      print <row_number> <seat_position> <direction>
      row_number: represents the row number from the entrance (a positive integer)  
      seat_position: can be one of "W" or "A" or "M" for window, aisle and middle respectively.
      direction: can be either "L" or "R" for left or right respectively.

      Example

      Input:
      3
      1
      2
      3 Output: poor conductor
      1 W L
      1 A L

      Added by:jack(chakradarraju)
      Date:2012-02-14
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10640. The Wild Wizard

      Problem code: MYQ2


      In the country of Thuvax lived an old wizard named Chanithpra. He practised a form of magic in which the power of spell came from the letters that were written on a piece of parchment.
      When a sentence s is written, the intensity of the letters are as follows:
      1. Intensity of 'a' is 1, 'b' is 2 and it continues till 'z' whose intensity is 26.
      2. Intensity of 'A' is 51, 'B' is 52 and it continues till 'Z' whose intensity is 76.
      3. Intensity of ' '(space) is 32.
       
      The power of a spell written as a part of the sentence is equal to the sum of the intensities of the characters present in it modulo m.
       
      Chanithpra finds an old parchment in Thuvax with a sentence s written on it.
      Help him find the longest spell (i, i+1, ... j) in the sentence s whose power matches with k. (0<=i<=j<length of s)
       
      You need to print the starting index i(0<=i<=length-1) of such a spell in the sentence and the length of the spell.  
       
      If there are multiple such spells, find the minumum index i and if there is no such spell print -1.

      Input

      The first line contains a single positive integer t(1<=t<=100) denoting the number of test cases.
      Each test case consists of 2 lines:
      The first line consists of the sentence s(1<=length of s<=1000000).
      The second line consists of two integers m and k (2<=m<=1000007 and 0<=k<m).

      Output

      For each test case, output one line containing 2 integers. The first is the minimum index i(0<=i<=s.length-1). The second is the length of the spell.
      If no such spell is present, print -1

      Example

      Input:
      1
      Hello World
      10 7 Output: 0 7

      Added by:jack(chakradarraju)
      Date:2012-02-14
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10641. The Dating Dress Problem

      Problem code: MYQ3

      Gauthami has to get dressed for a date. She is going to meet Prasanna in the poshest restaurant in the country of Thuvax.
      Prasanna arrives early and sees the outfit she has picked.  
      While waiting outside, Prasanna being a restless nerd calculates the number of ways she can get dressed.
       
      The complete outfit she picks is represented as a string of digits. The digits represent the following details about the apparel:
      (apparel = clothing or accessories or any other part of the outfit)
       
      1 - a 2 piece apparel where first piece has to be worn before the other. It is followed by the description of the two pieces in order.
       
      2 - a 2 piece apparel which can be worn in any order, and it is not necessary to complete one apparel before starting another one. It is followed by the description of the two pieces in order.
       
      0 - a single piece of apparel which can be put on directly.
       
      Help Prasanna calculate the number of ways in which Gautami can get dressed. Since Prasanna does not want to make Gauthami bored by telling her a huge number, he wants to tell her the number of ways modulo 1000000007.
       
      For example, consider an outfit comprising of a shirt, a skirt into which the shirt has to be tucked in and  
      a neck cloth worn over the shirt.
      It will be represented as 10200 and the number of ways she can get dressed is 2(She has to wear the shirt first after which she can wear either the skirt after the neck cloth or neck cloth after the skirt).

      Input

       

      First line is a positive integer T (T<=100) representing the number of testcases 
      It is followed by T lines, each containing a string S of digits (each digit will be one of 0,1,2) describing the outfit, 1<=|S|<=100,000
      The complete outfit comprises of a single item.

      First line is a positive integer T (T<=100) representing the number of testcases 

      It is followed by T lines, each containing a string S of digits (each digit will be one of 0,1,2) describing the outfit, 1<=|S|<=100,000

      The complete outfit comprises of a single item.

       

      Output

      Output for each test case should consist of one line representing the number of ways in which Gauthami can get dressed modulo 1000000007.

      Example

      Input:
      3 
      10200
      0
      1102000 Output: 2
      1
      2

      Added by:jack(chakradarraju)
      Date:2012-02-14
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10643. The Nerd Factor

      Problem code: MYQ5

      Prof.Venky handles Advanced Topics in Algorithms course for a class of 'n' students. He is always known for his unsolvable question papers. Knowing that it is impossible to pass his subject in a fair manner, one of the students of his class, Vishy, finds out from his seniors that Prof.Venky won't be able to find out if at least 'k' students together discuss and write the answers and thereby all of them can pass. Hence they decide to divide the whole class into a number of groups so that everyone passes. But all the students are fighting over forming the groups. So Puppala, one of the nerdy students in the class, decides  that he will compute all possible ways that they can form the groups and number them, and finally choose one of those numbers at random and go ahead with that way. Now it is your duty to help Puppala find the number of  ways that they can form such groups. 

      Pupalla is incapable of reading big numbers, so please tell him the answer modulo 10^9+7.

       

      Input

      The first line contains the number of test case t(1<=t<=10^6).
      Followed by t lines for each case.
      Each test case contains two integers 'n' and 'k' separated by a space(1<=k,n<=1000)

      Output

      For each test case, print a single line containing one positive integer representing the number of ways modulo 10^9+7 .

      Example

      Input:
      3 
      2 1
      4 2
      6 2 Output: 2
      2
      4

      Added by:jack(chakradarraju)
      Date:2012-02-14
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10644. Serve The Street

      Problem code: MYQ6


      Shree is a very ambitious person and wants to start a new company "RAM COURIER SERVICE" in the country of Thuvax. He plans to open his first office in the Main Street of Thuvax to serve only the people of this street. The Main Street is an inclined road consisting of N buildings spaced out unevenly(building 1 at lowest level and building N at highest level). The distance between adjacent buildings are known to Shree.
       
      The delivery costs incurred by him for various deliveries are calculated as follows:
       
      To deliver a package of weight 'w' to a building downhill at a distance 'd' from the office, Shree spends w*d*1 units of money.
      To deliver a package of weight 'w' to a building uphill at a distance 'd' from the office, Shree spends w*d*2 units of money.
      To deliver a package of non-zero weight to his own building, Shree spends 10 units of money irrespective of the weight of the package.
       
      Shree being an astute businessman wants to choose one of these buildings for his new office so that the total delivery cost incurred by him is minimum.
      Help Shree choose the building for his new office.

      Input

      The first line of the input consists of number of test cases t(1<=t<=20)
       
      The first line of each test case consists of a single number N(1<=N<=10^6) which is the number of buildings in the main street.
      The next line contains N integers representing the weight to be delivered at ith (1<=i<=N) building (0<=w[i]<=100).
      The last line contains N-1 integers where the ith (1<=i<=N-1) integer represents the distance between i and i+1 th building(1<=d[i]<=100).

      Output

      Output a single line for each test case containing two integers separated by a space.
      The first integer is the minimum delivery cost and the next integer is the building number where the office should be placed in order to incur that cost.  
      If more than one building has the same minimum cost, print the building labelled with the smallest number.

      Example

      Input:
      1 
      5
      1 2 3 4 5
      1 1 1 1 Output: 30 4

      Added by:jack(chakradarraju)
      Date:2012-02-14
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10645. The Rail Network Renovation

      Problem code: MYQ7


      The beautiful country of Thuvax has an ancient rail network connecting its 'n' cities using 'm' tracks. The King of Thuvax orders the Railway Minister, Poopsie to renovate the whole rail network. Due to Poopsie's past laziness, the tracks are in shambles and so he wants to rebuild(the tracks are functional again) some of the tracks and destruct(therefore, wont be available for usage) the rest completely.
       
      The King wants to ensure that all the cities are connected after the whole network is renovated but being a miser, he wants to spend the least amount of money possible.  
      Help Poopsie find out the least amount of money using which the renovation project can be completed.

      Input

      The first line of the input contains the number of test cases 't'(1<=t<=100).
       
      The first line of each test case consists of two numbers: number of cities 'n'(1<=n<=10^3) and number of tracks 'm'(0<=m<=10^6).
      The next m lines contains description of each of the tracks and their corresponding costs of destruction and rebuilding.
      Each of these m lines contains four integers 'a','b','d' and 'r'(1<=d,r<=1000000) representing a track between city 'a' and city 'b' with the cost of destruction and rebuilding being d and r respectively(cities are numbered from 1 to n).

      Output

      The ouput consists of t lines.

      For each test case, print a single line consisting of a single integer that is the least amount of the money required to renovate the whole rail network.

      Example

      Input:
      1 
      4 4
      2 1 7 8
      3 2 4 6
      4 2 2 4
      1 4 3 5 Output: 21

      Added by:jack(chakradarraju)
      Date:2012-02-14
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10646. The National Game

      Problem code: MYQ8


      Prasanna and Nithin had mastered Thuvax's national game, TicTacToe.
       
      TicTacToe is a board game for two players, x and o, who take turns (alternatively) marking the spaces in a 3×3 grid with their signs 'x' and 'o' respectively. The x player goes first. The player who succeeds in placing three of his signs in a horizontal, vertical, or diagonal row wins the game and the game stops there.

      While returning from a TicTacToe tournament, Prasanna and Nithin find a tictactoe like grid. They decide to continue playing from the state the board was in. Help Nithin find whether the next person to move will win/lose or whether the game will result in a tie (assuming both players play optimally), or if such a state is invalid.

      Input

      First line of the input contains a number T (1<=T<=10^6), followed by 4*T lines. The first line of each testcase is empty and the next 3 lines show the state of the game.

      Output

      Print win/lose/tie/invalid for each testcase on a separate line.

      Example

      Input:
      3 
       
      oox
      .x.
      ..x
       
      xox
      xoo
      oxx
       
      o..
      ...
      ... Output: lose
      tie
      invalid

      Explanation:
      Case 1: Player x can win by placing x in either last cell of the middle row, or the first cell of the last row. So the next player, o, cant prevent him from winning from this state.
      Case 2: It is completed game, as you can see no one has won. So, it has ended in a tie.
      Case 3: Player x should have started the game. Hence such a state can never be reached.

      Added by:jack(chakradarraju)
      Date:2012-02-14
      Time limit:1s-30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10647. Divide And Conquer

      Problem code: MYQ9


       

      The King of Thuvax decided to conquer the neighbouring country of Silicon Valley. In order to conquer  a country, he has to successfully invade every city in the country. But he always doesn't get into action unless he plans it properly. He knows that severing a city's communications with all other cities before invading it is the only way to conquer it. He has the information regarding how the cities communicate with each other through his spy. The spy has lived in Silicon Valley right from the time when it was a single city, much before its development into a country. He gives information about how every new city established communication links with other cities. The spy's information is represented as below.

       

      Every city can establish its communications with the help of only one other city. It can do it in one of the three ways.

      Type 1-It can establish a single communication link with another city 'c'.

      Type 2-It can establish communication links with all cities that communicate with another city 'c', but it can't have a communication link with 'c'.

      Type 3-It can establish communication links with all cities that communicate with another city 'c' and with 'c' also.

       

       

      All communication links are two-way. Having this information, he finds out that it is not possible for him to invade Silicon Valley in a fair way. So he hires a terrorist gang to bomb some cities and destroy them so that he can invade the country successfully. But the terrorists demanded a huge amount of money for bombing a city. Help the King to find out the minimum number of cities that should be bombed so that he can conquer the country of Silicon Valley successfully.

       

      Input

       

      The first line consists of number of test cases t(1<=t<=10)

      The first line of each test case consists of the number of cities n(1<=n<=10^4) in Silicon Valley.

      Each of the next n-1 lines consists of two integers x and c.

      The ith(1<=i<=n-1) line represents that city i+1 establishes a type 'x' communication link with the help of the city 'c'(1<=c<=i).(The country initially contains city 1 alone.)

       

      Output

       

      Output one line for each test case containing the minimum number of cities that should be bombed so that the King can conquer the country.

       


      Added by:jack(chakradarraju)
      Date:2012-02-14
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10648. DUGDUG

      Problem code: DUGDUG

      Dug Dug is a sweet and cute girl who just loves to eat sweet and choclates but only those which I used to gift her. One day I just said that "DUG DUG you are sweet and also like sweet". I will give you as many sweets as you want but you have to tell me the number of ways you can exchange the words in the sentence such that the sentence is not changed. Note that you can exchange one or more pair of words in the sentence simultaneously but all those pairs should be of different words. Dug Dug was confused. She got angry and said if you want to give the sweet then give otherwise go from here. I said "I i will , i i i will give". She got the choclates but you will not get it easily.

      Your task is to find out the number of ways words in a sentence can be exchanged without changing the sentence. Note - one or more pair of words in the sentence can be exchanged simultaneously but all those pairs should be of different words.

      Input

      Input will consists of several lines each containing a sentence consisting of not more than 5000 characters.

      Output

      For each line of input out a single integer denoting the number of ways in which words in a sentence can be exchanged without changing the sentence.

      Example

      Input:
      DUG DUG you are sweet and also like sweet
      I i will , i i i will give
      Ok done you will get what you want
      Done !!!!!!!!

      Output: 3
      13
      1
      0

      Explaination:
      For the first sentence "DUG DUG you are sweet and also like sweet" there are three ways -
      1) You can change the first "DUG" with second "DUG"
      2) You can change the first "sweet" with second "sweet"
      3) You can change the first "DUG" with second "DUG" and first "sweet" with second "sweet".

      Added by:Min2
      Date:2012-02-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10649. Mirror Number

      Problem code: MYQ10

      A number is called a Mirror number if on lateral inversion, it gives the same number i.e it looks the same in a mirror. For example 101 is a mirror number while 100 is not. 

      Given two numbers a and b, find the number of mirror numbers in between them (inclusive of a and b).

      Input

      First line contains T, number of testcases <= 10^5.
      Each testcase is described in a single line containing two numbers a and b.

      0 <= a<=b <= 10^44

      Output

      For each test case print the number of mirror numbers between a and b in a single line.

      Example

      Input:
      3
      0 10
      10 20
      1 4 Output: 3
      1
      1

      Added by:jack(chakradarraju)
      Date:2012-02-14
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10667. PASIJANS

      Problem code: FLLM

      Pasijans, patience, or solitaire is the name for a group of single player card games. One new such game, so new it has no name, is played with cards sporting random integers as values. The game starts by shuffling all cards and
      distributing them in N sequences, not necessarily of equal length. During each turn, the player can remove the first card in any sequence and place it at the end of the “Solution sequence”. The card that was second in the selected sequence now becomes the first and the turn ends. Of course once the card is in the “Solution sequence” it cannot be removed, replaced or altered in any way. So don't even try.

      The game ends when all cards are in the “Solution sequence”. The object of the game is to construct the best possible “Solution sequence”. One sequence  is better than the other if for the first cards they differ, lets call them X and Y, the value on the card X is smaller than the value on the card Y. Write a program that finds the best possible “Solution sequence”.

      Input

      The first line contains one integer N (1 ≤ N ≤ 1000), number of starting sequences.
      Next N lines contain description of input sequences. Each line starts with an integer L (1 ≤ L ≤ 1000), length of the sequence. It's followed by L integers, smaller than 100.000.000.

      Output

      One line containing ΣL numbers, the best possible “Solution sequence” obtainable.

      Example

      Input:
      3
      1 2
      1 100
      1 1

      Output:
      1 2 100

      Added by:Azat Taryhchiyev
      Date:2012-02-15
      Time limit:1s
      Source limit:20000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PAS fpc PAS gpc PYTH 3.2.3 n
      Resource:International Sebat Institutions









      SPOJ Problem Set (classical)

      10675. GENIJALAC

      Problem code: IWGBST

      Mirko is a genius. But the purpose of his inventions is not always obvious. His latest invention, the Shuffle-o-matic 3175, is one of those. The Shuffle-o-matic is used in a very special way. First Mirko places N paper cards, with numbers 1 to N printed on them, on the Shuffle-o-matic working surface. Then he inputs the shuffle sequence in the special input console and hits the go button. The machine than reads the paper cards and outputs the read sequence of numbers on its output tape. It than shuffles the cards according to the shuffle sequence. After that it reads the newly obtaind sequence and writes it onto a new line on its output tape. Then it procedes to shuffle the cards again acording to the same shuffle sequence, scans and writes the output to the tape. The machine does this until it runs out of tape.

      After experimenting with the machine Mirko decided to rest a bit on the floor. There he noticed a piece of output tape. The piece is neatly cut just before the A-th output row nad just after the B-th output row. It is also missing the first C number and the last D numbers in all rows.

      He now wonders how many rows on that piece of paper have the property that all numbers in the row, that are still on the paper, are in the exact same spot they were before all the shuffling began.

      Input

      The first line of input contains integers N, A, B, C and D in that order(1 ≤ N ≤ 500 000, A ≤ B ≤ 10^12, 0 ≤ C, D ≤ N, C + D < N).

      The second line contains the shuffle sequence. The sequence is given as a permutation of numbers 1 to N. If the k-th number in the shuffle sequence is x, after each shuffle the k-th element in the resulting sequence is the x-th
      element in the previous sequence.

      Output

      In the first and only line of input print the number of rows that have the property Mirko is looking for.

      Example

      Input:
      4 1 5 0 1
      1 3 4 2

      Output:
      2

      Added by:Azat Taryhchiyev
      Date:2012-02-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PAS fpc PAS gpc PIKE PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:International Sebat Institutions









      SPOJ Problem Set (classical)

      10676. 0110SS

      Problem code: IWGBS

      Dor is IWGolymp student so he has to count in how many ways he can make N digit numbers that is formed by ones and zeroes.But zeroes can not be next to each other .Help to him in how many differnt numbers can he make .

      ex:3

      101,010,111,110,011

      Input

      A number N    N<=10000

      Output

      Answer for the problem

      Example

      Input:
      2
      Output:
      3

      Added by:Azat Taryhchiyev
      Date:2012-02-16
      Time limit:0s-3.599s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10677. Joseph’s Problem

      Problem code: NAGAY

      Joseph likes taking part in programming contests. His favorite problem is, of course, Joseph’s problem.
      It is stated as follows.
                                 There are n persons numbered from 0 to n − 1 standing in a circle. The person number
                                 k, counting from the person number 0, is executed. After that the person number k of the
                                 remaining persons is executed, counting from the person after the last executed one. The
                                 process continues until only one person is left. This person is a survivor. The problem is,
                                 given n and k detect the survivor’s number in the original circle.

      Of course, all of you know the way to solve this problem. The solution is very short, all you need is one
      cycle:

               r := 0;
               for i from 1 to n do
               r := (r + k) mod i;
               return r;

      Here “x mod y” is the remainder of the division of x by y
      But Joseph is not very smart. He learned the algorithm, but did not learn the reasoning behind it. Thus
      he has forgotten the details of the algorithm and remembers the solution just approximately.
      He told his friend Andrew about the problem, but claimed that the solution can be found using the
      following algorithm:

                                 r := 0;
                                 for i from 1 to n do
                                 r := r + (k mod i);
                                 return r;

      Of course, Andrew pointed out that Joseph was wrong. But calculating the function Joseph described is
      also very interesting.

      Given n and k, find sum of (k%i) from i=1 to n;

      Input

      The input file contains n and k (1 <= n, k <= 10^18)

      Output

      Output the sum requested.

      Example

      Input:
      5 3
      Output:
      7
      

      Added by:Azat Taryhchiyev
      Date:2012-02-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: PERL PERL 6
      Resource:ACM ICPC 2005–2006, Northeastern European Regional Contest St Petersburg – Barnaul – Tashkent –









      SPOJ Problem Set (classical)

      10683. DRIVE

      Problem code: BYTESB

      Black Widow needs to get to the Avengers’ aid and fast. Stark may have lent her his new Audi but she forgot to fuel it up (people make all kinds of stupid mistakes, but if they look like Scarlet Johansson, who cares?). She needs to cross the next hill to get to her team but there’s only a little fuel left. So, obviously she’ll take the most efficient route. However, some parts of this route go uphill, some go downhill – each part with a different slope and different length.
      The fuel expenditure (per unit distance travelled) increases linearly with the driving speed v but there’s also an offset that depends on the slope s of the hill – let’s say when going downhill on a particular road, she might be able to go at 8 km/h without expending any fuel on the other hand, if she were to travel that same road uphill, she would expend fuel at the same rate as if she were driving 8 km/h faster along a flat road.
      The car’s fuel consumption c in litres per kilometer is given by
      c = max(0; a*v + b*s); (1)
      where
      a : fuel expenditure rate on a flat road
      v : speed in km/h
      s : inclination of the road
      b : positive constant

      Acceleration and deceleration are instantaneous and do not cost any fuel.
      There is also a safe speed limit that she can’t exceed. How quickly can she get there?

      Input

      On the first line a positive integer: the number of test cases, at most 100. After that per test case:

      One line with four floating point numbers a(0.1<=a<=100), b (0.1<=b<=100),
      vmax (10 <=vmax<=200) and f (0<=f<=50): the standard (flat road) fuel consumption rate of your car, the slope factor, the maximum speed of your car in km/h, and the amount of
      fuel you have left in liters, respectively.

      One line with an integer r (1<=r<=10000): the number of road segments.

      r lines with two floating point numbers xi and yi (1<=xi<=1 000, -1 000<=y<=1 000)
      each: the horizontal distance and height change (both in meters) of the i-th road segment. Each road segment has constant slope

      Output
      One line per test case: the earliest  time in hours in which you can make it to the 
      town. It is guaranteed that if it is possible  it will always be possible
      in <= twenty four HRS. If  impossible then output “IMPOSSIBLE” instead.

      Your output should have a relative or absolute error of at most 10^(-6).

      Sample in- and output
      Input Output
      2

      1.0 100.0 200.0 10

      2

      1000 0

      1000 -1000

      10.0 1.0 150 0.0

      1

      100.0 -100.0

       

      OUTPUT

      0.1141421356

      1.414213562

       


      Added by:Troika::Bytes
      Date:2012-02-16
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10699. Symmetry

      Problem code: SYM12


      After taking a modern art class, Farmer John has become interested in finding geometric patterns in everything around his farm. He carefully plots the locations of his N cows (2 <= N <= 1000), each one occupying a distinct point in the 2D plane, and he wonders how many different lines of symmetry exist for this set of points. A line of symmetry, of course, is a line across which the points on both sides are mirror images of each-other. Please help FJ answer this most pressing geometric question.

      INPUT FORMAT:

      * Line 1: The single integer N.

      * Lines 2..1+N: Line i+1 contains two space-separated integers representing the x and y coordinates of the ith cow (-10,000<= x,y <= 10,000).

      SAMPLE INPUT

      4 0 0 0 1 1 0 1 1

      The 4 cows form the corners of a square.

      OUTPUT FORMAT:

      * Line 1: The number of different lines of symmetry of the point set.

      SAMPLE OUTPUT

      4

      OUTPUT EXPLANATION

      There are 4 lines of symmetry -- one vertical, one horizontal, and two diagonal.




      Added by:Ikhaduri
      Date:2012-02-16
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Usaco FEB12









      SPOJ Problem Set (classical)

      10701. The Lazy Gamer

      Problem code: MYQ11

      In the kingdom of Thuvax, a mobile game called Thuball became very popular.  
      The description of the game is as follows:
      A mobile phone made in Thuvax has a screen made of X*Y pixels. Thuball is played by throwing a ball (of size 1 pixel) at an angle of 45 degrees from the bottom of the screen. The ball changes its direction if and only if it hits the left/right/top edge of the screen or an obstacle on its way.  
      There are N fixed obstacles (of size 1 pixel each) on the screen. There are no obstacles in the bottom-most row of the screen.  
      If the moving ball's edge comes in contact with an obstacle's edge, it gets reflected by 90 degrees.
      If the moving ball's corner comes in contact with an obstacle's corner, it is reflected by 180 degrees.
      In both reflections the obstacle doesn't move.
      There is a reflector of length L pixels placed below the bottom row, which reflects (akin to mirror reflection, ie 90 degrees) the ball incident on it.
      The game finishes only when the ball reaches the bottom row and the reflector is not present below it. The total distance (in pixels) travelled by the ball is the score attained during a round until the game finishes.
      If the game does not finish, the score is 0.

      Gosu, a Thuvaxian was very fond this game. He had set the highest score in Thuball in his friend Visu's phone. Not happy with the situation where he didn't have the highest score, Visu decided to recruit you to do his dirty work.
      Visu is lazy and doesn't want to move the reflector after starting the game. But, he wants to ensure that he gets the highest score possible with a reflector of length L when its kept stationary in any position.
      Help Visu out by telling him the maximum score he can get without moving the reflector for Q different lengths.

      Input

      First line contains two integers X and Y, which are the height and width of the screen. (1<=X,Y<=1000)
      Second line contains the number of obstacles N followed by N lines with two integers xi and yi, position of each obstacle.
      Consider the bottom-left corner of the screen as origin and the top-right corner to have the coordinates:(X-1,Y-1). 
      The next line contains Q, for the number of cases (for different lengths of the reflector).(1<=Q<=1000)
      Followed by Q lines with one positive integer L, representing the length of the reflector.

      Output

      For each query output the maximum score Visu can achieve without moving the reflector in a single line.

      Example

      Input:
      3 4
      1
      2 3
      1
      3
      Output:
      6
      

      Added by:jack(chakradarraju)
      Date:2012-02-16
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10704. The Great Escape

      Problem code: MYQ12

       

      A map consists of N checkpoints (numbered from 1 to N) connected by M one way roads. A thief is at checkpoint S. He wants to move to checkpoint D. The police, guessing that the thief will move through the route that takes him the least time to reach D from S, have called for security alerts to be placed in all the roads of all such routes. The thief wants to reach D without passing through any of those security alerted roads in the least possible time. If there are multiple such routes, he wants to travel so as to cross a minimum number of checkpoints. Find the minimum time required by the thief to reach D from S, the minimum number of checkpoints in such a route and the number of such routes available. Since the number of such routes may be huge, print the number of such routes modulo 1000000007.

      Input

      The first line of the input consists of a single integer t representing the number of test cases(1<=t<=300)
      The first line of each test case consists of two integers N, M where N is the number of checkpoints and M is the number of roads. (1<=N <= 500 and 1<=M <= 10^4)
      The next M lines consist of three integers x,y,t where x and y represent that the road can be used to travel to checkpoint y from checkpoint x in time t (t <= 100) (1<=x,y<=N)

      The last line contains S and D (source and Destination).

      Output

      For each test Case, output a single line containing 3 integers x,y,z. Where x is the least amount of time needed to travel from S to D without using any of the security alerted roads, y is the minimum number of checkpoints in such a route and z is the number of such routes modulo 1000000007. If there is no such path print -1.

       

      Example

      Input:
      1
      3 3
      1 3 2
      1 2 2
      3 2 4
      1 2
      
      Output:
      6 3 1

      Added by:jack(chakradarraju)
      Date:2012-02-16
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Bytecode 2012









      SPOJ Problem Set (classical)

      10707. Count on a tree II

      Problem code: COT2

       

      You are given a tree with N nodes.The tree nodes are numbered from 1 to N.Each node has an integer weight.

      We will ask you to perfrom the following operation:

      • u v : ask for how many different integers that represent the weight of nodes there are on the path from u to v.

       

      Input

      In the first line there are two integers N and M.(N<=40000,M<=100000)

      In the second line there are N integers.The ith integer denotes the weight of the ith node.

      In the next N-1 lines,each line contains two integers u v,which describes an edge (u,v).

      In the next M lines,each line contains two integers u v,which means an operation asking for how many different integers that represent the weight of nodes there are on the path from u to v.

      Output

      For each operation,print its result.

      Example

      Input:
      
      8 5
      8 2 105 2 9 3 8 5 7 7 1 2 1 3 1 4 3 5 3 6 3 7 4 8
      2 5
      7 8
      Output:
      4

       

      <p>You are given a tree with <strong>N</strong> nodes.The tree nodes are numbered from <strong>1</strong> to <strong>N</strong>.Each node has an integer weight.</p>
      <p>We will ask you to perfrom the following operation:</p>
      <ul>
      <li><strong>u v k</strong> : ask for the kth minimum weight on the path from node <strong>u</strong> to node <strong>v</strong></li>
      </ul>
      <p> </p>
      <h3>Input</h3>
      <p>In the first line there are two integers <strong>N</strong> and <strong>M</strong>.(<strong>N,M</strong><=100000)</p>
      <p>In the second line there are <strong>N</strong> integers.The ith integer denotes the weight of the ith node.</p>
      <p>In the next <strong>N-1</strong> lines,each line contains two integers <strong>u</strong> <strong>v</strong>,which describes an edge (<strong>u</strong>,<strong>v</strong>).</p>
      <p>In the next <strong>M</strong> lines,each line contains three integers <strong>u</strong> <strong>v</strong> <strong>k</strong>,which means an operation asking for the kth minimum weight on the path from node <strong>u</strong> to node <strong>v</strong>.</p>
      <h3>Output</h3>
      <p>For each operation,print its result.</p>
      <h3>Example</h3>
      <pre><strong>Input:</strong>
      <div id="_mcePaste" style="position: absolute; left: -10000px; top: 320px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">8 5</div>8 5
      105 2 9 3 8 5 7 7
      1 2        
      1 3
      1 4
      3 5
      3 6
      3 7
      4 8<br />2 5 1<br />2 5 2<br />2 5 3<br />2 5 4<br />7 8 2 </pre>
      <pre><strong>Output:</strong>
      2<br />8<br />9<br />105<br />7 </pre>

       

       


      Added by:Fotile
      Date:2012-02-17
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Just for fun...









      SPOJ Problem Set (classical)

      10711. VUK

      Problem code: NAGAY1

      Vjekoslav the Wolf is running away from a bunch of blood hungry hunters. The hunters are smart and hide behind trees. Vjekoslav knows this, but doesn't know which trees. He would like to run to his comfortable, civilized cottage (as opposed to the hunters quite uncivilized den, yes I am rooting for the Wolf here) staying as far away as possible from any trees.

      The forest can be represented as a N by M gird. Let us mark empty meadow patches with '.', patches with a tree in the middle with '+', Vjekoslav's current position with 'V' and the position of his cottage with 'J'. Vjekoslav can run from his current patch to any other patch north, east, south or west from him, even if it contains a tree.
      If Vjekoslav is standing in R-th row and C-th column on the grid and there is a tree in the A-th row and B-th column then the distance between Vjekoslav and that tree is:

      |R-A| + |C-B|

      Help Vjekoslav find the best route to his cottage. The best route is any route that maximizes the minimal distance between Vjekoslav and all trees at any given moment. Note that Vjekoslav's cottage doesn't occupy the entire patch so that patch must also be included in the route.

      Input

      The first line of input contains integers N and M (1 ≤ N, M ≤ 500), grid dimensions.
      The next N lines contain M characters each: '.', '+', 'V', 'J'.
      Input will contain exactly one character 'V' and 'J' and at least one character '+'.

      Output

      Output a single integer, the minimal distance from a tree in the optimal route.

      Example

      Input:
      4 4
      +...
      ....
      ....
      V..J

      Output:
      3

      Added by:Azat Taryhchiyev
      Date:2012-02-17
      Time limit:1s
      Source limit:30000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8 NODEJS PAS fpc PAS gpc PIKE PYTH 3.2.3 n
      Resource:2011 KRSU School Contest [olymp.krsu.edu.kg]









      SPOJ Problem Set (classical)

      10712. Easy Calculation

      Problem code: TRIGALGE

      Find x such that Ax+Bsin(x)=C.

      Input

      The first line denotes T(number of test cases). 3T integers follow denoting A,B and C for every test case. (A>=B>0). All Integers are less than 100000.

      Output

      T real numbers rounded to 6 digits one in each line.

      Example

      Input:
      1
      1 1 20
      
      Output:
      19.441787

      Added by:Saransh Bansal
      Date:2012-02-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10725. String Subsequence

      Problem code: STRSEQ

       

      Given a string of digits, find the smallest nonnegative integer that does not occur in the given string as a subsequence. The length of the string is between 1 and 100000, inclusive.

      Input

      The input consists of several lines (at most 200), each with a single string S, with between 1 and 10^5 digits.

      Output

      Print a single line for each string containing the smallest nonnegative integer that does not occur in the given string as a subsequence.

      Example

      Input
      9876543210
      21698921085321984125
      12345678901
      
      Output
      11
      7
      22
      
      

      Added by:Marcos Kawakami
      Date:2012-02-18
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Author: Guilherme Souza (guirns)









      SPOJ Problem Set (classical)

      10730. Michel and the championship

      Problem code: CHAMPS

       

      Michel is participating in a championship where each participant have pi (0<=i<=N-1) points. He knows for some pairs of participants an inequality between the points of each one, in the form pA -pB >= C. Now he wants to know if his data is correct, i.e., if its possible to assign points for each participant and satisfy all the inequalities.

      Input

      The input consists of several test cases (at most 150). The first line of each test case consists of two integers N and M (1<=N<=500, 0<=M<=5000). Then follow M lines of three integers A, B and C, indicating that pA -pB >= C (0<=A,B<=N-1, |C|<=20000).

      Output

      Print a single line for each test case with 'y' if the data is valid or 'n' if its not.

       

      Example

      Input
      2 2
      0 1 2
      1 0 2
      4 4
      0 1 1
      1 2 1
      2 3 -2
      3 0 1
      4 4
      0 1 1
      1 2 1
      2 3 -3
      3 0 1
      
      Output
      n
      n
      y
      
      

      Added by:Marcos Kawakami
      Date:2012-02-19
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Author: Guilherme Souza (guirns)









      SPOJ Problem Set (classical)

      10732. Trapezoid

      Problem code: TRAPEZBO

      Consider two arbitrarily chosen horizontal lines. A trapezoid Ti between these lines has two
      vertices situated on the upper line and the other two vertices on the lower line (see figure below).
      We will denote by ai, bi, ci and di the upper left, upper right, lower left and respectively lower right
      vertices of the trapezoid Ti. A subset S of trapezoids is called independent if no two trapezoids from
      S intersect.

      Task

      Determine the cardinality of the largest independent set of trapezoids (the largest set means the set
      with most elements). Also find the count of different independent sets with maximum cardinality.
      Find this count modulo 30013.

      Input

      The first line of input contains one integer N – the number of trapezoids. Each of the next N lines
      contains four integers ai, bi, ci and di. No two trapezoids have a common vertex (corner).

      Output

      The only line of output should contain two numbers separated by space: firstly, the cardinality of
      the largest independent set; secondly, the count of different independent sets with maximum
      cardinality modulo 30013.

      Constraints

      1 ≤ N ≤ 100 000
      1 ≤ ai, bi, ci, di ≤ 1 000 000 000

      Example

      The picture below is NOT an accurate representation. The trapezoids' top and bottom have been shifted up and down for visibility.

      Trapezoid_Example

      Input:
      7
      1 3 1 9
      4 7 2 8
      11 15 4 12
      10 12 15 19
      16 23 16 22
      20 22 13 25
      30 31 30 31 Output:
      3 8

      Added by:kipoujr
      Date:2012-02-19
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PYTH 3.2.3 n
      Resource:Balkan Olympiad In Informatics, 2011, Romania









      SPOJ Problem Set (classical)

      10738. Ra-One Numbers

      Problem code: RAONE

      In the War between good and evil . Ra-One is on the evil side and G-One on the good side.

      Ra-One is fond of destroying cities and its G-one's duty to protect them..

       

      Ra-One loves to destroy cities whose Zip Code has special properties. He says he loves to destroy cities which have Ra-One numbers as their ZIp Code.

      Any number is Ra-one if the Difference between Sum of digits at even location and Sum of digits at odd location is One (1).. For eg... for 234563 is Ra-One number

      digits at odd location are 3,5,3 (unit place is location 1 )

      digits at even location are 2,4,6

      Diff = (2+4+6)-(3+5+3)=12-11 = 1.

      And 123456 is not Ra-One number

      diff = (5+3+1) - (2+4+6) = -4

       

      G-One knows this about Ra-one and wants to deploy his Army members in those cities. 1 army member will be deployed in each city.

      G-one knows the range of ZIP-Codes where Ra-One might attack & needs your help to find out how many army members he needs.

      Can you help Him ?

      Input

      first line will have only one integer 't' number of Zip-Code ranges. it is followed by t lines

      each line from 2nd line cotains 2 integer 'from'  and 'to'. these indicate the range of Zip codes where Ra-one might attack .(from and to are included in the range)

      Output

      A single number for each test case telling how many army members G-One needs to deploy.

      each number should be on separate lines

      Example

      Input:
      2
      1 10
      10 100


       Output:
      1
      9
      explanation:
      for 1st test case the only number is 10
      for 2nd test case numbers are 10,21,32,43,54,65,76,87,98

      NOTE:
      t will be less than 100
      from and to will be between 0 and 10^8 inclusive

      Added by:Devil D
      Date:2012-02-21
      Time limit:1s
      Source limit:30000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      10790. G-One Numbers

      Problem code: GONE

      The War of Evil vs Good continues and Ra-One and G-One continue to be on respective sides.

      After saving all the cities with Ra-One Numbers G-One realised that some cities whose population is a "G-One Number" can be easy target for Ra-One.

      A G-One number is a number sum of whose digits is a prime number

      For eg. 12 .. sum = 1+2 =3 ... 3 is a prime number.

      G-One wants to find out all the populations which can be g-One numbers....

      Can You help Him.?

       

      You will be given the range of population and you have to tell him how many in this range are G-One Numbers.

      Input

      first line has number 'c' indicating the number of ranges.

      'c' lines follow and contain two numbers ..... 'f' and 't' inclusive.

      Output

      Print a single line per case giving the number of populations which are G-One numbers.

      Example

      Input:
      3
      10 19
      1 9
      20 29


       Output:
      4
      4
      5

      Note: c will be less than 100
      t and f will be less than 10^8 inclusive

      Added by:Devil D
      Date:2012-02-24
      Time limit:1s
      Source limit:30000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      10798. Wachovia Bank

      Problem code: WACHOVIA

        Danilo Gheyi is a renowned bank robber. He is known worldwide for accomplishing the most profitable bank robbery, in Fortaleza, Ceará. Danilo and his friends dug a tunnel to get into the main chest. There were some bags, with different amounts of money or jewelry and weight. They had to leave about 50% of the total value, since the truck couldn't carry all the bags.

      Danilo wasn't caught, and to show that he can do itall again, he is planning a robbery to one of the safer banks in USA -the Wachovia Bank. He wants your help to maximize the amount stolen, avoiding a huge loss as it happened in Fortaleza.

      Write a program that, given the maximum weight the truck is ableto carry and the information about each bag in the bank, determine the maximum value that Danilo can steal.

       

       

      Input

      The input consists of several instances. There is an integer N (1 ≤N ≤200) in the first line; it stands for the number of instances. The first line of each instance contains two integers, K and M (8 ≤K ≤1000 and 1 ≤M ≤50) representing, respectively, the maximum weight the truck can handle and the amount of bags in the bank. The next M lines describe each bag with two integers A and B (8≤A ≤200 and 1 ≤B ≤25): the weight and the value of the bag, respectively.

      Output

      For each instance output a sentence “Hey stupid robber, you can get P.”,and P represents the maximum value Danilo can steal.

      Example

      Input:
      3
      34 5
      178 12
      30 1
      13 7
      34 8
      87 6
      900 1
      900 25
      100 10
      27 16
      131 9
      132 17
      6 5
      6 23
      56 21
      100 25
      1 25
      25 25
      100 2
      
      Output:
      Hey stupid robber, you can get 8.
      Hey stupid robber, you can get 25.
      Hey stupid robber, you can get 99.

      Added by:Mateus Dantas [ UFCG ]
      Date:2012-02-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Mateus Dantas









      SPOJ Problem Set (classical)

      10799. Happiness at the lowest cost

      Problem code: RS2D

       

      Rafael Phofo was a happy guy living with his best friend, Danilo Gheyi. They were so friends that they made a blood pact during their childhood. But Matheus Pheverso, the owner of the Infelicity Forest, a forest that Rafael and Danilo used to cross every day, didn't like to see them together. He always tried to separate them; a day he finally achieved his goal, making the two guys lost in two different points of his forest.
      Rafael Phofo knew it wouldn't be hard to find his friend, because he had some RS2D (love notes), the money that Matheus Pheverso charged to let his visitors cross each street connecting two points of the forest.
      But there was a problem: analyzing the map of the forest, Rafael realized that his amount of RS2D could be insufficient. So he called you, a great programmer and also his friend, to know if it's possible to find Danilo with that amount of RS2D. You need to write a program that determine the minimum amount of RS2D necessary. Consider that Rafael is in the position 1 of the forest and Danilo is in the position N.

       

      Rafael Phofo was a happy guy living with his best friend, Danilo Gheyi. They were so friends that they made a blood pact during their childhood. But Matheus Pheverso, the owner of the Infelicity Forest, a forest that Rafael and Danilo used to cross every day, didn't like to see them together. He always tried to separate them; a day he finally achieved his goal, making the two guys lost in two different points of his forest.

      Rafael Phofo knew it wouldn't be hard to find his friend, because he had some RS2D (love notes), the money that Matheus Pheverso charged to let his visitors cross each street connecting two points of the forest.

      But there was a problem: analyzing the map of the forest, Rafael realized that his amount of RS2D could be insufficient. So he called you, a great programmer and also his friend, to know if it's possible to find Danilo with that amount of RS2D. You need to write a program that determine the minimum amount of RS2D necessary. Consider that Rafael is in the position 1 of the forest and Danilo is in the position N.

       

       

      Input

       

        The input consists of several instances; the first line contains an integer K (1 ≤K ≤20), the amount of instances. The first line of each instance contains two integers N and M (1 ≤ N ≤ 10⁶, 1 ≤ M ≤ 10⁶), the amount of points and the amount of streets in the forest, respectively. The next M lines contain tree integers A, B and C (1 ≤ A ≤ N, 1 ≤ B ≤ N, 1 ≤ C ≤ 10⁶), indicating a street between the points A and B with a cost C.

       

      Output

      For each instance output a sentence “Rafael will find his love for P RS2D.”,and P represents the minimum amount of RS2D that Rafael needs to caught Danilo.

      Example

      Input:
      2
      6 9
      1 2 7
      1 5 14
      1 3 9
      2 4 15
      2 3 10
      3 5 2
      3 4 11
      5 6 9
      4 6 6
      5 7
      1 2 1
      1 3 5
      2 4 2
      3 4 2
      3 5 3
      2 5 3
      4 5 1
      
      Output:
      Rafael will find his love for 20 RS2D.
      Rafael will find his love for 4 RS2D.
      

      Added by:Mateus Dantas [ UFCG ]
      Date:2012-02-25
      Time limit:0.150s-0.360s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Mateus Dantas









      SPOJ Problem Set (classical)

      10800. GAME

      Problem code: GAMECG

      Ashton Carl McDonalds (known as A.C.M.) works at a small school. The school have decided to compete in a new style of game designed by programmers. This game is organized in teams, each team have the size of M competitors, the goal of the game is to each team solve the maximum number of problems, if there is a tie, the team who solved faster win. It is important to you know that the order of the members in a team doesn't matter.

      Carl was designed by his school to be a kind of coach of this game. He needs to train all the teams of his school, and the most important, he needs to choose theses teams. A.C.M is kind of worried if it will be a lot of teams, and maybe it will be a lot of work to him. Due to this, he decides to count how many different teams can exist in his school.

      McDonalds is not good on mathematics, due to this he asked you to count the number of different teams. A.C.M knows that the result can be very large, so he asked to you to give the result in modulus 1300031, but he needs to know if the result exceeds 1300030 or not.

      Input

      The input consists of several lines.

      Each line consists of two integers N (1 <= N <= 10^6) and M (1 <= M <= N), the number of students and the numbers of members in each team.

       

      Output

      The output consists of two lines. The first line contains the result in modulus, and the second line contains “Exceeds” if the result exceeds 1300030 or “Does not exceed” if the result does not exceed 1300031.

       

      Sample Input

      Sample Output

      3 1

      140 60

      15 8

      3

      Does not exceed

      207865

      Exceeds

      6435

      Does not exceed


      Added by:Mateus Dantas [ UFCG ]
      Date:2012-02-26
      Time limit:1.100s-2.299s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Phyllipe Cesar









      SPOJ Problem Set (classical)

      10802. Sum of Tetranacci numbers

      Problem code: TETRAHRD

      The sequence of Tetranacci numbers is defined as follows:
      an = an-1 + an-2 + an-3 + an-4 with a0 = a1 = a2 = 0 and a3 = 1.

      Input

      Input starts with a positive integer t ≤ 4000, then t lines follow. Each of the t lines contains two space separated integers m and n with 0 ≤ m ≤ n ≤ 109.

      Output

      Calculate am + am+1 + ... + an and print the result modulo 1000000007.

       

      Example

      Input:
      2
      1 2
      1919 5393
      
      Output:
      0
      66616
      

      Note: If your solution times out, you may try the tutorial version first.


      Added by:numerix
      Date:2012-02-26
      Time limit:1s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      10809. Unlock it !

      Problem code: DCEPC204

      Vaibhav loves playing with numbers. To enjoy his summer holidays he decides to join the group "number players" of his school. He decides to visit the group hall. At the gate he finds a lock and a paper. The gate can only be unlocked by solving the puzzle written on the paper. Vaibhav is stuck with his puzzle, help him in solving it.

      Here is the puzzle description:

      Given a sequence F(N)

      F(0)=1

      F(1)=1

      F(2)=1

      F(n) = product of all odd primes less than or equal to n (for n<=10)

      F(n) = (2^(n/4)) * F(n/5)* F(n/10)      (for n>10)

      For every fraction , a ceil value is taken for evaluation.

      For eg. F(11)=2^ceil(11/4) * F(ceil(11/5)) * F(ceil(11/10))  = 2^3 * F(3) * F(2) = 24

      Given N. Find the max value of (a^b)%mod such that a and b satisfies the relation gcd(a,b) = F(N).

      Gcd : Greatest common divisor

      Input

      First line gives T, total number of testcases.

      Next T line gives number N

      Output

      For each test case, print the desired value on a new line

      Constraints

      T<=10

      N<=10^6

      mod = 10^9.

      NOTE: a must be <= 5*F(n) and b must be <=5*F(n) , a can be equal to b and mod=10^9

      Example

      Input:
      1
      2

      Output: 1024

      Added by:dce coders
      Date:2012-02-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10810. Its a Murder!

      Problem code: DCEPC206

      Once detective Saikat was solving a murder case. While going to the crime scene he took the stairs and saw that a number is written on every stair. He found it suspicious and decides to remember all the numbers that he has seen till now. While remembering the numbers he found that he can find some pattern in those numbers. So he decides that for each number on the stairs he will note down the sum of all the numbers previously seen on the stairs which are smaller than the present number. Calculate the sum of all the numbers written on his notes diary.

      Input

      First line gives T, number of test cases.

      2T lines follow.

      First line gives you the number of stairs N

      Next line gives you N numbers written on the stairs.

      Output

      For each test case output one line giving the final sum for each test case.

      Constraints

      T<=10

      1<=N<=10^5

      All numbers will be between 0 and 10^6.

      Example

      Input:
      1
      5
      1 5 3 6 4

      Output: 15

      Added by:dce coders
      Date:2012-02-26
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10814. Unique Paths

      Problem code: DCEPC202


      Vaibhav sir and Jyoti ma’am are pretty pissed off after taking the doubt clearing session for first batch. People are not taking them seriously and doing their assignments, so they decided only intelligent students should appear in the tutorials. So they put up a condition, only those students who came to the class walking on unique paths can attend the class. By unique path they meant that at least 1 move differs from any other path. You are at the position (0,0) in the corridor and the class is at the position (n-1,4). Where n is the length of corridor and width is 5 units. You can move only to the adjacent tile on the floor. As you are not idiots you have to reach at the class using shortest path only. Corridor has some broken tiles which are not to be traversed on, they are : (0,2),(n/2,0),(n/2,2)(n/2,4) and (n-1,2). The minimum students required for class is given (k). You have to tell the minimum length of corridor to select k students.

      Input

      First line contains T (1<=T<=10) number test cases. Each test case consist of 1 integer K (2<=K<=10^18),
      minimum number of student required.

      Output

      Minimum length of corridor required to select at least K student.

      Note : Required length of the corridor will always be between 4 and 10000 (inclusive)

      Example

      Input:
      2
      2
      9

      Output: 4
      6
       

      Added by:dce coders
      Date:2012-02-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10815. Finally a Treat

      Problem code: DCEPC207

      Anuja ma’am is getting more and more obsessed by her name (actually she loves it!!!). She has a strong belief that her name has something very special but she could not make it out what is it. As Vaibhav sir is very good in finding pattern he helped her with her problem, that she has a name in which only one character has maximum frequency i.e. ‘a’. She became very happy and decided to give a party to all of the members of DCE Coders who have special names. But wait, she finds out that the list is too big, so she decided to narrow it down. Heres how she narrows it: “Anuja ma’am will give a party to all those whose name is special and the character which makes their name special MUST be the character with maximum frequency in the entire list of names. There is only ONE special character in the string.”

      As a student you are required to make a list of names ELLIGIBLE for party.

      Remember, a name is special only if a SINGLE character has the maximum frequency in it. (See example #2 )

      Input

      1st line contains T(1<=T<=100), number of test cases. Next T lines contain a string(1<=Length of
      String<=10000) containing list of names separated by SPACES.

      Output

      Output k+1 lines for each test case, where k is the number of students ELLIGIBLE. First line
      contains “Case #x:” where x is the case number starting from 1. Then next k lines contain the names
      of ELLIGIBLE students.

       

      Note: Each input string will have at least 1 word (of at least 1 character). i.e. there is no input string with only spaces

      Example

      Input:
      2
      abcdd abccd cccd
      aabb aabcc aaa adaa Output: Case #1:
      abccd
      cccd
      Case #2:
      aaa
      adaa

      Added by:dce coders
      Date:2012-02-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10818. Medium Factorization

      Problem code: FACTCG2

      The task in this problem is to write a number in a multiplication of prime numbers separated by “ x”. You need to put the

      number 1 in this multiplication.


      Input

      The input consists of several lines.

      Each line consists of one integer N (1 <= N <= 10^7) .


      Output

      For each line you need to output the factorization separated by “ x” and including 1.


      Sample Input

      1

      2

      4

      8

      Sample Output

      1
      1 x 2
      1 x 2 x 2
      1 x 2 x 2 x 2

      Added by:Phyllipe Medeiros
      Date:2012-02-26
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10819. BF Vector

      Problem code: BFTAB

      Your task is to put in the output n char of the read input. You have to use BF

      Input

      - first line have x chars (1<=x<=99) and ends with a line feed (10)

      - second line is one number n (00<=n<=99)

      Output

      Its only one char

      Example

      Input:
      01234567
      02
      
      Output:
      2
      Input:
      0112ok3-12kewpl11,2eo12o3ke12ls12w1io2j34e12md
      14
      Output:
      l

      Added by:Marek Kotewicz
      Date:2012-02-27
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:BF









      SPOJ Problem Set (classical)

      10820. Obsession

      Problem code: DCEPC203

      Ankur sir is really obsessed with dce coders. Every other day he announces to the admins the current number of members and boasts about the continuos increase in the member count. Within a week the admins got bored of his habit and started losing interest in this topic. Ankur sir is very clever. He knows that every body loves to solve puzzles. To maintain their interest he decides to ask a puzzle based on the number of current members. This way he can still bug the admins about the increasing member count without making them feel bored. The puzzle says for the given member count N, tell me how how many smaller numbers (k>=2) exist such that F(k)=2*k*k-1 is a prime.

      Input

      First line gives T, the number of test cases

      Each of the next T lines give a number N.

      Output

      Print the output for every test case on a new line   

      Constraints

      T<=1000

      2<=N<=10000000

      Example

      Input:
      1
      5
      Output:
      3

      Added by:dce coders
      Date:2012-02-27
      Time limit:20s
      Source limit:3000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10822. The Prime Minister

      Problem code: DCEPC200


      DCE Coders mentors got fed up by making problems, they are deciding upon the toughest problem for contest. Everybody started to tease Ankur sir that he can’t make a single tough problem for juniors. He got very angry, now you only handle Ankur sir’s anger (Beware: All the tough number theory problems given to you as assignments are like 2+2=4 for Ankur sir). Here is the problem given by him (Say thanks to Jyoti ma’am that she softens the problem slightly.. ;)). You are given an integer n.  There will be 2 different numbers K1 and K2, such that K1*K2 = n.

      Both of which satisfies the equation  (Totient(K!)  mod K) !=0.  

      You are also given value of a function, F(n) = Sum of squares  of factor of n. (example F(20) = 546)

      Now you have to calculate the value of x and y which satisfies the equation K1x + K2y = m. Where m is given. Since there are many roots you have to find a single pair (x,y) which satisfies the equation having minimum absolute value of (x +y). If no pair is possible output -1. Else output (abs(x+y)^m)%mod

      Input

      First line contains T(1<=T<=10000) number of test cases. Each test case consist of single line containing 3 integers n, F(n) and m. 

      Output

      Output  T lines , each line contains a single integer ((x+y)^m)%mod.

      Constraints

      T<=10000

      N<=10^8

      F(n)<=10^18

      M<=100

      mod=10000000000283

      Example

      Input:
      1
      6 50 3
      
      Output:
      0 

      Added by:dce coders
      Date:2012-02-27
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10833. Counter-intelligence

      Problem code: CONINT

      After successfully conquering half of the known world, General Frey has realized the need to concern himself with the Empire's own security. Therefore, he told his most trusted advisor to set up a communication network among the officers of the Empire. In this network, each officer has a designed partner among the list of people he may contact, in a way such that each officer communicates with his partner only. Partnership is mutual, that is, if B is the partner of A, then A is the partner of B.

      The advisor came up with a proposed scheme for the communication activities, which he shows to the general. The general has heard rumors that some of the members of the opponent army have mind-reading abilities, so he wishes to take additional precautionary measures. In order for the system to be accepted, there must be a way to switch between two different valid assignments of partners, so that attempts to intercept the messages may be thwarted (two assignments are considered different if at least one person has a different partner in one of them). Your task is to decide whether the system shown by the advisor is safe or not.

      Input

      The input consists of several test cases. The first line of a testcase contains an integer n (1 n ≤ 300), the number of officers in the army. The ith of the following n lines contains an integer t, followed by t integers between 1 and n (not necessarily distinct), each of which is a valid contact for the ith officer. The first of the t integers is the ith officer's current partner. You may assume that no officer appears on their own contact list. 

      The last case is followed by a line containing a single zero.

      Output

      Output one line for each test case. The line should contain the word "Safe" if switching assignments is possible, otherwise, print "Unsafe" (without quotes).

      Example

      Input:
      4 
      2 2 3
      2 1 4
      2 4 1
      2 3 2
      2
      1 2
      1 1 0
      Output: Safe
      Unsafe

      Added by:Fernando Fonseca [ITA]
      Date:2012-02-27
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      10841. Supplying the Suppliers

      Problem code: SUPSUP

      It's battle time yet again, and now General Frey is worried about the supplies to his units. The capital city of the Empire has two exits, the North Gate and the South Gate, at which several key elements to the army will be stored. Several squads are going to be deployed, and seeing as each one of them has different needs, the General needs to decide on which exit he will deposit each supply type. Storing a supply element on both exits is costly and confusing, so the whole shipment for a resource must be located at a single exit.

      The orders that specify which soldier should get which supply should not be disrespected, that is, two soldiers from the same squad cannot swap items if it's more convenient to do so. To solve this issue, the General has decided that a simple rule should be followed: No squad should ever have more than one soldier carrying an element from the opposite exit in which he is located. Given the list of squads and their needs, find out if it's possible to place the items on the exits such that the rule's followed.

      Input

      The input consists of several test cases. On the first line of each test case will be an integer N (1 ≤ N ≤ 100), the number of squads. Each of the following N lines begins with an integer t, describing how many needs that specific squad has. t integers and characters follow, each of which specify a supply type that squad needs. You may assume a supply type fits in a signed 32-bit integer. If the character is 'S', then the soldier that is going to fetch that item is at the South Gate, if it is 'N' the soldier is at the North Gate. Equal integers specify equal supply types, and no item appears twice on the same squad list. The number of different supply types in a single testcase is at most 100.

      The last test case will be followed by a line containing a single zero.

      Output

      Print a single line for each test case. The line must contain the words "March onward" if it's possible to assign the deposits and follow the General's rules, "Coordination issue" otherwise.

      Example

      Input:
      2
      2 1S 2S
      2 1N 2N
      2
      3 1S 2S 3S
      3 1N 2N 3N
      0 Output: March onward
      Coordination issue

      Added by:Fernando Fonseca [ITA]
      Date:2012-02-28
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      10877. Decoys and Diversions

      Problem code: DECOY

      Apparently, both sides of the battle are now using some sort of cat-and-mouse tactics on the battlefield. The rules are as follows: there are two battles happening simultaneously at different fields. The armies take turns retreating one of their two units to a different location; the retreat of an army automatically causes the opposing army on the same field to follow it. The one that is cornered (that is, has nowhere to retreat on their turn) will be the one that ultimately loses the battle. Given the description of the fields, and supposing that both commanders are perfect strategists, can you decide who is going to win?

      Input

      The first line of input contains an integer T, the number of test cases. Each test case consists of two descriptions of the fields of the battle. A description begins with a line containing integers N (1 N 100), M (1 M 10000), the number of locations in the field and the number of roads connecting the locations, respectively. The following M lines each contain two integers u,v (1 ≤ u,v ≤ N) denoting that there is a one-way road connecting position u to the position v. The initial location of all units is at position 1 in their respective fields.

      Output

      For each test case, output a single line containing the result of the battle, assuming your side is the first to play. Print "I lose" if you're going to lose, "I win" if you're guaranteed to win or "Deadlock" if the battle will go on forever.

      Example

      Input:
      3
      2 1
      1 2
      2 1
      1 2
      2 2
      1 2
      2 1
      2 1
      1 2
      3 2
      1 2
      2 3
      2 1
      1 2 Output: I lose
      Deadlock
      I win

      Added by:Fernando Fonseca [ITA]
      Date:2012-03-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      10883. Customs

      Problem code: CUSTOMSL


      Matheus, Bruno and Ricardo are the boasting for the research department at Indústria de Obras Intermináveis ( IOI ) and they constantly traveled together for another countries to research different methods, equipments and primal materials for  amazing works.  Furthermore, they operate in the informal import market products electronics, bringing equipments and electronics for your friend and coworkers.

      Before leaving they make a list of N products who they have to buy, each one of them with a price Pi DE$ ( Dinheiro Estrangeiro). They have to pay some customs duty if anyone of them exceeds the maximum amount of Q that each one can brings.

      As them always travel together, they note that it’s more cheap for them, if the products are organizated in a way that’s can be possible to reduct the maximum amount of imposts who they have to pay. Given the prices of N products, Q and the maximum tax A, you have to say the minimum price of imposts that they have to pay.

      Input

       

      The input is only a testcase. The first line include an integer N ( 1 ≤ N ≤ 100), that represents the number of products bought.
      The second line include two integers, Q and A ( 1 ≤ Q ≤ 500, 1 ≤ A ≤ 200), that represents the maximum amount of import, and the tax of importation in percent. 
      The next N lines includes each one, an integer Pi ( 1 ≤ Pi ≤ Q ), that represents the price of the i-th product.

       

      The input is only a testcase. The first line include an integer N ( 1 ≤ N ≤ 100), that represents the number of products bought.

      The second line include two integers, Q and A ( 1 ≤ Q ≤ 500, 1 ≤ A ≤ 200), that represents the maximum amount of import, and the tax of importation in percent. 

      The next N lines includes each one, an integer Pi ( 1 ≤ Pi ≤ Q ), that represents the price of the i-th product.

       

       

      Output

      You have to write in your output a single line contains the minimum possible value of impost that Matheus, Bruno and Ricardo have to pay..

      Example 

      Input:
      4
      10 1
      10
      9
      8
      7
      
      Output:
      0.05
      Input:
      6
      9 20
      9
      6
      3
      3
      3
      3
      Output:
      0.00

      Added by:Mateus Dantas [ UFCG ]
      Date:2012-03-02
      Time limit:1s-3.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Olimpiada Brasileira de Informatica - Seletiva 2007









      SPOJ Problem Set (classical)

      10919. I Hate Parenthesis

      Problem code: FERT21_1

      “I Hate Parenthesis”, it was the phrase that Ana said during the class of arithmetic. She want a simple code made for yourself (of course) to “kick out” the parenthesis from particular expressions without break maths.

      Input
      The first line contains the number of test cases T. One expression per line from second to (T+1)-th line. Each expression contains only uppercase letters (each letter can appears once), operators(+,*) and parentheses (()). There are no spaces inside the expressions and no input line contains more than 80 characters.

      Output
      A single line per case. The line must contains the expression without parenthesis. If there is more than one addend then you must sort first the one with more factors. Addends with the same amount of factors must be sorted in alphabetic order. See the input/output for more details.

      Example
      Input:
      2
      C*(A+B)
      (A+B+D*E)*C

      Output:
      A*C+B*C
      C*D*E+A*C+B*C


      Added by:Leandro Castillo Valdes
      Date:2012-03-05
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:-









      SPOJ Problem Set (classical)

      10930. Dixon Dominoes

      Problem code: DIXDOOM


       

      Dixon was in his house, he was a little bored, so he took some dominoes from the case and started thinking: “It is possible to use Qx pieces from the Dominoes so it can make a simulation of a game?” so, Dixon is not a super programmer, but he knows a little bit of constraints in the problems, so he will give it to you, your task, if you choose to accept it, is to find all the possible ways of some N pieces of Domino can be joined together to make a game simulation using exactly Qx dominoes pieces. If you can’t do this, you should print “0”

      Dominoes

      INPUT:

      The input will consists of an integer T, denoting the number of test cases, next, T cases will follow, every case starts with 2 lines N and Q, being N the number of dominoes David has and Q the number of queries you should do, then, N lines will follow, denoting the two parts of a domino piece, as you may know, the domino piece is split in two, so you can join by any side another piece, after this, Q lines will follow, denoting the number of piece you must use to build the game simulation.

       

      CONSTRAINTS:

      1<=T<=100

      1<=N<=16

      1<=Q<=16

      0<=N1,…,NN<=6

      1<=Q1,…,QN<=N

       

      OUTPUT:

      You should output all the possible ways to form a game using Qx pieces (with any possible permutation too), as this number can grow very huge, we need you to print the output modulo 31337.

       

      Sample Input:

      3
      4 3
      2 3
      3 1
      1 4
      4 3
      1
      3
      4
      2 1
      1 2
      1 2
      2
      2 1
      1 1
      1 1
      2

       

      Sample Output:

      8

      10

      4

      4

      8

       

       

      Domino idea credits goes to: Daniel Ampuero and Luis Arguello

       

      Example of the output with the first case and Q=4

      solution 1: joining the pieces 1,2,3 and 4

      solution 2: joining the pieces 4,3,2 and 1

      solution 3: joining the pieces 2,3,4 and 1

      solution 4: joining the pieces 1,4,3 and 2

       

      Tip: In the case with one piece only, you can form a game starting with the two faces of every single piece, i.e. if we want to form a game using just the piece "2 1", one possible game is "2 1" and the other "1 2", resulting in two different ways.


      Added by:David Moran
      Date:2012-03-06
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10945. Foodie Golu

      Problem code: DCEPC301


      Being a big foodie Golu wants to try all the dishes available at a party but because of his increasing weight his mother does not allow him to do so. After a huge fight they both come to an agreement.

      1.  The first rule of the agreement says that Golu should only eat at an interval of 10 minutes.

      2.  The second rule is regarding the stalls available. There are N stalls in one line and Golu should select only one stall to eat at one time. The selected stall must lie at the n/2th position or (n/2 + 1) position (zero indexed) among all remaining stalls.

      3.  Once he has selected a stall he must discard all the stalls to its left (or right) and in future can only eat from the remaining stalls. Also he can eat from a stall only once during the party, so once he has eaten from a stall, it should be discarded too.

      The initial cooking speed at all the stalls is 1 unit. After doing some calculations Golu realises that the speed of cooking of the cook at every stall becomes double every 10 minutes. Depending upon the type of dish available and his eating capacity, he assigned a value to each stall such that any point of time he can eat a quantity which is equal to (value of that stall) * (current speed of cooking at that stall). Since speed is increasing exponentially he only remembers speed as speed % mod at any time.

      Since he wants to eat the maximum amount of food, help him in developing a strategy to eat.

      NOTE: If there are only 2 stalls left, he must choose any one stall and discard the other.

      Input

      First line contains T, the number of test cases. (1<=T<=5)

      First line of each test case contains n, the number of stalls in the party. (1<=n<=3000)

      Next line of each test case contains n space separated integers, representing the value of each of the stalls. (All values are between 1 and 3000 inclusive)

      Output

      Output T lines, one for each test case containing the maximum amount of food Golu can eat mod 10^9+7

      Example

      Input:
      

      1

      5

      2 4 1 3 5

      Output: 21
      Explanation:

      Golu can select the fourth stall first and discard all stalls to its right (i.e discard fifth stall). Then he can select the third stall and again discard all stalls to its right (no stall to discard this time). Finally he chooses the 2nd stall.Therefore total food he can eat = 3*1 + 1*2 + 4*4 = 21.


      Added by:dce coders
      Date:2012-03-06
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10958. Vero Dominoes

      Problem code: VERODOOM

      Vero was one day playing some sort of game that consists in drinking a lot of orange juice, the game's idea is in turning up one domino piece and count the black dots in it, then, drink as many deciliters as the total count of the dots in the domino piece, for example, a 6-maximum-dots dominoes contains 168 dots in it.

       

      She wants to know how much deciliters can be drank in one simple game, she doubts about your skills as a programmer, so she can test your program with over 150 thousands of cases.

       

      INPUT:

       

      The input will start with a T integer number, then, T lines will follow, for each T there will be a number N.

       

      CONSTRAINTS:

      1<=T<=150.000

      0<=N<=50.000.000

       

      OUTPUT:

       

      For each number N you should output the total dots in the domino pieces...

       

      SAMPLE INPUT:

      2

      6

      1

       

      SAMPLE OUTPUT:

      168

      3

       

      Explanation of the second case:

      There's only 1 dot maximum in the domino pieces, so you will count the piece 0 0, 0 1 and 1 1 (you should not count the 1 0 piece as it is represented with the 0 1 piece)

       

      Constraints of the problem has been modified so the problem is a little bit challenging now.


      Added by:David Moran
      Date:2012-03-08
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      10966. Aritho-geometric Series (AGS)

      Problem code: AGS

      Arithmatic and geometric Progressions are 2 of the well known progressions in maths.

      Arithmatic progression(AP) is a set in which the difference between 2 numbers in constant. for eg, 1,3,5,7,9 .... In this series the difference between 2 numbers is 2.

      Geometric progression(GP) is a set in which the ratio of 2 consecutive numbers is same. for eg, 1,2,4,8,16.... In this the ratio of the numbers is 2.

      .....

      What if there is a series in which we multiply a(n) by 'r' to get a(n+1) and then add 'd' to a(n+1) to get a(n+2)...

      For eg .. lets say d=1 and r=2 and a(1) = 1..

      series would be 1,2,4,5,10,11,22,23,46,47,94,95,190 ......

      We add d to a(1) and then multiply a(2) with r and so on ....

       

      Your task is, given 'a' , 'd'  &  'r' to find the a(n) term .

      sicne the numbers can be very large , you are required to print the numbers modulo 'mod' - mod will be supplied int the test case.

      Input

      first line of input will have number 't' indicating the number of test cases.

      each of the test cases will have 2 lines

      firts line will have 3 numbers 'a' ,'d'  and   'r'

      2nd line will have 2 numbers 'n' & 'mod'

      a- first term of the AGS

      d-the difference element

      r - the ratio element

      n- nth term required to be found

      mod- need to print the result modulo mod

      Output

      For each test case print "a(n)%mod" in a separate line.

      Example

      Input:
      2
      1 1 2
      13 7
      2 2 2
      10 8

       Output:

      1
      6


      Description - for the first test case the series is 1,2,4,5,10,11,22,23,46,47,94,95,190..
      13th term is 190 and 190%7 = 1

      Note - the value of a , d , r , n & mod will be less than 10^8 and more than 0.
      for every series 2nd term will be a+d and third term will be (a+d)*r .. and so on ..

      Added by:Devil D
      Date:2012-03-09
      Time limit:0.5s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      10968. LUCIFER Number

      Problem code: LUCIFER


      Lucifer is the only human whi has defeated RA-ONE in a computer game ..

      RA-One is after lucifer for revenge and G-One is there to protect him ...

      All thi G-One and Ra-one Nonsense has disturbed lucifers life..

      He wants to get Rid of Ra-One and kill him . He found that Ra-One can be killed only by throwing Lucifer number of weapons at him.

      Lucifer number  shares the some properties of Ra-One Numbers numbers and G-One Numbers

      Any number is LUCIFER NUMBER  if the Difference between Sum of digits at even location and Sum of digits at odd location is prime number .. For eg... for 20314210 is lucifer number

      digits at odd location 0,2,1,0

      digits at even location 1,4,3,2

      diff = (1+4+3+2)-(0+2+1+0)=10-3  = 7 ..... a prime number.

      Lucifer has access to a Warehouse which has lots of weapons ..

      He wants to know in how many ways can he kill him.

      Can you help him?

       

      Input

      First line will have a number 't' denoting the number of test cases.

      each of the following t lines will have 2 numbers 'a' , 'b'

      Output

      Print single number per test case, depicting the count of Lucifer numbers in the range a,b inclusive.

      Example

      Input:
      
      5
      200 250
      150 200
      100 150
      50 100
      0 50

       Output:
      2
      16
      3
      18
      6


      NOTE: t will be less than 100
      from and to will be between 0 and 10^9 inclusive

      Added by:Devil D
      Date:2012-03-09
      Time limit:0.100s-0.5s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set ()

      11050. R Numbers

      Problem code: ITRIX12E

                                                                      R - Numbers

                       R-numbers are numbers which have the property that they do not have the digit '0 ' and sum of every two adjacent digits of the number is prime. 123 is a R-number because 1+2 =3 and 2+3 =5 and 3 , 5 are primes.

      How many R-numbers can be formed with atmost length N?

      i.e R-numbers of length 1 + R-numbers of length 2 + R-numbers of length 3+....... R-numbers of length N

      Length of a number = Number of digits in the number

      Only four single digit numbers are R-numbers which are nothing but single digit primes 2,3,5,7

      Input Specification:

         The first line of the input file contains T which denotes the number of Test cases.The next T lines contain an integer N <= 10^9

      Output Specification:

                      Print the numbers of R-numbers modulo 1000000007. [10^9+7];

      Sample Input

      2

      1

      2

      Sample Output

      4

      33


      Added by:Radhakrishnan
      Date:2012-03-12
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Own problem









      SPOJ Problem Set (classical)

      11054. Discords Dilemma

      Problem code: PONY3

      Discord is in trouble for causing discord, so he is trying to escape from Equestria. He's arrived at the port, and he doesn't care what boat he gets on, he just wants to get out. He can see the boat schedule, where he sees that N boats are arriving today,

      boat 1 arrives any time within a_1 minutes

      boat 2 arrives any time within a_2 minutes

      ...

      boat N arrives any time within a_N minutes (uniform distribution)

      Tell discord the expected number of minutes he needs to wait for a boat to arrive.

      For some reason, you should be accurate to 10^-6 of a minute.

      Input Format:

      T (number of test cases)

      N1 (number of boats for test case 1)

      a1 a2 ... aN

      N2

      ...

      NT

      ...

      Output Format:

      answer1

      answer2

      ...

      answerT

      Limits:

      1 <= T <= 100

      1 <= N <= 100

      1 <= ai <= 1000

      Also, N * max{ai} <= 10000

      Sample Input:
      4
      1
      5
      3
      49 50 51
      3
      50 50 50
      3
      2 7 19
      
      Sample Output:
      
      2.500000
      12.495000
      12.500000
      0.874687
      (Fixed thanks to )
      
      Note: Round however Java would round if you used the statement System.out.printf("%.6f\n", answer);
      Added by:Alex Anderson
      Date:2012-03-12
      Time limit:1s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11063. AP - Complete The Series (Easy)

      Problem code: AP2

      Arithmatic and geometric Progressions are 2 of the well known progressions in maths.

      Arithmatic progression(AP) is a set in which the difference between 2 numbers in constant. for eg, 1,3,5,7,9 .... In this series the difference between 2 numbers is 2.

       

      The task here is very simple indeed.

      You will be given the 3rd term , 3rd last term and the sum of the series. You need print length of the series & the series.

      Input

      First line will contain a number indicating the number of test cases.

      Each of the following t lines will have 3 number '3term' ,'3Lastterm' and 'sum'

      3term  - is the 3rd term in of the series and

      3Lastterm  - is the 3rd term in of the series and

      sum - is the sum of the series.

      Output

      For each input of the test case, you need to print 2 lines.

      fist line should have 1 value- number of terms in the series.

      2nd line of the output should print the series numbers separated by single space.

      Example

      Input:
      
      1
      3 8 55
      Output:
      10
      1 2 3 4 5 6 7 8 9 10
      NOTE - In all the test cases all the series elements are positive integers.
      The series will have at least 7 elements.
      number of test cases <=100.
      All the numbers will fit in 64 bits(long long in C)

      Added by:Devil D
      Date:2012-03-13
      Time limit:0.100s-0.150s
      Source limit:1500B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      11066. AP - Complete The Series v2

      Problem code: AP3

      After solving "AP - Complete The Series (easy)" very fast, Lucifer decided to make it little more interesting.

      He said

      He will be give you the 3rd term , 4th last term and the sum of the AP series. You need print length of the series & the series.

      Input

      First line will contain a number indicating the number of test cases.

      Each of the following t lines will have 3 number '3term' ,'4Lastterm' and 'sum'

      3term  - is the 3rd term in of the series and

      4Lastterm  - is the 4th term in of the series and

      sum - is the sum of the series.

      Output

      For each input of the test case, you need to print 2 lines.

      fist line should have 1 value- number of terms in the series.

      2nd line of the output should print the series numbers separated by single space.

       

      Example

       

      Input:
      
      1
      3 7 55


      Output:

      10
      1 2 3 4 5 6 7 8 9 10

      NOTE
      - In all the test cases all the series elements are positive integers.
      The series will have at least 7 elements.
      number of test cases <=100.
      All the numbers will fit in 64 bits(long long in C)

      Added by:Devil D
      Date:2012-03-13
      Time limit:0.5s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      11090. Large banner

      Problem code: BANNER


      Bessie is returning from a long trip abroad to the Isle of Guernsey, and Farmer John wants to mount a nice "Welcome Home" banner for her arrival. Farmer John's field has integer dimensions M x N (1 <= M, N <= 100,000), and he has installed a post at every possible point in the field with integer coordinates (if we assign a coordinate system to the field so that (0,0) is in the lower-left corner and (M,N) is in the upper-right corner). Of these (M+1) * (N+1) points, Farmer John must pick two as the endpoints of the banner.

      Farmer John, being the perfectionist that he is, insists that the banner must be completely straight. This means that, for the two posts he chooses, there cannot be any other post on the line segment that the banner will form between them. Additionally, Farmer John wants the banner to have length at least L and at most H (1 <= L <= H <= 150,000). Farmer John needs your help to figure out how many possible ways he can hang the banner. The banner is reversible, so switching the two endpoints of the banner counts as the same way to hang the banner. As this number may be very large, Farmer John simply wants to know what it is modulo B (1 <= B <= 1,000,000,000).

      Consider the example below, with M = 2 and N = 2:

      * * *

      * * *

      * * *

      Farmer John wants the length of the banner to be between 1 and 3 inclusive. Any choice of posts satisfies this length requirement, but note that eight pairs cannot be picked:

      (0, 0) and (2, 0): (1, 0) is on the line segment between them (0, 1) and (2, 1): (1, 1) is on the line segment between them (0, 2) and (2, 2): (1, 2) is on the line segment between them (0, 0) and (2, 2): (1, 1) is on the line segment between them (0, 0) and (0, 2): (0, 1) is on the line segment between them (1, 0) and (1, 2): (1, 1) is on the line segment between them (2, 0) and (2, 2): (2, 1) is on the line segment between them (0, 2) and (2, 0): (1, 1) is on the line segment between them

      Therefore, there are a total of (9 choose 2) - 8 = 28 possible locations.


      Input

      * Line 1: Five space-separated integers: M, N, L, H and B.

      Output

      * Line 1: One integer denoting the number of possible banners (modulo B).

      Example

      Input:
      2 2 1 3 100
      
      Output:
      28

      Added by:Ikhaduri
      Date:2012-03-14
      Time limit:1s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Usaco MAR12









      SPOJ Problem Set (classical)

      11102. SelfDescribingSequenceProblem

      Problem code: MAIN12A

      Everyone loves Swampy. Swampy the Alligator lives under the city and yearns for a more human like existence. Swampy recently learned a new self describing sequence. The sequence is described in blocks where each block has the same number and two consecutive blocks have consecutive numbers in them. To construct the sequence start with '1'. Now '1' means that the following block is of length 1. As '1' was chosen in previous block, therefore '2' is chosen for the current block making the sequence '12'. Now '2' means that the following block is of length 2. As '2' was chosen in previous block, therefore '3' is chosen for the current block making the sequence '1233'. Now '33' means that the following 2 blocks are of length 3. As '3' was chosen in previous block, therefore '4' is chosen for the current block making the sequence '1233444'. And the second '3' in the sequence appends '555' in the already generated sequence, making the sequence '1233444555'.

      Input

      First line of the input contains an integer T, the number of test cases. Then T test cases follow. Each test case consists of a single integer N.

      Output

      For each test case, print Case #X: S, where X is the test case number starting from 1, S is the Nth term of the sequence described above.

      Example

      Input:
      4
      1
      2
      3
      4
      
      Output:
      Case #1: 1
      Case #2: 2
      Case #3: 3
      Case #4: 3
      

      Constraints: T <= 10000 1 <= N <= 1000000


      Added by:Nikunj Jain
      Date:2012-03-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Vaibhav Mittal









      SPOJ Problem Set (classical)

      11103. PrimeFactorofLCM

      Problem code: MAIN12B

      Everyone loves Swampy. Swampy the Alligator lives under the city and yearns for a more human like existence. One day Swampy took part in a maths contest to show his supremacy over other his other alligator friends. The task required him to output the prime divisors of the lcm of n numbers a1,a2,..,an. Tired trying the problem, he turned to you for help. He believes that you can help him solve the problem.

      Input

      First line of the input contains an integer T, the number of test cases. Then T test cases follow. Each test case consists of a single integer n. Next line contains n integers(space separated), a1,a2,..,an.

      Output

      For each test case, print Case #X: M where M is the number of prime divisors of lcm(a1,a2,..,an) and then M lines with the prime divisors in non-decreasing order.

      Example

      Input:
      1
      8
      1 2 3 4 5 6 7 8
      
      Output:
      Case #1: 4
      2
      3
      5
      7

      Constraints: T <= 100 1 <= N <= 100 1 <= ai <= 10^12


      Added by:Nikunj Jain
      Date:2012-03-15
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Vaibhav Mittal









      SPOJ Problem Set (classical)

      11105. Email ID

      Problem code: MAIN12C

      Everyone loves Swampy. Swampy the Alligator lives under the city and yearns for a more human like existence. One day Swampy thought to learn the intricacies of the internet. He went to a book store in SwampVille immediately and bought a book on "Basic Internet". After reading the book Swampy decided to try on some exercises. The exercise demanded Swampy to report all valid email-id's in a given free-form text string. Check output section for exact specification. Swampy lacks the intelligence of humans and therefore needs you to help him in this job. The chapter defined email-id's as a string consisting of two parts. From left to right, these are username and site-address. The username is non-empty string of minimum length 5 build from characters {a-z A-Z 0-9 . _} (excluding the brackets). The username cannot start from '.' or '_' The site-address is build of a prefix which is non-empty string build from characters {a-z A-Z 0-9} (excluding the brackets) followed by one of the following suffixes {".com", ".org", "edu", ".co.in"}. There is no space character in the email-id. The entire email-id is "username@site-address".

      Input

      First line of the input contains an integer T, the number of test cases. Then T test cases follow. Each test case consists of String S on a single line. S is made up of characters {a-z A-Z 0-9 ~!@#$%^&*()<>?,.} (excluding the brackets) and space character too.

      Output

      For each test case, print Case #X: K, where X is the test case number starting from 1, K is the number of email-id's found in S, and then K lines with email-id's found in S.

      Example

      Input:
      2
      svm11@gmail.com
      svm11@gmail.com svm12@gmail.co.in
      
      Output:
      Case #1: 1
      svm11@gmail.com
      Case #2: 2
      svm11@gmail.com
      svm12@gmail.co.in
      

      Constraints: T <= 100 |S| <= 10000


      Added by:Nikunj Jain
      Date:2012-03-15
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Vaibhav Mittal









      SPOJ Problem Set (classical)

      11116. Discord is Cornered

      Problem code: PONY4

      The ponies have finally cornered Discord. His earlier escape attempts didn't help him much.

      The unicorn ponies have begun casting magic spells at Discord to turn him back into stone. There are N ponies and pony I has a casting rate A_I. That is, once pony I began casting her magic spell, it would send a bolt of magic at Discord every A_I seconds, precisely.

      At time t = 0 seconds, all the ponies began casting their magic. It has now been M seconds since they began casting.

      Discord is wearing down. He only can survive being hit by K-1 more spells before being turned into stone (so the Kth spell will turn him to stone).

      Determine which pony has the honor of casting the final blow against Discord.

      Notes: If multiple ponies send a bolt of magic at the same time, then they hit in order of the smaller rate first.

      All the ponies are casting different spells, so all the casting rates are distinct.

      If some ponies cast a bolt of magic after exactly M seconds, that bolt has already hit Discord. He can survive an additional K-1 spells.

      Input

      The input file will begin with a number T on the first line, indicating the number of test cases in the file. It is followed by 2T lines, which represent the T test cases. Test case i begins with the label "Case #i: " and is followed by space separated N, M, and K for that case. On the next line are N space separated integers representing the rates of pony0, pony1, ..., ponyN-1.

      T //number of test cases
      Case #1: N M K//number of ponies, number of seconds since they began casting, the spell which will turn him to stone
      A_0 A_1 ... A_N-1
      ... (etc.)
      

      Output

      The output contains T lines, one for each test case. For test case i, begin the line with the label "Case #i: ", and then the index of the pony which has dealt the final blow against Discord.

      Case #1: C_1 //C_1 is the pony which casts the final blow against Discord
      Case #2: C_2
      ...
      Case #T: C_T 

      Limits

      Limits:
      Number of Test cases varies.  Depends on the instance size.
      1 <= N <= 5000
      0 <= M <= 10^18 - 1
      1 <= K < 2^63 - 1
      1 <= A_I <= 10^18
      

      Example

      Input:
      5
      Case #1: 2 0 4
      2 3
      Case #2: 2 0 5
      2 3
      Case #3: 3 7 4
      2 3 5
      Case #4: 4 55 88
      10000 55 3 16
      Case #5: 4 9950 23
      10000 55 3 16
      
      Output:
      Case #1: 0
      Case #2: 1
      Case #3: 2
      Case #4: 2
      Case #5: 0
      

      You can be assured that it will not take more than 10^18 seconds to turn Discord into stone from when the ponies began casting.


      Added by:Alex Anderson
      Date:2012-03-18
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11117. Restacking haybales 2012

      Problem code: RESTACK

      Farmer John has just ordered a large number of bales of hay. He would like
      to organize these into N piles (1 <= N <= 100,000) arranged in a circle,
      where pile i contains B_i bales of hay. Unfortunately, the truck driver
      delivering the hay was not listening carefully when Farmer John provided
      this information, and only remembered to leave the hay in N piles arranged
      in a circle. After delivery, Farmer John notes that pile i contains A_i
      bales of hay. Of course, the A_i's and the B_i's have the same sum.

      Farmer John would like to move the bales of hay from their current
      configuration (described by the A_i's) into his desired target
      configuration (described by the B_i's). It takes him x units of work to
      move one hay bale from one pile to a pile that is x steps away around the
      circle. Please help him compute the minimum amount of work he will need to
      spend.

      Input

      * Line 1: The single integer N.

      * Lines 2..1+N: Line i+1 contains the two integers A_i and B_i (1 <=
      A_i, B_i <= 1000).

      Example:

      4
      7 1
      3 4
      9 2
      1 13

      OUTPUT:

      A single line containing one number,answer to the problem.

      Example:

      13


      Added by:Ikhaduri
      Date:2012-03-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:USACO MAR12









      SPOJ Problem Set (classical)

      11157. The Great Escape

      Problem code: GREAT_E

      Primo is a famous guitar player in the city of Caracas, he wants to live his life at the fullest, so he went to the nearest food store to buy an arepa, a famous dish of all South America.

      While eating his arepa, Primo received a call from his friend Maxx, who was piloting his helicopter when he soon noticed that a lot of fans were around the streets, pursuing and looking for Primo.

      Primo is starting to go crazy, he wants to eat his arepa as many time he can before the fans takes him... He is not interested in the fans because he already has a girlfriend!

       

      So, your task is very simple, Maxx (in his helicopter) will give you the connection between the streets, the time you can spend from street to street, and the amount of time the street has left before the fans takes it.

      If some fans “take” a street, that street will be discarded, Primo won't go there... NOT EVEN DEAD!

       

      Primo really likes arepas, so help him find the maximum time he can spend eating the food before the fans can reach him...

       

      INPUT:

      Input will start with a number T of test cases, then, T cases will follow:

      Each test case will start with 3 numbers N,R,M, corresponding, to number of intersections, number of streets and maximum time he can eat the arepa

      Then, R lines will follow.

      Each line will contain 3 numbers and a string Ri,Rj,Wij,Tij, corresponding to, Intersection I is connected to intersection J, with a length of Wij minutes and the fans will arrive to the street in Tij minutes (or may not arrive, in this case, Tij will be equal to INF)

      The final line of each test case will contain two numbers S,E corresponding to the starting intersection Primo is in (the food store) and the E will correspond to his house.

       

      Note that: if the fans won't arrive to the street the Tij of the street will be INF

      Also note that: You can go from the i-th intersection to the j-th intersection as you can go from the j-th intersection to the i-th intersection

       

      OUTPUT:

      Your output will start with a “Case #i: “ string, where I is the i-th case you are on.

      If Primo can escape, you should output “Primo can escape in T minute(s)” where T Is the maximum amount of time he can spend eating his arepa, else, you should print “Primo can't escape”

       

      Sample input:

      4

      3 2 100

      0 1 30 40

      1 2 10 40

      0 2

      3 2 100

      0 1 30 INF

      1 2 10 INF

      0 2

      4 3 100

      0 1 20 INF

      1 2 40 INF

      2 3 50 120

      0 3

      2 1 100

      0 1 1 2

      0 1

       

      Sample Output:

      Case #1: Primo can't escape

      Case #2: Primo can escape in 100 minute(s)

      Case #3: Primo can escape in 9 minute(s)

      Case #4: Primo can't escape

       

      CONSTRAINTS:

       

      1<=N<=100,000

      1<=R<=100,000

      1<=M<=100,000

      1<=R1,R2<N

      1<=Tij,Wij<=500

       

      Clarification: It is guaranteed that every intersection will be connected to at least one other intersection, there will be no equal relation on the input data and Primo will always reach his house.


      Added by:David Moran
      Date:2012-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11165. Magic Strawberries

      Problem code: STRAWB

      Andreina the Hobbit was walking in a big yard when he saw a huge path of strawberries, Andreina ran, looking where to found her friend, Teresa (Everybody knows that Teresa LOVES strawberries), Teresa then looked the giant path of strawberries, having some amount of strawberries in a single meter, but she soon noticed that in the end of the path there was a HUGE pot of strawberries, full of this delicious fruit, Teresa, grabbed the first strawberry, but she was sent some amount of spaces ahead! However, she grabbed another strawberry and she was sent out of the range of the pot.

       

      She was a little confused, but, the Hobbit noticed that she was sent exactly Ai meters, the same exact amount of strawberries that were on the floor.

       

      Now, Teresa likes a lot this fruits and wants to reach the pot, however, she doesn't want to repeat the experience of magically sent out away from the pot! Teresa won't leave any fruits in a single square if she decides to grab it.

       

      Andreina the Hobbit called you, and you, the only programmer in Rainbowland must solve the problem... Andreina will give you the amount of meters to reach the pot and the number of strawberry meters that Teresa wants to pick as maximum (she has a little trauma as she was sent out of the pot range). Andreina then explains you:

       

      “Teresa can grab all the strawberries in a single square, but, if she does so, she will be transported “Ai” meters ahead, being Ai the number of strawberries she grabbed. Else, Teresa will decide to skip the strawberry meter, she doesn't like this, so, give me the minimum strawberry meters Teresa should skip.”

       

      INPUT:

      The input will consists on T test cases, then, 3 lines will follow, the first line contains two numbers N and K, being N the number of meters and being K the maximum numbers of strawberries Teresa wants to pick, in the next line there will be N integers, giving the number of strawberries in each tile, the last number (Nn) will always be a 0, this represents the pot Teresa wants to go. Finally, the third line is a blank line.

       

      OUTPUT:

      The output starts with “Scenario #i:” where “i” is the test case of evaluation starting by 1, in the next line, you should output “Teresa will skip N strawberries” where N is the minimum number of strawberries Teresa will skip, if Teresa should skip all the strawberries, you should output “Teresa will skip all the strawberries”

       

      Sample Input:

      3

      7 2

      1 1 1 1 1 1 0

       

      7 2

      3 2 1 3 2 1 0

       

      7 1

      7 6 5 4 3 2 0

       

      Sample Output:

      Scenario #1:

      Teresa will skip 4 strawberries

      Scenario #2:

      Teresa will skip 0 strawberries

      Scenario #3:

      Teresa will skip all the strawberries

       

      Explanation of the second sample test:

      Teresa takes the first strawberry at the 1st tile, moves 3 tiles to the right (4th tile), then she grabs the strawberry (3) and moves 3 more tiles, arriving then to the tile 7 where is the pot.

       

      CONSTRAINTS:

      2<=N<=1000

      0<=K<=N

      1<=Ni<=N


      Added by:David Moran
      Date:2012-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11175. The Ball Game

      Problem code: IEEEBGAM

      Taru and Hanaku play a ball game. The game is played with N white balls, N black balls and N boxes. Hanaku chooses one box randomly and one ball from it randomly. Taru has to arrange the balls in such a way that the probability of Hanaku choosing a White ball is maximised. None of the boxes after the arrangement should be empty. Your task is to find that maximum probability.

      Input

      The first line contains the number of test cases (T) followed by T lines each an integer N.

      Output

      For each test case output the maximum probability of getting a white ball which is possible with an arrangement for the above configuration. Print answer to 8 decimal places.

      Constraints

      T<=20

      N<=1000

      Sample Input

      1

      1

      Sample Output

      0.50000000


      Added by:Saransh Bansal
      Date:2012-03-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11178. Save money for YTU

      Problem code: MONEYYTU

      It is Taru’s dream to study in Yanyang Technological University and Taru must start saving money in order to ensure that he has sufficient funds to take admission. Taru needs to have X amount of dollars at the end of T months. Taru deposits his money in a bank that pays a monthly interest of R% on the balance in his account. But wait, Taru is very superstitious; he deposits money in his account only if the balance in the account is a multiple of 100. If the balance in the account at the beginning of a month is not a multiple of 100 Taru withdraws the minimum offset to make the balance divisible by 100 and donates it to a charitable trust. Example – If in the beginning of the month Taru has $17823 in his account he will donate $23 and make the balance divisible by 100. You are to calculate the minimum monthly installment which Taru should deposit in the bank in order to get the funds required.

      Input

      The first line contains the number of test cases (Test) followed by Test lines each containing 3 integers, X, T, R.

      Output

      For each test case output the minimum monthly installment Taru deposits in the bank in order to generate the required funds. Print the answer rounded to 4 decimal places.

      Constraints Test<=20, X<=10^6, T<=60, R<=10.

      Sample Input

      2

      50000 3 5

      20000 5 6

      Sample Output

      15142.8571

      3386.7925

       


      Added by:Saransh Bansal
      Date:2012-03-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11179. Korra in the Spirit World

      Problem code: SPWORLD



      Avatar Korra is trapped in the spirit world and she summons Avatar Aang for help. Avatar Aang who wants to help Avatar Korra first wants to know whether she is intelligent enough to win the ancient game of co-prime Polygons. Two polygons are said to be co-prime if the number of their sides is co-prime. Examples - A 3-sided polygon and a 4-sided polygon are co-prime whereas a 4 sided polygon and a 6 sided polygon are not. The game begins with N polygons. The game has the following rules-

      1. A player takes any one polygon cuts them into two co-prime polygons. Cutting is done along a line joining 2 vertices of a polygon (points cannot be adjacent). These 2 new co-prime polygons now become a part of the game. If he/she is not able to perform such a cut on any of polygons he/she loses.
      2. Avatar Aang takes the first turn. After each cut it is the turn of the other person. In a turn a person can make only one cut.
      3. Though Aang thinks Korra is not intelligent he is forgetting that she has the wisdom of all the Avatars, even him. So she knows the game. Hence both of them play optimally.

      Input

      The first line contains the number of test cases (T) followed by T lines each containing a test case. A test case begins with the number N. N integers follow denoting the number of sides in the N polygons. Every polygon will has at least 3 sides.

      Output

      For each test case output the winner of the game.

      Constraints T<=15, N<=7, 3<=sides of polygon<=1000

      Sample Input

      2

      3 5 6 7

      2 6 7

      Sample Output

      Aang

      Korra


      Added by:Saransh Bansal
      Date:2012-03-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11180. 369 Numbers

      Problem code: NUMTSN

      7. 369 numbers

      A number is said to be a 369 number if

      1. The count of 3s is equal to count of 6s and the count of 6s is equal to count of 9s.
      2. The count of 3s is at least 1.

      For Example 12369, 383676989, 396 all are 369 numbers whereas 213, 342143, 111 are not.

      Given A and B find how many 369 numbers are there in the interval [A, B]. Print the answer modulo 1000000007.

      Input

      The first line contains the number of test cases (T) followed by T lines each containing 2 integers A and B.

      Output

      For each test case output the number of 369 numbers between A and B inclusive.

      Constraints

      T<=100

      1<=A<=B<=10^50

      Sample Input

      3

      121 4325

      432 4356

      4234 4325667

      Sample Output

      60

      58

      207159

       


      Added by:Saransh Bansal
      Date:2012-03-21
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11181. Build the Tower

      Problem code: BUILDTOW

      8. Build the Tower

      The president of Yanyang University has decided to build a new tower in front of the auditorium and has invited the students of SCE to help with the project. The tower is one of a kind and is made up of N cuboids one over the other. Each cuboid has a height of 1 unit and the length and breadth of a cuboid is equal. The top most cuboid’s length is 1 unit. The cuboid below it has a length of 2. All the cuboids below it have their lengths equal to the sum of the lengths of the 2 cuboids above it.

      Cuboid

      Length

      Breadth

      Height

      1

      1

      1

      1

      2

      2

      2

      1

      3

      3

      3

      1

      4

      5

      5

      1

      5

      8

      8

      1

       

      As a token of appreciation the president has decided to give SCE a grant of

      $ ((Volume of Tower) % 1000000007)

      Your task is to calculate the amount of grant received by SCE for a given value of N.

      Input

      The first line contains the number of test cases (T) followed by T lines each containing a single integer N.

      Output

      For each test case output the grant that SCE receives for building the tower.

      Constraints T<=20, N<=10^18

      Sample Input

      2

      5

      10

      Sample Output

      $103

      $12815


      Added by:Saransh Bansal
      Date:2012-03-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11198. Ipad Testing

      Problem code: IPAD

      Apple recently released "the new Ipad" with several advance features. But the device was jailbroken within a week of its launch.  After learning the technique to jailbreak "the new Ipad", one of the enthusiast, Donncha O'Cearbhaill successfully installed different programming language compilers available from the cydia store on the device. Now O'Cearbhaill wants his friends to test these compilers. Being a good computer science student, he decided to use instead of traditional 'hello world' program, a new programming puzzle to test the compilers on the jailbroken devices :

      For any α, β >= 0, how many positive integers are there which can't be expressed as αλ + βμ where gcd(λ,μ) = 1 and λ,μ > 1. Also find the maximum of all such possible integers. ( α, β, λ, μ are all integers )

      O'Cearbhaill knew that neither the cydia store nor the app store has a decent text editor suitable for all programming languages, so he only accept programs less than equals to 100 characters in length.

      Input

      First line consist of T ( <= 1000 ). Next T lines has two integers λ and μ such that gcd(λ,μ) = 1 and  1<λ,μ<10^8.

      Output

      For each test case output the two required values separated by a single space in a single line.

      Example

      Input:
      2
      2 3
      3 4

      Output: 1 1
      3 5

      Added by:XeRoN!X
      Date:2012-03-22
      Time limit:1s
      Source limit:100B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11202. Number Theory

      Problem code: NUMTRY


      f(n) and g(n) are two functions defined as following :

      f(n) = ( pi2ei+1+1 ), where pi is prime factor of n and ei is highest power of pi in n.

      g(n) = Σ( n/gcd(n,i) ); 1 <= i  <= n

      For a given value of n, you have to compute [f(n)/g(n)] % 1000000007.

      Input

      First line has T ( <= 10000 ), next T lines has 2 <= n <= 10^12.

      Output

      [f(n)/g(n)] % 1000000007 for each test case.

      Example

      Input:
      2
      2
      4 Output:
      3
      3

      Warning: Test cases aren't random. Test files consist of large primes, strong pseudo primes, Carmichael numbers, squares of primes, product of large primes, worst possible test cases for fermat, miller rabin and other primality testing algorithms.

      Note: You may try the tutorial version ( same test files, 5s-100s time limit ). 

       


      Added by:XeRoN!X
      Date:2012-03-23
      Time limit:0.100s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Number Theory









      SPOJ Problem Set (classical)

      11244. GP - Complete the Series v1 ()

      Problem code: GP1


      Geometric progression(GP) is a set in which the ratio of 2 consecutive numbers is same. for eg, 1,2,4,8,16.... In this the ratio of the numbers is 2.

      The task here is very simple indeed.

      You will be given the 3rd term , 3rd last term and the sum of the series. You need print length of the series & the series.

      Input

      First line will contain a number indicating the number of test cases.

      Each of the following t lines will have 3 number '3term' ,'3Lastterm' and 'sum'

      3term  - is the 3rd term in of the series and

      3Lastterm  - is the 3rd term in of the series and

      sum - is the sum of the series.

      Output

      For each input of the test case, you need to print 2 lines.

      fist line should have 1 value- number of terms in the series.

      2nd line of the output should print the series numbers separated by single space

      Example

      Input:
      
      1
      4 64 511

       Output:
      9
      1 2 4 8 16 32 64 128 256


      NOTE
      -
      All the values will be in the range [0, 2^64] inclusive
      The series will have at least 6 elements.
      number of test cases <=100.
      The Ratio in all the cases will be an integer. (Thanks Mitch for pointing this out)
      All the numbers will fit in 64 bits(long long in C)

      Added by:Devil D
      Date:2012-03-26
      Time limit:1s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (acm)

      11267. Arnook Defensive Line

      Problem code: KL11B

      Based on the latest intelligence reports, Chief Arnook of the northern tribe has become suspicious of the warrior nations that dwell south of the border. The chief has ordered his warriors to protect the southern border which runs parallel to the 54o latitude line and stretches between the longitudes of 1o to 1000,000,000o, inclusive.

      Each warrior is assigned the task of protecting a segment of the border defined to lie between longitudes “a” and “b”, inclusive. No two warriors are assigned to protect the exact same segment. Bound by loyalty to his chief, a warrior will inform the chief upon his arrival at his appointed post and will never leave once he arrives. 

      Your task is to write a program that performs the following two operations to help Chief Arnook track the status of his border protection.    

       

      + a b

      a warrior assumes his position and protects the segment between longitudes “a” and “b”, inclusive.

       

      ? c d        

      computes the number of warriors who completely protect the segment between longitudes “c” and “d”, inclusive. The segment between the longitudes “c” and “d”, inclusive, is said to be completely protected by a warrior X if and only if warrior X protects a segment between

      “a” and “b”, inclusive, and a ≤ c ≤ d ≤ b.


       

      Input

      The input starts with an integer N (1 ≤ N ≤ 500000), on a line by itself, that indicates the number of operations. Each of the following N lines contains one operation. The description of an operation consists of a character “+” or “?” followed by two integers on a line by itself. The entries on a line are separated by single blank spaces. 


      Output

      There is one output line for each input line that starts with the operation “?”. The output consists of a single integer that represents the number of warriors who completely protect the corresponding segment at the time. 

      There is no output for input lines that start with the character “+”.    

      Example

      Input:
      9
      + 5 10
      + 7 20
      + 3 15
      ? 9 12
      + 10 20
      ? 8 9
      + 6 30
      ? 8 9
      ? 9 12
      
      Output:
      2
      3
      4
      3

      Added by:Race with time
      Date:2012-03-30
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC Kuala Lumpur 2011









      SPOJ Problem Set (classical)

      11273. Team Nim

      Problem code: TEAMNIM


      Elayne and Nynaeve have teamed up against Aviendha and Birgitte to play a game of Nim. There are 3 piles of coins with X, Y and Z coins initially. In each turn the current player selects any non-empty pile, and removes any non-zero number of coins from that heap. Then play passes to the next player. The team whose player cannot make any valid move, loses, and the other team wins the game. Assume that all the players play optimally. Find out which team wins the game.

      Input:
      The first line contains T, the number of test cases. T test cases follow.
      The first line of each test case contains 3 integers X,Y,Z.
      This is followed by 4 lines containing the names "Elayne", "Nynaeve", "Aviendha", "Birgitte" (without quotes) in some order. This denotes the order of play. The player listed first gets the first turn, the next listed player gets the next turn and so on. After the player listed fourth, turn comes back to the player listed first and play continues.


      Output:
      Output T lines, each containing the winner's description for the corresponding test case.
      Output "Elayne/Nynaeve" (without quotes) if Elayne and Nynaeve's team wins.
      Output "Aviendha/Birgitte" (without quotes) if Aviendha and Birgitte's team wins.


      Constraints:
      T <= 50000
      1 <= X,Y,Z <= 1000000000

      Sample Input:
      3
      1 1 1
      Elayne
      Nynaeve
      Aviendha
      Birgitte
      2 2 1
      Aviendha
      Elayne
      Birgitte
      Nynaeve
      3 1 3
      Elayne
      Nynaeve
      Birgitte
      Aviendha

      Sample Output:

      Elayne/Nynaeve
      Aviendha/Birgitte
      Elayne/Nynaeve


      Explanation:
      In the first test case, the players do not really have any choice. Elayne, Nynaeve and Aviendha empty one pile each on their turn, and Birgitte cannot make any valid move after that.
      In the second test case, Aviendha should empty the third pile of 1 coin. Now if Elayne takes 2 coins from a pile, Birgitte takes 2 coins from the other pile, leaving Nynaeve with no move. Or if Elayne takes 1 coin from a pile, Birgitte takes 1 coin from the other pile, and play will continue to leave Elayne with no move on her next turn.
      In the third test case, Elayne and Nynaeve should each take 3 coins and empty a pile. Birgitte is forced to take the last coin leaving Aviendha with no move.


      Added by:Rudradev Basak
      Date:2012-03-30
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem, used for ACM Indo-Pak Contest









      SPOJ Problem Set (classical)

      11274. Lights and Switches

      Problem code: LIGHTPZ


      On his birthday, Perrin received a very unusual puzzle. It consists of an NxN grid of lightbulbs, all of them initially at the off state. The goal is to turn on some of the lights, such that there is exactly one lit bulb in each row, and exactly one lit bulb in each column. Normally this would be an easy exercise, but this puzzle has an additional constraint. For each lightbulb, there is exactly one critical moment of time that the lightbulb can be switched on. As Perrin is a busy man, he does not want to spend a lot of time on the puzzle. Help Perrin calculate the minimum time taken to achieve the goal. Note that the time taken to solve the puzzle is defined as the time difference between the first and the last switching on events.

      Input

      The first line contains T, the number of test cases. T test cases follow.
      The first line of each test case contains a single integer N. N lines follow each containing N integers. The j th integer in the i th of these lines represent the critical time for the bulb in row i, column j.
      For any two lightbulbs, the critical times will be different

      Output

      Output T lines, each with one integer as the answer for the corresponding test case.

      Constraints

      T <= 100
      1 <= N <= 50
      0 <= critical times <= 1000000000

      Example

      Input:
      2
      2
      3 6
      9 8
      4
      10 41 38 66
      91 13 95 70
      49 32 43 52
      51 98 36 19 Output: 3
      29

      Explanation:

      In the first test case, one can either turn on bulbs at times 3 and 8, or at times 6 and 9.Time taken to solve is 5 for the first option and 3 for the second. So the answer is 3.

      In the second test case, one optimal way is to turn on lights at times 41,43,51,70.


      Added by:Rudradev Basak
      Date:2012-03-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem, used for ACM Indo-Pak Contest









      SPOJ Problem Set (classical)

      11276. Adventure

      Problem code: ADVNTURE

      Rand has been sitting in a spaceship at the point (0,0,0) for a long time. One day, he got bored and decided to undertake an adventure.

      Deciding upon an adventure has several complicated steps. First, Rand chooses a destination point (x,y,z) different from (0,0,0) such that 0<=x<=A, 0<=y<=B, 0<=z<=C. To go to this point, Rand travels in a straight line from the origin. As a result, he might encounter several other lattice points in the way. Each part of the journey between two consecutive lattice points encountered is called a phase.( For example if (x,y,z)=(1,2,3) then there is only one phase (0,0,0)->(1,2,3), while if (x,y,z)=(3,0,3) then there are 3 phases (0,0,0)->(1,0,1)->(2,0,2)->(3,0,3) ).

      In each phase Rand chooses one of K different activities that he can undertake to pass the time. You need to calculate the total number of different adventures possible, modulo 1000000007 (1e9+7). Two adventures are considered different if they have different destination points, or if the activity undertaken during any of the corresponding phases is different.

      Input

      The first line contains the number T, the number of test cases.
      T lines follow, each contains the integers A,B,C,K, corresponding to one testcase

      Output

      Output T lines, each with one integer as the answer for the corresponding test case.

      Constraints

      T <= 1000
      0 <= A,B,C <= 50000
      1 <= K <= 10

      Example

      Input:
      3
      0 0 5 2
      0 2 2 5
      4 4 4 9 Output: 62
      100
      53388

      Explanation

      In the first test case, if Rand chooses (0,0,1) as destination point, then there are 2 possible adventures. Similarly for (0,0,2), (0,0,3), (0,0,4) and (0,0,5), the number of adventures corresponding to each are 4,8,16,32 respectively. The total number of adventures is 2+4+8+16+32=62.

      In the second test case, for points (0,0,2), (0,2,0) and (0,2,2) there are 25 adventures each, while for the rest of the 5 valid points, there are 5 adventures each. So total is 100.


      Added by:Rudradev Basak
      Date:2012-03-30
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem, used for ACM Indo-Pak Contest









      SPOJ Problem Set (classical)

      11300. Fun with numbers

      Problem code: NUMPLAY

      consider a set of 4 numbers {1,3,5,7} .. Form a number using these digits in the set under the following constraints ,1 can be followed only by 3((i.e) the number may contain 13 but not 15 or 17 or 11 eg:13573 is valid but not 113573), 3 can be followed only by 1 and 5, 5 can be followed only by 7 ,7 can be followed only by 5 and 3

      Find the number of such numbers of length n

      eg:

      37,51,53,71 are all not a valid number of length2 ,131 is a valid number of length 3,1357,1313 are all a valid number of length 4 but 11 or 1537 or15 or 17 or 33 is not a valid number..

      Input

      t, First line of input contains number of test cases 0<=t<=40

      remaining t lines consist of length n for each test case 0<=n<=10000

       

       

      Output

      Output the number of possible numbers of length n followed by a line(note long long int  in c++ may not be sufficient)

      Example

      Input:
      3
      2
      1
      4
      
      Output:
      6
      4
      13
      Note : time limit is reduced for checking the accuracy

      Added by:B.R.ARVIND
      Date:2012-04-03
      Time limit:1s-1.5s
      Source limit:30000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      11321. G-One Sort

      Problem code: GONESORT


      After Killing RaOne G-One had nothing to do. HE started reading books and became a avid book reader.

      To avoid purchasing books and he started working in a library.

      Every evening he had to arrange the books in the shelf in increasing order of their serial number.

      every book in a the library is is numbered .

      ..

      G-One found a ingenious way of arranging the books.  He can remove any book from the shelf and put it either at the beginning or at the end of the shelf..

      For example if the books are arranged in the order below

      2 3 1 7 4 5 6

      he can make it sorted by removing '1' and placing it at the beginning and then removing '7' and placing it in the end.

       

      Since the book shelf can be very big and can have large number of books He needs your help to tell him the minimum remove and place operations he needs to do.

       

      Can you help him ?

       

      Input

      1st line of the input contains number 't' denoting the number of shelves in the library. 2*t lines follow this

      1st line of each test case will have single number 'b' - denoting number of books on the shelf.

      2nd line wil contain b numbers. each bi denoting the serial number of the book.

       

      Output

      For each test case ouput single number 'res' - denoting the minimum remove and place operations needed to arrange the shelf.

      Example

      Input:
      3
      7
      2 3 1 7 4 5 6
      5
      1 2 3 4 5
      6
      6 5 4 3 2 1

       Output:
      2
      0
      5

      NOTE -
      All the values will be in the range [0, 10^7]
      number of test cases <=100.

      Added by:Devil D
      Date:2012-04-05
      Time limit:0.5s-1s
      Source limit:20000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      11326. Arithmetic Evaluation

      Problem code: ARTHEVAL

      Evaluate a parenthesized expression of single-digit positive integers and the binary operators +, -, *.

      The order of operations differs from the canonical one in that operations have no precedence; they are simply evaluated from left-to-right, with only parentheses affecting the order of evaluation.

      Every intermediate step is guaranteed to have absolute value no greater than 1,000,000,000.

      Input:

      Input is an arithmetic expression of single-digit positive integers, the binary operators +,-, * and parentheses (). The arithmetic expression will be well-formed and will have no spaces.

      Output:

      The evaluated value of the arithmetic expression.

      Example Input 1: Example Input 2: Example Input 3:
      1*2+1
      
      1+1*2
      
      (5*6)-(40+(1))
      
      Example Output 1: Example Output 2: Example Output 3:
      3
      
      4
      
      -11
      


      Added by:Paul Draper
      Date:2012-04-06
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11334. Lucifer Sort

      Problem code: LUCISORT


      Lucifer is as bored as G-One after the defeat of Raone. he has no comuter game to play.

      He Like g-One started reading books and Unlike G-One he bought a Big book shelf and lots of books

      He labled all books with serial numbers.(All books have separate serial numbers).

       

      He invites his friends and small kids to home and allows them to read books. But the problem is everyone replaces the books anywhere on the shelf.

       

      At the end of the day Lucifer has to sort all the books in increasing order of serial number on the shelf from left to right.

      The problem is He knows just one way of sorting called LUCIFER SORT.

       

      He can pick a book from anywhere on the shelf but can Replace it only in the center of the remaining books.

      For eg. of the books are in order

      2 1 3 4 5 6

      The steps of sorting are

      1 3 4 2 5 6  -  Pick 2 and place between between 4 & 5 in (1 3 4 5 6)

      1 4 2 3 5 6  -  Pick 3 and place between between 2 & 5 in (1 4 2 5 6)

      1 2 3 4 5 6  -  Pick 4 and place between between 3 & 5 in (1 2 3 5 6)

       

      Assuming positions are numbered from 1 to N.

      While Replacing if number of books left is even then it is put back between n/2 and n/2+1 position.

      if the books left are odd it is put back between (n+1)/2 and (n+1)/2+1 position.

       

      Since the number of books are large , he needs your help to tell me number of steps he needs to sort the shelf.

      Input

       

      first line contains number of shelves 'svs'

      For each shelf there are 2 lines.

      first line will have number of books 'bks'

      second line will have the serial number of the books at the end of the day.

      Output

      Single line telling how many books he needs to remove and replace.

      If there is no way he can sort the books by this process Print "YOU ARE DOOMED" without the quotes.

       

      Example

      Input:
      
      3
      6
      1 2 3 4 5 6
      6
      2 1 3 4 5 6
      6
      6 5 4 3 2 1
      
      Output:
      
      
      0
      3
      6
      All the values will be in the range [0, 10^7] 
      number of test cases <=100.

      Added by:Devil D
      Date:2012-04-06
      Time limit:1s
      Source limit:15000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Lucifer Sort









      SPOJ Problem Set (classical)

      11345. lcm addition

      Problem code: ADDLCM

      Mao is very good in mathematics, he likes to play with numbers and number theory is his favorite chapter. Once he decided to give a question to kalyu his friend . Now Kalyu is always busy in writing articles, as he likes maths but articles is his passion and source of income too, so he can’t give much time solving that maths question, but he too don’t want to hurt his friend, so help kalu in his problem ?

      Given a,b such that a<=b  calculate the addition:-

       LCM(a,b) + LCM(a+1,b) + .. + LCM(b,b), where LCM(a,b) denotes the Least Common Multiple of the integers a and b.


      Since, output may be very large, take the mod 10^9+7

      Input

      First line cosists of T=number of test  cases, next T line will contain a and b

      Output

      For each T lines, print the required output.

      Constraints

      T<=100000

      1 <= a <= b <= 1000000

      Example

      Input:
      3
      1 6
      10 15
      41 90

      Output:
      66
      675
      139860

      Added by:avinash
      Date:2012-04-08
      Time limit:20s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      11354. Amusing numbers

      Problem code: TSHOW1


      Amusing numbers are numbers consisting only of digits 5 and 6.Given an integer k , display the kth amusing number.

      Input

      FIrst line consists of integer N representing number of test cases

      Next N lines consist of N integers (1<=k<=10^15)

      Output

      N lines each displaying corresponding kth amusing number

      Example

      Input:
      2
      1
      5
      Output: 5
      65

      Added by:Pandian
      Date:2012-04-10
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:AOL code contest









      SPOJ Problem Set (classical)

      11355. SQUARE TO SQUARE

      Problem code: SQ2SQ

      There are Squares whose digits can be rearranged to make another squares.Lets call them S2S numbers.

      for ex.

      144->441

      Input

      Single line containing two integers X Y(Xth,Yth term in the list of S2S numbers).

      Output

      Print all the numbers from Xth to Yth Term of S2S numbers list(both inclusive).

      Example

      Input:
      
      1 3 Output:
      144
      169
      196

      (Xth,Yth term<=10^12)
      (Source Code Limit= 500B)
      Note: 1->100->1 or other similar numbers are NOT S2S numbers(ex 9->900->9)
      Try Tutorial at -> http://www.spoj.pl/problems/SQ2SQ2/


      Added by:Avinash
      Date:2012-04-11
      Time limit:0.400s-14.5s
      Source limit:500B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11371. Answer the boss!

      Problem code: RPLA

      Eloy is a hard worker man, however, he is constantly bullied by his superiors, molested by this, one day he was wondering in what “rank” you are, so you can bully the people with lower ranks, also to discover who can really bully Eloy!.

       

      Now, given the number of employees and the number of relations between them, Eloy need you to output the “rank” which employee is in, being 1 the “boss” (not bullied by anybody) and the employee who are in these ranks

       

      INPUT:

      There will be an integer T denoting the test cases, then, T test cases will follow, each test case starts with two integers N and R, the number of employees and the number of relations between them, the next R lines consists in two integers R1 and R2, meaning that “employee R1 is lower than employee R2's rank”.

       

      OUTPUT:

      You will output for each test case the string “Scenario #i:” where i is the test case you are analyzing, after that, you will print N lines, for each line you will output the rank of the employee and the employee itself, if there is the same rank for several employees, then output them lexicographically ordered (the first is the lower)

       

      SAMPLE DATA:

       

      INPUT

      OUTPUT

      2


      5 6

      2 0

      2 4

      1 4

      1 2

      3 2

      4 0

       

      5 4

      1 0

      2 0

      3 2

      4 2

      Scenario #1:

      1 0

      2 4

      3 2

      4 1

      4 3

      Scenario #2:

      1 0

      2 1

      2 2

      3 3

      3 4

       

      "Blank line between test cases for clarification and separation" 

      "Please note that can be more than one "boss" (not bullied by anybody)"

      CONSTRAINTS:

      1<=N<=1000; 1<=R<=10000


      Added by:David Moran
      Date:2012-04-12
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11372. Blueberries

      Problem code: RPLB


      Teresa picked up enough strawberries, now she wants to pick blueberries from the magical blueberry bush from Rainbowland.

       

      Knowing her previous experience with the strawberries, Teresa wants to pick up the blueberries in a way that she may not exceed the limit proposed.

       

      When picking the blueberries, she noticed that if she pick from the bush i, she couldn't pick the blueberries at the bush i+1 (some sort of magic in rainbowland).

       

      Worried about this, Teresa wants to know the maximum blueberries she can pick, given the number of bushes and the number of blueberries in each bush.

       

      INPUT:

      Will contain an integer T, then, T cases will follow, each case starts with a number N and K, being N the number of bushes and K the number of blueberries Teresa will pick as maximum, the next line contains N integers, each one representing the blueberries there is on the i-th bush.

       

      OUTPUT:

      You will output for each test case the string: “Scenario #i: “ where i is the test case you are analyzing, then, an integer denoting the maximum number of blueberries you can grab.

       

      INPUT

      OUTPUT

      2

      5 100

      50 10 20 30 40

       

      5 87

      21 45 30 12 14

      Scenario #1: 90

      Scenario #2: 65

       

      Blank line between test cases for clarification and separation”

      Output explanation (first scenario)

      Teresa picks the 1st blueberry bush (50), she cannot pick the 2nd, she decides not to pick until the 5th one where she picks the “40” blueberry, she could pick the 3rd bush, but she would exceed the limit (100).

      Output explanation (second scenario)

      Teresa picks the 1st, the 3rd and the 5th bush, total of (21+30+14 = 65) blueberries

       

      CONSTRAINTS:

      1<=N<=1000; 1<=K<=1000


      Added by:David Moran
      Date:2012-04-12
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11373. Coke madness

      Problem code: RPLC


      David likes coke, lets say he likes it a lot... One day he was walking by a narrow street when he sees a lot of bottles of cokes, from different brands, he wants to drink it all, but he noticed that one brand gives him power, the other brand weaken him, now, he can wait and regain more energy, but he don't want to do that, he will wait at the beginning and, when he has the sufficient energy he will drink all the cokes in the street.


      Please, help him find when he will be in the perfect moment to drink all the cokes.

       

      INPUT:

      Will start with an integer T denoting the number of test cases, then, T lines will follow, for each test case, there will be an integer N, then, in the next line will be N integers, this will be the number of cokes, and the values of the cokes in the floor (the positive one gives energy, the negative ones will take his energy).

       

      OUTPUT:

      Each test case will output the string “Scenario #i: “ where i is the number of test case analyzed, followed by the minimum energy required by David to pass the street.

       

      INPUT

      OUTPUT

      2

      5

      4 -10 4 4 4

       

      5

      1 2 3 4 5

      Scenario #1: 7

      Scenario #2: 1


      Blank line between test cases for clarification and separation”

      The life of David should never reach 0 or less”

       

      CONSTRAINTS:

      1<=N<=1000000

      -10000000<=Ni<=10000000


      Added by:David Moran
      Date:2012-04-12
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11374. Database

      Problem code: RPLD

      Gaby enjoy working in a database of a very important university, this university has students of course, each student can see as many subjects they want, however, the database suffered an attack by a group of hackers, now, Gaby needs to see the backup files, but then she noticed that some of the backup files are corrupted as well... For example, the backup file can show that a student is seeing 2 same subjects, desperate, she needs help on this task.

       

      It is known that several students (different ones) can see the same subject, however, one single student cannot see the same subject (this would seem ridiculous), if one student sees the same subject two or more times, this test would belong to a corrupted file.

       

      INPUT:

      First line will contain an integer T, representing the cases to evaluate, the next T cases will start with a N and R, both integers, denoting the number of students and the number of lines the database have, the next R lines contains two integers I and C, I stands for the ID of the students and C for the subject code.

       

      OUTPUT:

      You will output T lines for each test case, starting with the string “Scenario #i: “ where i is the test case you're evaluating, then, you should output the string “impossible” if the database file on evaluation is corrupted and the string “possible” if its not.

       

      INPUT

      OUTPUT

      2

      2 4

      1 6102

      1 6103

      2 6102

      2 6103

       

      2 4

      1 6102

      1 6102

      2 6102

      2 6103

      Scenario #1: possible

      Scenario #2: impossible

       

      Blank line between test cases for clarification and separation”

       

      CONSTRAINTS:

      1<=N<=10000

      1<=R<=100000

      1<=I<=N

      1000<=C<=9999


      Added by:David Moran
      Date:2012-04-12
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11375. Espionage

      Problem code: RPLE


      Marcos the little one decided to build and manage an espionage agency, he was happy working as the chief of his agency, hiring spies to spy everybody in the country! But he realized that some of their own spies are spying themselves, of course, this is bad to the business and he don't want this to happen, he wants a program to alert him whenever a spy is spying another spy.

       

      INPUT:

      Will consists in T test cases, then, T cases will follow, starting from two integers N and R, each one denoting the number of persons to evaluate and the number of relationships spy-person each one has, then, R lines will follow and will contain two integers R1 and R2, meaning that R1 spies R2

       

      OUTPUT:

      Will consist in T lines, starting from the string “Scenario #i: “ where i is the number of the test case you're analyzing, print the string “spying” if each spy has as a target a civilian, print “spied” otherwise

       

      INPUT

      OUTPUT

      3

      3 2

      0 1

      2 1

       

      3 3

      0 1

      2 1

      0 2

       

      4 2

      2 3

      0 1

      Scenario #1: spying

      Scenario #2: spied

      Scenario #3: spying

       

      "Blank line between test cases for clarification and separation"

       

      CONSTRAINTS:

      1<=N<=1000

      1<=R<=10000

       

      Explanation of the second test case:

      Spy 0 spies civilian 1, spy 2 spies civilian 1, spy 0 spies spy 2. (Spied case).


      Added by:David Moran
      Date:2012-04-12
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11383. Fast Sum of two to an exponent

      Problem code: FAST2


      There is people that really like to do silly thinks, one of them is sum the numbers from 2^0 to 2^n, task is actually really simple, just do a ultra fast sum of term 2^0 to 2^n

      Input

      the first line starts with a number, T, wich is the number of test cases, T lines will follow

      each line contains a number "n" that is the nth term of the sum from 2^0 to 2^n

      0<=n<=500

      Output

      Output the sum from 2^0 to 2^n MODULO 1298074214633706835075030044377087

      Example

      Input:
      3
      0
      1
      2

      Output: 1
      3
      7

      Extra: TLE is equal to 0.15s

      Added by:Rodolfo Miquilarena
      Date:2012-04-14
      Time limit:0.119s
      Source limit:500B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      11384. Zoom Operation

      Problem code: ZOOMOP2

       

      Zoom Operation:

      zoomop

      zoomop

      zoomop

      Use only 4 symbols:  + ? - #   (in circular order  beginning with + ) to zoom the number given. 

      Every segment of the number has one symbol more than the previous.(First Segment has a single symbol).

      First symbol of evry segment starts in the same column/row where the previous segments' last symbol ends.

      1st segment(orange color) -> 1 symbol   + (first symbol only)

      2nd segment(green color) -> 2 symbols  ? - (starts with 2nd symbol as 1st segment uses sinlge element)

      3rd segment(yellow color) -> 3 symbols  # + ? (starts with 4th symbol as 3 symbols have been used)

      Colors are shown for better understanding.See Picture for more clarification.

       

      Input:

      Given a number you have to apply Zoom operation and print it.

      Output:

      Print the Pattern after Zoom Operation.

       

      Example:

      Input:

      1

      Output:

      +

       

      Input:

      2

      Output:

         +?
           -
      -?+#
      #
      +
      ?
      -#+?-

       

      Input:

      3

      Output:

           +?
             -
        -?+#
        #
        +
        ?
        -#+?-#
                +
                ?
                -
                #
                +
      #-?+#-?                       

       

      Input:

      4

      Output:

      +
      ?-#
         +
         ?

       

      Input:

      5

      Output:

        ?+
        -
        #+?-
             #
             +
             ?
       -?+#-                 

       

      For any clarification,refer to the picture above.

      Try tutorial at -> http://www.spoj.pl/problems/ZOOMOP/


      Added by:Avinash
      Date:2012-04-14
      Time limit:0.009s-0.270s
      Source limit:256B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11386. Recycled Numbers

      Problem code: GCJ2012C

      Do you ever become frustrated with television because you keep seeing the same things, recycled over and over again? Well I personally don't care about television, but I do sometimes feel that way about numbers.

      Let's say a pair of distinct positive integers (n, m) is recycled if you can obtain m by moving some digits from the back of n to the front without changing their order. For example, (12345, 34512) is a recycled pair since you can obtain 34512 by moving 345 from the end of 12345 to the front. Note that n and m must have the same number of digits in order to be a recycled pair. Neither n nor m can have leading zeros.

      Given integers A and B with the same number of digits and no leading zeros, how many distinct recycled pairs (n, m) are there with A ≤ n < m ≤ B?

      Limits
      1 ≤ T ≤ 55
      A and B have the same number of digits.
      1 ≤ A ≤ B ≤ 2000000.

      Are we sure about the output to Case #4?
      Yes, we're sure about the output to Case #4.

      Input

      The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single line containing the integers A and B.

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is the number of recycled pairs (n, m) with A ≤ n < m ≤ B.

      Example

      Input:
      4
      1 9
      10 40
      100 500
      1111 2222
      
      Output:
      Case #1: 0
      Case #2: 3
      Case #3: 156
      Case #4: 287
      

      Added by:Ruslan Sennov
      Date:2012-04-15
      Time limit:9s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:GCJ2012









      SPOJ Problem Set ()

      11391. EASY MATH

      Problem code: EASYMATH

      You will be given 4 numbers

      n m a d

      find count of numbers between n & m (inclusive) not divisible by (a) or (a+d) or (a+2d) or (a+3d) or (a+4d).

      Input

      first line has number t - number of test cases.

      each test case has 4 numbers          n m a d

      Output

      Single line having single number giving the count

      Example

      Input:
      3
      1 10 2 2
      20 100 3 3
      100 1000 4 5 
      
      Output:
      
      
      5
      54
      543
      NOTE - 1<=n<=m<= 2^32
      	1<=a<= 2^32
      	1<=d<=2^32
      	2<=t<=100
      ALSO TRY THR CHALLENGE VERSION --- /http://www.spoj.pl/problems/EASYMATC/
      Added by:Devil D
      Date:2012-04-17
      Time limit:0.400s-1s
      Source limit:20000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      11401. Bazinga!

      Problem code: DCEPC505

      Sheldon is very proud of his intelligence. To test his intelligence Howard designs a puzzle and asks him to solve it. The puzzle consists of special numbers which can be obtained by multiplying exactly two distinct prime numbers. Sheldon has to tell Howard what is the Kth element of this series. Help him.

      For Example 6,10,14,15 are the first few members of this series whereas 4,9 and 12 are not.

      Input

      First line specifies T, the number of test cases.

      Next T lines each gives 1 number, K

      Output

      Output 1 line for each test case giving the Kth element of this series.

      Constraints

      1<=T<=1000

      1<=K<=2000000

      Example

      Input:

      4
      2
      3
      5
      7
      Output:

      10
      14
      21
      26


      Added by:dce coders
      Date:2012-04-18
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11402. The Indian Connection

      Problem code: DCEPC504


      Rajesh Kuthrapali has a weird family structure. Every male member gives birth to a male child first and then a female child whereas every female member gives birth to a female child first and then to a male child. Rajesh analyses this pattern and wants to know what will be the Kth child in his Nth generation. Help him.

      Note:

      1.Every member has exactly 2 children.

      2. The generation starts with a male member(Rajesh).

      3. In the figure given below:

                                         M-------- 1st generation 

                                    /        \
                                M             F ------- 2nd generation
                              /    \         /   \
                            M     F       F     M
                                            |
                                         3rd child of 3rd generation

      Input

      First line specifies T, the number of test cases.

      Next T lines each gives 2 numbers, N and K

      Output

      Output 1 line for each test case giving the gender of the Kth child in in Nth generation.

      Print “Male” for male “Female” for female (quotes only for clarification).

      Constraints

      1<=T<=100

      1<=N<=10000

      1<=K<=min(10^15 , 2^(n-1))

      Example

      Input:
      4
      1 1
      2 1
      2 2
      4 5 
      Output:
      Male
      Male
      Female
      Female

      Added by:dce coders
      Date:2012-04-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set ()

      11404. Save Thy Toys

      Problem code: DCEPC501

      Leonard is very fond of buying rare and expensive science fiction toys. He keeps his collection in a sequential order of the date on which the toy was bought in a special closet so that his roomie Sheldon never gets hold of his toys. But because of his bad luck Leonard once loses a bet to Sheldon and Sheldon demands a share Leonard’s toys. Since Leonard doesn’t want to loose much money, he decides upon a strategy to reduce his loss to minimum.

      Leonard, beginning from the first toy in his closet will pick some toys, say "x" toys in sequence. Sheldon will then pick the next "x" toys (Note that Sheldon picks equal no. of toys as picked by Leonard in his move unless the remaining toys are less than "x". In that case he picks all of the remaining). This will keep going on till no more toys are left in the closet for Leonard to pick. You are given the sequence of toys with their price. Help Leonard in maximizing the total price of all toys he picks.

      Leonard in his each turn can either pick only 1 or 2 or 3 toys ("x" described above can take value either 1, 2 or 3).

      Input

      First line specifies T, the number of test cases.

      Each test case contains N in the first line. Second line contains N integers as described above.

      Output

      Output 1 line for each test case giving the maximum possible value of the total sum of all toys Leonard picks.

      Constraints

      1<=T<=10

      1<=N<=100000

      1<=Price of toys<=1000000

      Example

      Input:
      2
      4
      5 4 3 2
      6
      10 8 7 11 15 20
      
      Output:
      12
      53



      Explanation:

      In 1st case, Leonard picks 3 toys in his first move with value 5,4,3 and Sheldon has no choice but to pick the last.
      In 2nd case, Leonard picks 10, 8. Then Sheldon picks 7,11. And then Leonard picks the rest.


      Added by:dce coders
      Date:2012-04-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11405. Just Like the Good Old Days

      Problem code: DCEPC502


      Sheldon and Penny are neighbours. Penny really likes grid games so Sheldon develops a new grid based game for Penny. The game consists of a MXN grid (M rows, N columns) and an infinite number of black and white knights. The grid has some open and some closed blocks. In the beginning of the game each player chooses his colour of knight.The rule says that each player on his turn can place his knight on any of the open blocks such that none of his knights attack any knight of other colour (he may attack any knight of the same colour). You are given a MXN grid. Specify the maximum number of knights (black+white) which can be placed on the grid. The game stops when any one player cannot place any more knights.

      Note: In one turn, Knight can move exactly two squares horizontally and one square vertically, or two squares vertically and one square horizontally.

      Input

      First line specifies T, the number of test cases.

      First line of each test case gives M and N seperated by a single space

      This is followed by a grid of size MXN consisting of ‘.’ And ‘#’. Each ‘.’ represents an open
      position and each ‘#’ represents closed position.

      Output

      Output 1 line for each test case giving the maximum possible value of knights that can be placed.

      Constraints

      1<=T<=5
      1<=M,N<=10
      0<= No. of open positions "." <=10

      Example

      Input:
      2
      3 3
      ...
      ...
      ...
      3 3
      ...
      .#.
      ...
      
      Output:
      7
      6

      Added by:dce coders
      Date:2012-04-18
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11407. Tied Down

      Problem code: TDOWN


      As we all know, Bessie the cow likes nothing more than causing mischief on the farm. To keep her from causing too much trouble, Farmer John decides to tie Bessie down to a fence with a long rope. When viewed from above, the fence consists of N posts (1 <= N <= 10) that are arranged along vertical line, with Bessie's position (bx, by) located to the right of this vertical line. The rope FJ uses to tie down Bessie is described by a sequence of M line segments (3 <= M <= 10,000), where the first segment starts at Bessie's position and the last ends at Bessie's position. No fence post lies on any of these line segments. However, line segments may cross, and multiple line segments may overlap at their endpoints.

      Here is an example of the scene, viewed from above:

      To help Bessie escape, the rest of the cows have stolen a saw from the barn. Please determine the minimum number of fence posts they must cut through and remove in order for Bessie to be able to pull free (meaning she can run away to the right without the rope catching on any of the fence posts). All (x,y) coordinates in the input (fence posts, Bessie, and line segment endpoints) lie in the range 0..10,000. All fence posts have the same x coordinate, and bx is larger than this value.

      Input

      * Line 1: Four space-separated integers: N, M, bx, by.

      * Lines 2..1+N: Line i+1 contains the space-separated x and y coordinates of fence post i.

      * Lines 2+N..2+N+M: Each of these M+1 lines contains, in sequence, the space-separated x and y coordinates of a point along the rope. The first and last points are always the same as Bessie's location (bx, by).


      Output

      * Line 1: The minimum number of posts that need to be removed in order for Bessie to escape by running to the right.

      Example

      Input:
      2 10 6 1
      2 3
      2 1
      6 1
      2 4
      1 1
      2 0
      3 1
      1 3
      5 4
      3 0
      0 1
      3 2
      6 1
      Output:
      1
      Output explanation:
      Removing either post 1 or post 2 will allow Bessie to escape.


      Added by:Ikhaduri
      Date:2012-04-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:USACO OPEN 2012









      SPOJ Problem Set (classical)

      11409. Fibonacci With a Twist

      Problem code: FIBTWIST

      Fibonacci numbers are given by 

      f(n)=f(n-1) + f(n-2)

      with f(0) =0       &        f(1) =1

      first number of series ------ 0  1  1  2  3  5  8  13 

      Now lets have a new series called "Fibonacci Twist" which is given by 

      ft(n) = ft(n-1) + ft(n-2) + (n-1)  

      with ft(0) = 0  & ft(1) =1

      with first few number in the series ----- 0  1  2  5  10  19  34  59 

       

      Now your task is to find ft(n).

      Since the number can be Big you have to find the result mod M.

      Input

      first line having single number 't' -- number of test cases.

      next t lines have 2 number each     'n' and 'M'

      Output

      Single number given the nth term mod M

      Example

      Input:
      
      3
      5 20
      10 77
      15  111
      
      Output:
      
      
      19
      45
      69
      NOTE -
      10<=t<=100
      0<=n<=10^9
      100<=M<=10^9
      Explanation - 
      1)  ft(5) is 19 . 19%20 = 19
      2)  ft(10) is 276 .  276%77  = 45
      3)  ft(15) is 3177 . 3177 %111=69

      Added by:Devil D
      Date:2012-04-19
      Time limit:0.5s-1.5s
      Source limit:20000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      11414. Combat on a tree

      Problem code: COT3


      Alice and Bob are playing a game on a tree of n nodes.Each node is either black or white initially.

      They take turns to do the following operation:
      Choose a white node v from the current tree;
      Color all white nodes on Path(1,v) to black.

      The player who takes the last turn wins.

      Now Alice takes the first turn.Help her find out if she can win when they both use optimal strategy.

      Input

      The first line of input contains a integer n representing the number of nodes in the tree. 1<=n<=100000

      The second line contains n intergers c1,c2,..cn.0<=ci<=1.
      ci=0 means the ith node is white initially and ci=1 means black.

      Next n-1 lines describes n-1 edges in the tree.Each line contains two integers u and v,means there is a edge connecting u and v. 

      Output

      If Alice can't win print -1.

      Otherwise determine all the nodes she can choose in the first turn in order to win.Print them in ascending order.

      Example

      Input#1:
      8
      1 1 0 1 0 0 1 0
      1 2
      1 3
      2 6
      3 4
      3 5
      5 7
      7 8 
      Output#1:
      5
      Input#2:
      20
      1 1 1 0 1 1 1 0 1 0 0 0 1 0 1 0 0 0 0 0
      1 2
      2 3
      2 4
      1 5
      1 6
      5 7
      5 8
      2 9
      8 10
      1 11
      1 12
      9 13
      6 14
      14 15
      7 16
      11 17
      2 18
      7 19
      12 20 
      Output#2
      8
      11
      12 

      Added by:Fotile
      Date:2012-04-20
      Time limit:1s-1.200s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11440. Unlock it ! Part 2

      Problem code: DCEPC604


      Now you all helped Vaibhav solve the puzzle and open the gate last time (although not
      too much help). But as soon as he opens the gate, there is another puzzle to open the front door. Let’s see whether this time you all are able to help him or not.

      Fac(n) = no of zeroes in n!
      Fact(n)= Fac(n)%25+1

      F(0)=1

      F(1)=1

      F(2)=1

      F(n) = product of all odd primes less than or equal to n (for n<=10)

      F(n) = 4^fact(n) * f(n/5) * f(n/10)   (for n>10)

       

      For every fraction , a floor value is taken for evaluation.

      For eg. F(11)=4^fact(11) * F(floor(11/5)) * F(floor(11/10))  = 4^3 * F(2) * F(1) = 64

      Given N. Find the max value of (a^b)%mod such that a and b satisfies the relation gcd(a,b) = F(N).

      Gcd : Greatest common divisor

      Input

      First line gives T, total number of testcases.
      Next T line gives number N

      Output

      For each test case, print the desired value on a new line.

      Constraints

      T<=10

      N<=10^6

      mod = 10^9.

      NOTE: a must be <= 5*F(n) and b must be <=5*F(n) , a can be equal to b and mod=10^9

      Example

      Input:
      
      1
      2 
      
      Output:
      
      1024

      Added by:dce coders
      Date:2012-04-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11443. Davids Greed

      Problem code: DAVIDG

      The King David it’s a particularly miser character. He have all the gold in his kingdom, and never lends a single coin to anyone. Years passed, and the streets in his kingdom, made by his father, King Enrique, started to deteriorate. The villagers couldn’t traffic with their carts without dropping some of their content.

      This problem was affecting the merchants, because they were losing food and other stuff that they sell. So they decided to go to the castle and block the entrance, so the king couldn’t get out until he promised that he would restore the streets.

      The King, tired by the annoyance of the people, decided to promess to restore the streets of his kingdom, but because he’s too greedy, he will restore only the ones that are important for the city, let’s call them “vital streets”.

      The vital streets connect a commercial point A to a commercial point B in the city such that there will never exist 2 ways to go from point A to point B. This is given by some coordinates X and Y, you can assume the commercial point will be a single point in a space.

      The original streets, built by King Enrique, connects every point with the other points, so point A it’s connected with point B, C, D, and so on. So restore every street would be too expensive, that’s why King David will restore only the “vital streets”, but he is not really good at this type of calculations, so he need you to write a program that help him out.

      The cost of restoring a street is given by its length and some value P, that tell how much cost to restore a single unit of distance. By example, if P = 3, and the distance of points A and B it’s 3.5, then the total cost of restoring that street would be 3.5 * 3. Note: you have to round up the total cost of the street.


      Input

      The first line of input will consist of an integer T, denoting the number of test cases. Every test case will have by first line 2 integers, N and P, denoting the number of points and the unitary cost. Then N lines follow, every of them having 2 numbers Xi  and Yi , denoting the coordinates in the cartesian plane of every commerciant points.

      Output

      For each test case output a single line containing this: “Scenario #i: j”, where i is the number of the test case, starting in one, and j it’s the minimum cost of restoring the streets, such as the restored streets let the villagers to go from one point to another point. Since this number can be quite large, output j mod 10^9 + 7.

      Example

      Input:
      
      

      2

      4 1

      35 46

      29 13

      44 0

      27 17

      3 18

      18 0

      11 17

      2 31

      Output:

      Scenario #1: 56

      Scenario #2: 631


      Constraints:

      1 ≤ N ≤ 1,000

      -1,000 ≤ Xi , Yi ≤ 1,000

      1 ≤ P ≤ 1,000


      Added by:Luis Arguello
      Date:2012-04-22
      Time limit:0.5s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PYTH 3.2.3 n
      Resource:Own problem.









      SPOJ Problem Set (classical)

      11444. MAXOR

      Problem code: MAXOR


      You are given a sequence A[1], A[2], ..., A[N] . ( 0 ≤ A[i] < 231 , 1 ≤ N ≤ 12000 ).

      A query is defined as follows:
      Query(x,y) = Max { a[i] xor a[i+1] xor ... xor a[j] ; l ≤ i ≤ j ≤ r }.
      l = min ( ((x+lastans) mod N)+1 , ((y+lastans) mod N)+1 ).
      r = max ( ((x+lastans) mod N)+1 , ((y+lastans) mod N)+1 ).
      lastans[1] = 0 , lastans[i] = Query[i-1].
      G
      iven M queries, your program must output the results of these queries. ( 0 ≤ M ≤ 6000 ).

      IMPORTANT : PROBLEM ENHANCED. ( I'M SO SORRY.. )

      Input

      • The first line of the input file contains 2 numbers : N M.
      • In the second line, N numbers follow.
      • M lines follow, where line i contains 2 numbers xi and yi.

      Output

        Your program should output the results of the M queries, one query per line.

      Example

      Input:
      3 3
      1 4 3
      0 1
      0 1
      4 3
      Output:
      5
      7
      7

      Added by:Fotile
      Date:2012-04-23
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:seter









      SPOJ Problem Set (classical)

      11458. Ninja

      Problem code: VUDBOL5


      A ninja is practicing and he is very fast he can make two cuts in one second and his master give he a new challenge. The master take a cube, thrown through the air and quickly says four numbers. The ninja has to think fast to make two cuts and get desired values.

      Given a cube of size N*N*N, he need to cut it into four entire pieces of size A, B, C and D. He needs to divide the cube in these pieces with only two cuts, one vertical and one horizontal.

      Input

      The input consists in multiple test cases.
      Each test case begins a line containing five integers N (2 <= N <= 1000000), A, B, C y D (1 <= A, B, C, D <= 2^63).
      The end of input is indicated by a line with five zeros. This is not a part of any test cases.

      Output

      For each test case print "Possible" if it is possible to obtain the pieces and print "Impossible" if it is not possible to obtain the pieces with two cuts.

      Example

      Input:
      2 5 1 1 1
      2 2 2 2 2
      3 12 3 6 6
      0 0 0 0 0
      
      Output:
      Impossible
      Possible
      Possible
      
      

      ID RESULT TIME
      code...



      Added by:Edwin Guzman
      Date:2012-04-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      11460. Planning Poker

      Problem code: VUDBOL7

      Planning Poker, also called Scrum poker, is a consensus-based technique for estimating, mostly used to estimate effort or relative size of user stories in software development.
      A typical Planning Poker Deck has cards showing the Fibonacci sequence including a zero: 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. other decks use similar progressions.
      We have some tasks estimated with other complexities from 1 to 10000000.
      We need to estimate the complexity of all tasks using the Fibonacci sequence used in Planning Poker. The rule is that the old complexity will change to the valid complexity more close. But if two complexities are in equal distances take the higher.

      Input

      The input consists of multiple test cases.
      Each test case begins with a line containing an integer “N” (1 <= N <= 100000) the number of tasks. In the following line are the complexities of "N" tasks from "0" to "N-1" (1 <= task[i] <= 10000000).
      The end of input is indicated by a line with one zero. This is not a part of any test cases.

      Output

      For each test case print the list of new complexities sorted in ascending order. Print a space character between two complexities.

      Example

      Input:
      5
      1 2 3 4 5
      5
      7 8 9 11 10
      0
      
      Output:
      1 2 3 5 5
      8 8 8 8 13
      
      

      ID RESULT TIME
      code...



      Added by:Edwin Guzman
      Date:2012-04-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      11461. Book Shelves

      Problem code: SHELF


      When Farmer John isn't milking cows, stacking haybales, lining up his cows, or building fences, he enjoys sitting down with a good book. Over the years, he has collected N books (1 <= N <= 100,000), and he wants to build a new set of bookshelves to hold them all.

      Each book i has a width W(i) and height H(i). The books need to be added to a set of shelves in order; for example, the first shelf should contain books 1...k for some k, the second shelf should start with book k+1, and so on. Each shelf can have a total width of at most L (1 <= L <= 1,000,000,000). The height of a shelf is equal to the height of the tallest book on that shelf, and the height of the entire set of bookshelves is the sum of the heights of all the individual shelves, since they are all stacked vertically.

      Please help FJ compute the minimum possible height for the entire set of bookshelves.

      INPUT FORMAT: 
      * Line 1: Two space-separated integers: N and L. 
      * Lines 2..1+N: Line i+1 contains two space-separated integers: H(i)         and W(i).  (1 <= H(i) <= 1,000,000; 1 <= W(i) <= L).
      SAMPLE INPUT
      5 10 
      5 7 
      9 2 
      8 5 
      13 2 
      3 8
      INPUT DETAILS: 
      There are 5 books.  Each shelf can have total width at most 10. 
      OUTPUT FORMAT: 
      * Line 1: The minimum possible total height for the set of         bookshelves.
      SAMPLE OUTPUT : 
      21 
      OUTPUT DETAILS: 
      There are 3 shelves, the first containing just book 1 (height 5, width 7), the second containing books 2..4 (height 13, width 9), and the third containing book 5 (height 3, width 8).


      Added by:Ikhaduri
      Date:2012-04-25
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Usaco open 2012









      SPOJ Problem Set (classical)

      11469. Balanced Cow Subsets

      Problem code: SUBSET

      Farmer John's owns N cows (2 <= N <= 20), where cow i produces M(i) units of milk each day (1 <= M(i) <= 100,000,000).

      FJ wants to streamline the process of milking his cows every day, so he installs a brand new milking machine in his barn.

      Unfortunately, the machine turns out to be far too sensitive: it only works properly if the cows on the left side of the

      barn have the exact same total milk output as the cows on the right side of the barn!

      Let us call a subset of cows "balanced" if it can be partitioned into two groups having equal milk output.

      Since only a balanced subset of cows can make the milking machine work, FJ wonders how many subsets of his N cows are balanced.

      Please help him compute this quantity.

      INPUT FORMAT:
      * Line 1: The integer N.
      * Lines 2..1+N: Line i+1 contains M(i).
      SAMPLE INPUT
      4
      INPUT DETAILS:
      There are 4 cows, with milk outputs 1, 2, 3, and 4.
      OUTPUT FORMAT: 
      * Line 1: The number of balanced subsets of cows. 
      SAMPLE OUTPUT:
      3
      OUTPUT DETAILS: 
      There are three balanced subsets: the subset {1,2,3}, which can be partitioned into {1,2} and {3}, the subset {1,3,4}, 
      which can be partitioned into {1,3} and {4}, and the subset {1,2,3,4} which can be partitioned into {1,4} and {2,3}.

      Added by:Ikhaduri
      Date:2012-04-29
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Usaco open 2012









      SPOJ Problem Set (classical)

      11470. To the moon

      Problem code: TTM

      Background

      To The Moon is a independent game released in November 2011, it is a role-playing adventure game powered by RPG Maker.

      River && Anya .. .

      The premise of To The Moon is based around a technology that allows us to permanently reconstruct the memory on dying man. In this problem, we'll give you a chance, to implement the logic behind the scene.

      Description

      You‘ve been given N integers A[1], A[2],..., A[N]. On these integers, you need to implement the following operations:

      • C l r d: Adding a constant d for every {Ai | l <= i <= r}, and increase the timestamp by 1, this is the only operation that will cause the timestamp increase. 
      • Q l r: Querying the current sum of {Ai | l <= i <= r}.
      • H l r t: Querying a history sum of {Ai | l <= i <= r} in time t.
      • B t: Back to time t. And once you decide return to a past, you can never be access to a forward edition anymore.

       .. N, M ≤ 10^5, |A[i]| ≤ 10^9, 1 ≤ l ≤ r ≤ N, |d| ≤ 10^4 .. the system start from time 0, and the first modification is in time 1, t ≥ 0, and won't introduce you to a future state. 

      Input

      n m
      A1 A2 ... An
      ... (here following the m operations. )

      Output

      ... (for each query, simply print the result. )

      Example

      Input 1:
      10 5 1 2 3 4 5 6 7 8 9 10 Q 4 4 Q 1 10 Q 2 4 C 3 6 3 Q 2 4

      Output 1:
      4 55 9 15

      Input 2:
      2 4 0 0 C 1 1 1 C 2 2 -1 Q 1 2 H 1 2 1

      Output 2:

      0 1

      Added by:xiaodao
      Date:2012-04-30
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem, 2012 Multi-University Training Contest 5









      SPOJ Problem Set (classical)

      11472. Amazing Maze

      Problem code: DCEPC701

      Chintu and his father Nikka, on their vacations, went to The Amazing Maze. But unfortunately, Chintu is has been separated from his father. His father Nikka has to find him as soon as possible in the maze or else Chintu will start crying soon.

      The Amazing Maze is actually pretty amazing! The maze is built in a rectangular grid fashion. There are walls (#) and walking cells (.) in the grid. One can only walk through walking cells and so cannot jump off the wall. The amazing part is that each wall becomes a walking cell at some point of time (Neglect the transition time). Alternatively one can say that at some time t1 units, the wall will become walking cell and so one can step on to it at t1 time and at any time after t1. One can only move to adjacent walking cells from a walking cell. Adjacent cells mean the immediate up, down, right and left walking cells. It takes 1 unit of time to go from current cell to any adjacent cell. One can also wait on a particular walking cell for an adjacent wall to become a walking cell.

      Nikka has the map of the maze with the information of the time at which the walls becomes walking cells. Also he knows at which walking cell he is situated and at which walking cell Chintu is situated. Help Nikka find out the minimum time required to reach to his son Chintu.

      Input

      First line contains T, the number of test cases.

      Each case begins with two integers, M and N, the dimensions of maze.

      Next contains M lines each containing N characters. Each character is either a “#” or a “.” as described above. This maze is the snapshot at time t=0.

      Next M lines contain N space separated non negative integers. For each “.”, there will be a 0 and for each “#”, there will be a positive integer which represent the time at which that wall (#) will become a walkable cell.

      Next line contains x1 and y1 denoting the position of Nikka in the maze.

      Next line contains x2 and y2 denoting the position of Chintu in the maze.

      Output

      Output T lines each containing an integer, the minimum time required for Nikka to reach Chintu.

      Constraints

      1<=T<=10
      1<=M<=200
      1<=N<=200
      0<=x1, x2<M
      0<=y1, y2<N

      For all #’s, time “t” will be > 0 and <= 10^4.

      Example

      Input:
      

      2

      1 5

      ..#..

      0 0 1 0 0

      0 0

      0 4

      3 3

      .##

      ##.

      ##.

      0 1 2

      3 4 0

      6 7 0

      0 0

      2 2 Output: 4
      4

      Added by:dce coders
      Date:2012-04-30
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11473. NOS

      Problem code: DCEPC702

      Find the number of strings of length “N” made up of only 3 characters – a, b, c such that “a” occurs at least “min_a” times and at most “max_a” times, “b” occurs at least “min_b” times and at most “max_b” times and “c” occurs at least “min_c” times and at most “max_c” times. Note that all permutations of same string count as 1, so “abc” is same as “bac”.

      Input

      First line gives T, the number of test cases.

      Each test case has an integer “N” on first line.

      Next line contains 2 integers, min_a and max_a.

      Next line contains 2 integers, min_b and max_b.

      Next line contains 2 integers, min_c and max_c.

      Output

      Output T lines, each containing the required answer modulo 10^9+7.

      Constraints

      1<=T<=1000
      1<=N<=10^9
      1<=min_a<= max_a<=10^9

      1<=min_b<= max_b<=10^9

      1<=min_c<= max_c<=10^9

      Example

      Input:
      

      1

      3

      1 1

      1 1

      1 1

      Output: 1

      Added by:dce coders
      Date:2012-04-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11474. Totient Game

      Problem code: DCEPC703


      Bahl and Debnath are always looking up for new exciting games on the internet. Yesterday, Bahl stumbled across a new game known as “Totient Game”. He immediately showed that to Debnath. They found it pretty exciting and decided to play it. The game is as follows:

      1. The game is played with N piles of stones.
      2. 2 players play alternatively and at each turn a player selects a pile and divides it into two unequal sized piles “i” and “j” such that Totient(i)*Totient(j)=Totient(i*j) and i+j = no. of stones in that pile.
      3. The player who is unable to make a move loses the game.

      Bahl insists on starting the game first. Can you predict the winner of the game? Assume that both player plays optimally.

      http://en.wikipedia.org/wiki/Euler%27s_totient_function

      Input

      First line gives T, the number of test cases.

      Each test starts with a line containing “N”, the number of piles.

      Next line gives N space separated integers. The ith integer represents the number of stones in the ith pile.

      Output

      Output T lines each containing the winner of the T games. Output “Bahl” if Bahl wins the game or “Debnath” if Debnath wins the game.

      Constraints

      1<=T<=10
      1<=N<=10^5
      1<= No. of stones in each pile <=10^7

      Example

      Input:
      1
      3
      1 2 3
      
      
      Output:
      Bahl

      Added by:dce coders
      Date:2012-04-30
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11476. Weird Points

      Problem code: DCEPC705

      Given N distinct points in a plane, a point (x1, y1) is said to be dominating another point (x2, y2) if x1>=x2 and y1>=y2.

      The Dominance of a point is the absolute difference between 2 quantities – no. of points dominated by this point and no. of points not dominated by this point. (excluding itself)

      A Weird point is the point whose Dominance value is greater than or equal to a threshold value ‘k’. Find the no. of such Weird Points among those N given points.

      Input

      First line gives T, the no. of test cases.

      Each test case consists of 2 integers in first line, N and K, as specified above.

      Next N lines give the coordinates of N points in the plane. “Xi” and “Yi” are space separated.

      Output

      Output T lines, each containing the required answer.

      Constraints

      1<=T<=10
      1<=N<=10^5
      1<=Xi, Yi<=10^9
      0<=K<=N

      Example

      Input:
      1
      4 2
      3 1
      7 5
      2 8
      6 7
      Output:
      2

      Problem Statement and Test Cases has been updated 2012-05-17 18:10:00.


      Added by:dce coders
      Date:2012-04-30
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11477. Meeting For Party

      Problem code: DCEPC706

      Ankur, Anuja and Jyoti are planning to have party at some place. Their houses are located at different points in a rectangular grid of size M*N. They want to meet in minimum time and then party.

      The M rows and N columns rectangular grid contains some impassable points (denoted by a #), however. So none of them wants to step over these points. They can only step over passable points (denoted by a .). They can also meet at some point outside the grid. You can assume that the points outside the grid are all passable. They cannot party on an impassable point and they have their house only on passable point. They can move either to North, South, East or West passable point from the current passable point and it takes 1 unit time to do so. Also they can wait at a passable point if they want to.

      Find the minimum time of meeting.

      Note: Assume that they will always meet at some point.

      Input

      First line gives T, the no. of test cases.

      Each test case has two space separated integers M and N, the dimensions of the grid.

      Next M lines contain N characters per line (no spaces). Characters can be either “#” (impassable) or “.” (passable) or “1” (Ankur’s house) or “2” (Anuja’s House) or “3” (Jyoti’s house). Each test case will have exactly 1 “1”, exactly 1 “2” and exactly 1 “3”.

      Output

      Output T lines, each containing the required answer.

      Constraints

      1<=T<=10
      1<=M<=200
      1<=N<=200

      Example

      Input:
      
      4 4
      1
      #...
      4 4 #... .2#. ..#3 1..#
      .2#.
      ..#3
      1..#
      Output: 4

      Added by:dce coders
      Date:2012-04-30
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11482. Count on a trie

      Problem code: COT4

       

      Maintain two sets of strings S and T.Initially,each set contains an empty string with id 1.
      You are to perform the follwing four operations:
      1.Add a char to the end of an existed string in S,then insert the new string into S.Since there has been n strings in S already,the new string will hold the id n+1.
      2.Add a char to the beginning or to the end of an existed string in T,then insert the new string into T.
      3.Choose two existed strings S1 and S2 from T,next combine them into a new one S1S2,then insert the new string into T.
      4.Print the time that an existed string S1 in T appears in an string S2 in S.

       

      Maintain two sets of strings S and T.Initially,each set contains an empty string with id 1.
      Your program are to perform the following four operations:

      1.Add a char c to the end of an existed string Si in S,then insert the new string into S.Since there has been n strings in S already,the new string will hold the id n+1.
      2.Add a char c to the beginning or to the end of an existed string Ti in T,then insert the new string into T.
      3.Choose two existed strings Ti and Tj from T,next combine them into a new one TiTj,then insert the new string into T.
      4.Print the time that an existed string Ti in T appears in an string Si in S.Your program should print 0 if Ti is an empty string. 

       

       

      Input

      In the first line,there is an integer Q,which means the number of operations to perform.
      In the next Q lines,the i-th line describes the i-th operation containing some integers.Such a line may look like this:
      1 Si c
      2 0 Ti c =>add c to the beginning of Ti
      2 1 Ti c =>add c to the end of Ti
      3 Ti Tj
      4 Ti Si

      Q<=300000,'a'<=c<='z'
      The number of the first operation will not exceed 100000. 
      The number of the third operation will not exceed 30000.
      The number of fourth operation will not exceed 100000.   

      Output

      For each "4 Ti Si" operation,print its result;

      Example

      Input:
      18
      1 1 a
      1 2 a
      1 3 b
      1 2 b
      1 5 a
      1 5 b
      2 1 1 a
      3 2 2
      2 0 3 b
      2 1 2 b
      3 2 5
      3 5 2
      4 7 6
      4 5 6
      4 3 4
      4 2 4
      4 2 7
      4 2 6
      
      Output:
      1
      1
      1
      2
      1
      2

      Added by:Fotile
      Date:2012-05-01
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11493. Goto & labels

      Problem code: RPLG

       Vero is working on an important company, the company noticed that Vero codes using goto labels, her boss does not want Vero to code this kind of programs, the boss tells her that he will cut her payment by the number of lines contained between the label and the goto.

       

      Vero does not know any iterative structures, and she is too worried to code the program she is asking you for, Code a solution for Vero's problem.

       

      The solution to this is to count the lines of code that are between the label and the goto statement, having in consideration that the goto will always return to an existent label, the label will consist on a single string formed by letters from the 'a' to the 'z' and from the 'A' to the 'Z', all labels will have the format <label>: as the goto will always contains the format goto <label>;, however, remember that before the labels and the gotos you can have an important amount of spaces that will count as an indentation of a code.

      Note: An uppercase letter label is distinct from a lowercase letter label, by example: 'abc' is not equal to 'ABC'

       

      INPUT:

      The first line of input will contain an integer T denoting the T test cases, then, T cases will follow. Each of the following line will contain an integer N, then, N lines will follow, each of the next N lines will contain a string S.

       

      OUTPUT:

      Output the string “Scenario #i: “ where i is the test case you are analyzing followed by the sum of the number of lines between the label and the goto.

       

      SAMPLE DATA:

       

      INPUT

      OUTPUT

      3

      6

      A:

            SPACES will InDeNt the CoDe

            No TaBs ArE iN the >> test << data

      goto A;

      B:

      goto B;

      7

      B:

      A:

      cin >> n;

          if(n<0) then

             goto A;

          else

             goto B;

      7

             A:

               TumbaBicho:

                 printf("goto TumbaBicho");

             printf("goto TumbaBicho");

           goto TumbaBicho;

      AA:

                 goto A;

      Scenario #1: 2

      Scenario #2: 7

      Scenario #3: 7

       

      CONSTRAINTS:

      1<=N<=10000

      1<= Length of string <= 1000


      Added by:David Moran
      Date:2012-05-05
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11494. Hard Launching

      Problem code: RPLH

       Felix, the cat, decided to play in the afternoon with some melons, he built a “melon launcher” and started pointing to targets. Soon he noticed that the melons sometimes overflies the victims or don't even get close to them.

       

      The melon launcher can be rotated so it can shoot from an angle from 0 to 45 degrees.

       

      Felix isn't good at maths, so he ask you to code a program that, given the target (in meters) distance and the speed (in meters / sec) you can give him the perfect angle for the melon launcher.

       

      The gravity to be considered is of 9.806 meters / sec^2

      PI value to be considered is 2*acos(0.0).

       

      INPUT:

      The first line of input will contain an integer T denoting the T test cases, then, T cases will follow. Each of the following line will contain two integer numbers Ta and Sp, denoting the distance of the target and the speed of the melon respectively.

       

      OUTPUT:

      Output the string “Scenario #i: “ where i is the test case you are analyzing followed by a single number D, denoting the Degrees necessary to do the launch, if the launching can't be done, output D as -1. the number must have a precision of 2 decimal digits.

       

      SAMPLE DATA:

       

      INPUT

      OUTPUT

      3

      10 10

      10 9

      8 9

      Scenario #1: 39.35

      Scenario #2: -1

      Scenario #3: 37.79

       

      CONSTRAINTS:

      0<Ta,Sp<10000


      Added by:David Moran
      Date:2012-05-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (main)

      11495. Ignore the bounds

      Problem code: RPLI

       Luis is seeing his son playing, he ask him gently in what the game consists, the boy replies “Its like this, you have a big number, a bound and a “mod” (the remainder of a division between a number and “mod”), the goal of the game is to discover the maximum sub-number you can create following this rules:”

      • The sequence must not decrease lower from the first digit taken.

      • The sequence chosen must not reach the bound. By example, if the first digit is 'd' and a bound 'k', the range you can take is between [d,min(d+k,9)]

      • You can start from any digit of a number.

      • For any given start point, you should look for the sub-numbers making the maximum sum applied to the mod operation.

      Luis, astonished by the explanation, request his son to give him and example, the boy then continues: “Suppose a number like this: 56789, a bound of 2, and a mod 10. you start with 5, being the bound of 2, this mean you can take up to the digit 7 (this means that you can always collect as many fives, sixes and sevens following the rules explained). The sub-number formed is of “5+6+7”, following the rules, we will have all others sub-numbers: “6+7+8” “7+8+9” “8+9” and “9”, after applying the operation, you will find that the maximum remainder of the sub-number's sum will be of “9”, made by the sub-number “9”.

       

      Luis is a former programmer now and he does not have the same ability he had years ago, please, help him in his task following the game previously defined.

       

      INPUT:

      The first line of input will contain an integer T denoting the T test cases, then, T cases will follow. Each of the following cases will contain a line with an integer L, a big number N in the range [10^(L-1),(10^L)-1], an integer K denoting the bound and the M that will be the mod of the whole operation.

       

      OUTPUT:

      Output the string “Scenario #i: “ where i is the test case you are analyzing followed by the maximum sum of the sub-sequence that can be formed.

       

      SAMPLE DATA:

       

      INPUT

      OUTPUT

      4

      7 1235678 2 10

      7 1235678 2 3

      3 679 2 20

      4 3457 2 10

      Scenario #1: 8

      Scenario #2: 2

      Scenario #3: 16

      Scenario #4: 9

       

       

      CONSTRAINTS:

      1<=L<=100000

      10^(L-1)<=N<(10^L)-1

      1<=K<=8

      1<=M<=45


      Added by:David Moran
      Date:2012-05-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11496. Just the distance

      Problem code: RPLJ


       Deisy is working on a robotics project, she wants to test the robot at the top before sending it to a very important company, she made a complete map for the robot, the robot is in the beta test, so it's a little dummy, the robot can't walk in diagonals, it only can walk in four directions; north, south, east or west, Deisy thinks someway this is a very bad thing, so, she wants to know if a diagonal is always the best path for the robot to go through.

       

      You are going to test the robot's diagonal steps versus the real steps the robot can make from a map A to a map B, having in consideration that the robot can start whenever in map A or B and arrives to the nearest point in B or A, also, Deisy can choose any point as a start for the robot (this point will belong to a map) and you must not compare the set of points where the robot belongs.

       

      Definition of a "map": a map is a set of stars (*) in adjacency, we define the adjacency as the four positions (north,south,east,west), meaning that a star is adjacent to other if they are communicated by one of these positions.

       

      INPUT:

      The first line of input will contain an integer T denoting the T test cases, then, T cases will follow. Each of the following cases will contain a line with an integer N, then N lines with N characters each will follow, denoting the map the robot will have to traverse from a set of points A to a set of points B, a free space will be denoted by '-' and a occupied space by some point will be denoted by a character '*', it is guaranteed that there will be always two maps.

       

      OUTPUT:

      Output the string “Scenario #i: “ where i is the test case you are analyzing followed by the option to choose, output 1 if the robot can go by its normal direction, 0 if going in diagonals is better.

       

      SAMPLE DATA:

       

      INPUT

      OUTPUT

      2

      5

      ---**

      ---**

      -----

      **---

      **---

      4

      *--*

      *--*

      *--*

      *--*

       

      Scenario #1: 0

      Scenario #2: 1

       

      Explanation of the first case: For each point in the matrix either you start in map A or B, traversing in diagonals will always be better, the output should be zero (0).

       

      Note: if Deisy find herself with equal distance between the diagonal and the "normal" steps of the robot, she will choose the "normal" steps as the best, in this case, the output should be 1 (normal is better).

       

      CONSTRAINTS:

      2<=N<=1000


      Added by:David Moran
      Date:2012-05-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11509. IPL - CRICKET TOURNAMENT

      Problem code: IPL1

       

       

      NOTE: This problem needs knowledge about the game cricket.

      Those who know the basics about IPL can skip the first paragraph.

      IPL is one of the famous cricket tournaments. Every match is played between two teams. Each team has eleven players. When the first team bats, the second team bowls. The second team’s aim is to get more score/runs than the first team and the first team’s aim is to defend their score. Each team can bat either till the end of 20 overs or until they lose 10 wickets. 6 balls are bowled every over.

      The possible things that can happen in any ball are dot-ball, 1 run, 2 runs, 3 runs, 4 runs, 5 runs, 6 runs, wide, no-ball, wicket. For any no-ball or a wide, 1 run is granted and the ball is not counted. Assume that these things can happen with equal probability.

      You are given the overs gone, the current score/wickets and the Target. Find the winning probability of the chasing team.

       

      Input Specifications:

      The first line consists of an integer t, denoting the number of test cases. Then for the next t lines, each test case consists of three inputs. The overs, current score and the target score.

       

      Output Specifications:

      For each test case output the winning probability(in percentage) of the chasing team.

      Note: The first two decimal places in it's representation should be printed without rounding


      Input Constraints:

      1<=t<=1000

      0.0 <= Overs <= 20.0

      0<= Score <= 300

      0<= Wickets <= 10

      Score <= Target <= 300 

       

      Sample Input:

      10

      19.4 129/9 129

      20.0 100/10 100

      19.5 0/9 100

      19.5 0/0 1

      0.0 0/0 300

      0.0 0/0 200

      0.0 0/0 100

      10.0 0/0 100

      10.0 0/5 100

      13.5 112/4 222

       

      Sample Output:

      100.00

      100.00

      0.00

      80.00

      18.02

      61.65

      97.60

      97.60

      55.49

      35.84 


      Added by:cegprakash
      Date:2012-05-10
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11515. I AM VERY BUSY

      Problem code: BUSYMAN


      I AM VERY BUSY


      You are actually very busy man. You have a big schedule of activities. Your aim is to do as much as activities as possible.

      In the given figure, if you go to date with crush, you cannot participate in the coding contest and you can’t watch the movie. Also if you play DotA, you can’t study for the exam. If you study for the exam you can’t sleep peacefully. The maximum number of activities that you can do for this schedule is 3. 

      Either you can 
      * watch movie, play DotA and sleep peacefully (or)
      * date with crush, play DotA and sleep peacefully



      Input Specifications:

      The first line consists of an integer t, the number of test cases. For each test case the first line consists of an integer n, the number of activities. Then the next n lines contains two integers m and n, the start and end time of each activity.

       

      Output Specifications:

      For each test case find the maximum number of activities that you can do.



      Input Constraints:

       1<=t<=10

      1<=n<=100000

      0<=start<end<=1000000

       

      Sample Input: (empty lines just for clarity)

      3

      3

      3 9

      2 8

      6 9

      4

      1 7

      5 8

      7 8

      1 8

       

      6

      7 9

      0 10

      4 5

      8 9

      4 10

      5 7

       

      Sample Output:

      1

      2

      3


      Added by:cegprakash
      Date:2012-05-11
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11516. VALIDATE THE MAZE

      Problem code: MAKEMAZE


       

       

      MAZE MAKING

       

      There are many algorithms to generate maze. (http://en.wikipedia.org/wiki/Maze_generation_algorithm). After generating the maze we’ve to validate whether it’s a valid maze or not. A valid maze has exactly one entry point and exactly one exit point (exactly 2 openings in the edges) and there must be atleast one path from the entry point to exit point.

      Given a maze, just find whether the maze is "valid" or "invalid".


      Input Specification:

      The first line consists of an integer t, the number of test cases. Then for each test case, the first line consists of two integers m and n, the number of rows and columns in the maze. Then contains the description of the matrix M of order mxn. M[i][j]=# represents a wall and M[i][j]='.' represents a space.

      Output Specification:

       For each test case find whether the maze is "valid" or "invalid".

       

      Input Constraints:


      1<=t<=10000

      1<=m<=20

      1<=n<=20


      Sample Input:

      6
      4 4
      ####
      #...
      #.##
      #.##
      5 5
      #.###
      #..##
      ##..#
      #.#.#
      ###.#
      1 1
      .
      5 1
      #
      #
      .
      .
      #
      2 2
      #.
      .#
      3 4
      #..#
      #.##
      #.##
      

      Sample Output:

      valid
      valid
      invalid
      valid
      invalid
      invalid
      

      Added by:cegprakash
      Date:2012-05-11
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set ()

      11517. GAMING ARENA

      Problem code: GAMARENA

       

      GAMIN ARENA


       

      Elgin and Hajee are planning to conduct gamindrome next day. As they have to connect all the computers, they need lan cables, hubs and wireless routers. They went to Richi street to purchase them. Unexpectedly hub was not available in any shop.

      Any lan cable can connect two computers. Any wireless router can connect atmost ‘k’ number of computers. Any computer can be connected to atmost one lan cable and atmost one wireless network. If a computer is connected to both lan and wireless, the connections get automatically bridged.

       

      They have n computers and their aim is to connect all the computers with minimum cost. So they have to buy minimum number of lan cables and wireless routers.

      The cost of of buying one lan cable is L and the cost of buying one wireless router is W. 

      Given n, k, L and W find the minimum cost needed to connect all the computers.

       

      Input Specification:

      The first line contains an integer t, the number of test cases. Each test case consists 4 integers n, k, L and W as defined above.

       

      Output Specification:

      For each test case find the minimum cost to connect all the computers.

      Input Constraints:

      1<=t<=1000

      1<=n<=1000

      2<=k<=1000

      1<=L<=1000

      1<=W<=1000

       

      Sample Input: 

       9

      1 4 8 6

      10 2 5 8

      5 4 9 9

      2 5 2 6

      7 3 3 6

      3 3 3 5

      6 4 7 2

      10 4 2 7

      5 3 10 8

      Sample Output:

      0

      57

      18

      2

      18

      5

      11

      20

      26

      3 2

      359 5 5 5
      146 2 5 3

      Added by:cegprakash
      Date:2012-05-12
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      11521. Dominant Strings

      Problem code: DOMINST


      Dominant Strings

      Given two strings s1 and s2, we say that s1 dominates s2 if the (multi)set of characters in s1 is a proper superset of the (multi)set of characters in s2. For instance, "acmicpc" dominates "camp", but it does not dominate "chimp" or "macpac". For a set S of strings, we call the strings in S which are not dominated by any string in S thedominant strings of S (even if they do not dominate any strings in S).

      Now, your task is simply to find all the dominant strings of a set of strings.

      Input

      The input contains a single set of strings, with one string per line. Each string consists of at least one and at most ten lower-case alphabetic characters. There will be at most 15000 strings, and no two strings will be identical. Input is terminated by end-of-file.

      Output

      Output consists of all dominant strings in the input set, in alphabetical order, one word per line.

      Example

      Input:

      acmicpc
      cccp
      macpac
      chimp
      camp

      Output:

      acmicpc
      chimp
      macpac

       


      Added by:Coach UTN FRSF
      Date:2012-05-13
      Time limit:35s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:http://uva.onlinejudge.org/external/107/10745.html









      SPOJ Problem Set (classical)

      11540. Training

      Problem code: TRAIN07

      Mirko and Slavko are training hard for the annual tandem cycling marathon taking place in Croatia. They need to choose a route to train on. 

      There are N cities and M roads in their country. Every road connects two cities and can be traversed in both 
      directions. Exactly N−1 of those roads are paved, while the rest of the roads are unpaved trails. Fortunately, the 
      network of roads was designed so that each pair of cities is connected by a path consisting of paved roads. In 
      other words, the N cities and the N−1 paved roads form a tree structure. 
      Additionally, each city is an endpoint for at most 10 roads total. 
      A training route starts in some city, follows some roads and ends in the same city it started in. Mirko and Slavko 
      like to see new places, so they made a rule never to go through the same city nor travel the same road twice. 
      The training route may start in any city and does not need to visit every city. 
      Riding in the back seat is easier, since the rider is shielded from the wind by the rider in the front. Because of 
      this, Mirko and Slavko change seats in every city. To ensure that they get the same amount of training, they must 
      choose a route with an even number of roads. 
      Mirko and Slavko's competitors decided to block some of the unpaved roads, making it impossible for them to 
      find a training route satisfying the above requirements. For each unpaved road there is a cost (a positive integer) 
      associated with blocking the road. It is impossible to block paved roads. Mirko and Slavko are training hard for the annual tandem cycling marathon taking place in Croatia. They need to 

      There are N cities and M roads in their country. Every road connects two cities and can be traversed in both 

      directions. Exactly N−1 of those roads are paved, while the rest of the roads are unpaved trails. Fortunately, the network of roads was designed so that each pair of cities is connected by a path consisting of paved roads. In other words, the N cities and the N−1 paved roads form a tree structure. 

      Additionally, each city is an endpoint for at most 10 roads total. 

      A training route starts in some city, follows some roads and ends in the same city it started in. Mirko and Slavko like to see new places, so they made a rule never to go through the same city nor travel the same road twice. The training route may start in any city and does not need to visit every city. 

      Riding in the back seat is easier, since the rider is shielded from the wind by the rider in the front. Because of this, Mirko and Slavko change seats in every city. To ensure that they get the same amount of training, they must choose a route with an even number of roads. 

      Mirko and Slavko's competitors decided to block some of the unpaved roads, making it impossible for them to find a training route satisfying the above requirements. For each unpaved road there is a cost (a positive integer) associated with blocking the road. It is impossible to block paved roads.

      Write a program that, given the description of the network of cities and roads, finds the smallest total cost needed to block the roads so that no training route exists satisfying the above requirements.

      Input

       

      The first line of input contains two integers N and M (2 ≤ N ≤ 1 000, N−1 ≤ M ≤ 5 000), the number of cities and the total number of roads. 

      Each of the following M lines contains three integers A, B and C (1 ≤ A ≤ N, 1 ≤ B ≤ N, 0 ≤ C ≤ 10 000), describing one road. The numbers A and B are different and they represent the cities directly connected by the road. If C=0, the road is paved; otherwise, the road is unpaved and C represents the cost of blocking it. 

      Each city is an endpoint for at most 10 roads. There will never be more than one road directly connecting a single pair of cities. 

       

      Output

      Output should consist of a single integer, the smallest total cost as described in the problem statement.

       

      Example

      Input:
      5 8 
      2 1 0 
      3 2 0 
      4 3 0 
      5 4 0 
      1 3 2 
      3 5 2 
      2 4 5 
      2 5 1
      
      Output:
      5
      Input:
      9 14 
      1 2 0 
      1 3 0 
      2 3 14 
      2 6 15 
      3 4 0 
      3 5 0 
      3 6 12 
      3 7 13 
      4 6 10 
      5 6 0 
      5 7 0 
      5 8 0 
      6 9 11 
      8 9 0 
      Output:
      48

      Added by:Stjepan Glavina
      Date:2012-05-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOI 2007









      SPOJ Problem Set (classical)

      11560. A Summatory

      Problem code: PUCMM210


      f(n) is defined as: f(n) = 13+23+33+...+n3, so it is the sum of the cubes of all natural numbers up to n.

      In this problem you are about to compute,

      f(1) + f(2) + f(3) + ... + f(n)

      Input

      The first line is an integer T(1 ≤ T ≤ 100,000), denoting the number of test cases. Then, T test cases follow.

      For each test case, there is an integer n(1 ≤ n ≤ 1,000,000) written in one line.

      Output

      For each test case output the result of the summatory function described above.

      Since this number could be very large, output the answer modulo 1,000,000,003.

      Example

      Input:
      3
      2
      10
      3

      Output:
      10
      7942
      46

      Added by:Olson Ortiz
      Date:2012-05-24
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Used in 2nd dominican ACM-ICPC Warm Up 2012 Competition in PUCMM









      SPOJ Problem Set (classical)

      11564. E 23 Stairs pattern

      Problem code: PUCMM215

      In this problem you will work on a plane, where the natural numbers are arranged in a stair pattern.

      Starting on coordinate (2,1) thru (2,23) are the first 23 natural numbers in sequence, 1 is in (2,1), 2 is in (2,2) and so on...,the next 23 natural numbers (24 to 46) are arranged from (2,24) thru (24,24), the next 23 from (25,24) thru (25,46), a stair pattern where each step is 24 numbers high, this pattern continues infinitely.

      Y-axis

      |                             48

      |  24 25 26 27 . . . 46 47

      |  23

      |   .

      |   .

      |   .   

      |  3

      |  2

      |  1

      _____________________________ X axis

      Input

      You will be given a series of queries that could be one or two integers per line.

      The last test case is 0 0.

      each integer N, Xi, Yi satisfy: 1 ≤ N, Xi, Yi, ≤ 1015.

      Output

      If the test case is one integer you have to output two comma separated integers denoting the coordinates (x,y) of the selected number, if there are two numbers you have to output one integer that corresponds to the integer that is located in those coordinates, if there is no number with such coordinates, output the string "No Number"

      Example

      Input:
      2
      2 7
      3 7
      0 0

      Output:
      2, 2
      7
      No Number

      Added by:Olson Ortiz
      Date:2012-05-24
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Used in 2nd dominican ACM-ICPC Warm Up 2012 Competition in PUCMM









      SPOJ Problem Set (classical)

      11573. A Famous ICPC Team

      Problem code: TEAM2

      Mr. B, Mr. G, Mr. M and their coach Professor S are planning their way to Warsaw for the ACM-ICPC World Finals. Each of the four has a square-shaped suitcase with side length Ai (1 <= i <= 4) respectively. They want to pack their suitcases into a large square box. The heights of the large box as well as the four suitcases are exactly the same. So they only need to consider the large box’s side length. Of course, you should write a program to output the minimum side length of the large box so that the four suitcases can be put into the box without overlapping.

      Input

      Each test case contains only one line containing 4 integers Ai (1<= i <=4, 1<= Ai <=1,000,000,000) indicating the side length of each suitcase.

      Output

      For each test case, display a single line containing the case number and the minimum side length of the large box required.

      Example

      Input:
      2 2 2 2
      2 2 2 1
      
      Output:
      Case 1: 4
      Case 2: 4
      

      Explanation

      For the first case, all suitcases have size 2x2. So they can perfectly be packed in a 4x4 large box without wasting any space.

      For the second case, three suitcases have size 2x2 and the last one is 1x1. No matter how to rotate or move, you could find the side length of the box must be at least 4.


      Added by:[Trichromatic] XilinX
      Date:2012-05-25
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FDU Local Contest 2012









      SPOJ Problem Set (classical)

      11574. A Famous Stone Collector

      Problem code: STONE2

      Mr. B loves to play with colorful stones. There are n colors of stones in his collection. Two stones with the same color are indistinguishable. Mr. B would like to select some stones and arrange them in line to form a beautiful pattern. After several arrangements he finds that it's very hard for him to enumerate all the patterns. So he asks you to write a program to count the number of different patterns.

      Two patterns are considered different, if and only if they have different number of stones or have different colors on at least one position.

      Input

      Each test case starts with a line containing an integer n indicating the kinds of stones Mr. B have. Following this is a line containing n integers - the number of available stones of each color respectively. All the input numbers will be nonnegative and no more than 100.

      Output

      For each test case, display a single line containing the case number and the number of different patterns Mr. B can make with these stones, modulo 1,000,000,007, which is a prime number.

      Example

      Input:
      3
      1 1 1
      2
      1 2
      
      Output:
      Case 1: 15
      Case 2: 8
      

      Explanation

      In the first case, suppose the colors of the stones Mr. B has are B, G and M, the different patterns Mr. B can form are: B; G; M; BG; BM; GM; GB; MB; MG; BGM; BMG; GBM; GMB; MBG; MGB.


      Added by:[Trichromatic] XilinX
      Date:2012-05-25
      Time limit:99s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Classical Problem, used in FDU Local Contest 2012









      SPOJ Problem Set (main)

      11575. A Famous Equation

      Problem code: EQ2

      Mr. B wrote an addition equation such as 123+321=444 on the blackboard after class. Mr. G removes some of the digits and makes it look like “1?3+??1=44?”. After Mr. B realizes some digits are missing, he wants to recover them. Unfortunately, there may be more than one way to recover the equation. For example “1?3+??1=44?” can be recovered to “123+321=444” or “143+301=444” and many other possible solutions. Your job is to determine the number of different possible solutions.

      Input

      Each test case describes a single line with an equation like a+b=c which contains exactly one plus sign + and one equal sign = with some digits are missing and replaced with ?. You may assume a, b and c are non-negative integers, and the length of each number is no more than 9. In the other words, the equation will contain three integers less than 1,000,000,000.

      Output

      For each test case, display a single line with its case number and the number of possible solutions to recover the equation.

      Example

      Input:
      7+1?=1?
      ?1+?1=22
      
      Output:
      Case 1: 3
      Case 2: 1
      

      Explanation

      There are three solutions for the first case:

      7+10=17, 7+11=18, 7+12=19

      There is only one solution for the second case:

      11+11=22

      Note that 01+21=22 is not a valid solution because extra leading zeros are not allowed.


      Added by:[Trichromatic] XilinX
      Date:2012-05-25
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:g201513's own problem, used in FDU Local Contest 2012









      SPOJ Problem Set (main)

      11576. A Famous King’s Trip

      Problem code: TRIP2

      Mr. B is the chief engineer in the Kingdom of FDUCS. Recently, the King asks Mr. B to develop a new plan of the road network in the country, since the existing one is so old that traffic jam often occurs. Unfortunately, Mr. B is now preparing for the ICPC World Final Contest so that he is quite busy. He asks his friends, Mr. G and Mr. M to help him finish that work. When Mr. B gets the solution from his friends, he realizes some problems: Mr. B forgot to specify the budget plan to Mr. G and Mr. M, thus the new solution contains too many new roads which the government cannot afford. After a precise calculation, Mr. B finds that he has just to delete exactly two roads in term of the financial facts (Of course, Mr. B will not delete more than two roads because he wants people in his country to have a convenient traffic).

      Can Mr. B delete two roads arbitrarily? The answer is negative. The King would like to take a travel on the new road system to review Mr. B's work. However, the King is so busy that he does not want to take travel with redundancy. That is, the King wants Mr. B to design a road system so that he can travel from the palace (in one city), pass each road exactly once, and then back to the palace. Moreover, during his travelling, the king must visit each city at least once too.

      Mr. B feels hard to satisfy the Kings demand by deleting two roads from the original design. As an ICPC candidate with unlimited potential, can you help him?

      Input

      For each test case, the first line contains two integers, n and m (1 <= n, m <= 200,000), indicating the number of cities in the Kingdom and the roads in Mr. B's original plan. Following this are m lines, each contains a pair of integers a and b. Each of them denotes a bidirectional road between city a and city b (1 <= a, b <= n and a != b), the number of cities are counted from 1. No two roads connect the same pair of cities.

      Output

      For each test case, if Mr. B can satisfy the Kings requirement, then output YES in the first line, otherwise, output NO. If the answer is YES, output two integers X and Y (X < Y) in the following line, specifying two roads that Mr. B should delete from the original design. X and Y are the indexes of roads in the input, counting from 1. If there are more than one possible answer, output the one that makes the pair of (X, Y) lexicographically smallest.

      Example

      Input:
      4 6
      1 2
      1 3
      1 4
      2 3
      2 4
      3 4
      
      Output:
      Case 1: YES
      1 6
      

      Added by:[Trichromatic] XilinX
      Date:2012-05-25
      Time limit:53s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:lcosvse's own problem, used in FDU Local Contest 2012









      SPOJ Problem Set (classical)

      11577. The Famous ICPC Team Again

      Problem code: MEDIAN3

      When Mr. B, Mr. G and Mr. M were preparing for the 2012 ACM-ICPC World Final Contest, Mr. B had collected a large set of contest problems for their daily training. When they decided to take training, Mr. B would choose one of them from the problem set. All the problems in the problem set had been sorted by their time of publish. Each time Prof. S, their coach, would tell them to choose one problem within a particular publish time interval. That is to say, if problems had been sorted in a line, each time they will choose one of them from a specified segment of the line.

      Moreover, when collecting the problems, Mr. B had also known an estimation of the difficulty of each problem. When he was asked to choose a problem, if he chose the easiest one, Mr. G would complain that “Hey, what a trivial problem!”; if he chose the hardest one, Mr. M would grumble that it took too much time to finish it. For addressing this dilemma, Mr. B decided to take the one with the medium difficulty. Therefore he needed a way to know the median number in the given interval of the sequence.

      Input

      For each test case, the first line contains a single integer n (1 <= n <= 100,000) indicating the total number of problems. The second line contains n integers xi (0 <= xi <= 1,000,000,000), separated by single space, denoting the difficulties of each problem, already sorted by publish time. The next line is a single integer m (1 <= m <= 100,000), specifying number of queries. Then m lines follow, each line contains a pair of integers, A and B (1 <= A <= B <= n), denoting that Mr. B needed to choose a problem between positions A and B (inclusively, positions are counted from 1). It is guaranteed that the number of items between A and B is odd.

      Output

      For each query, output a single line containing an integer which denotes the difficulty of the problem that Mr. B should choose.

      Example

      Input:
      5
      5 3 2 4 1
      3
      1 3
      2 4
      3 5
      5
      10 6 4 8 2
      3
      1 3
      2 4
      3 5
      
      Output:
      Case 1:
      3
      3
      2
      Case 2:
      6
      6
      4
      

      Added by:[Trichromatic] XilinX
      Date:2012-05-25
      Time limit:31s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Classical Problem, used in FDU Local Contest 2012









      SPOJ Problem Set (classical)

      11578. A Famous City

      Problem code: CITY2

      After Mr. B arrived in Warsaw, he was shocked by the skyscrapers and took several photos. But now when he looks at these photos, he finds in surprise that he isn't even able to point out the number of buildings in it. So he decides to work it out as follows:

      - divide the photo into n vertical pieces from left to right. The buildings in the photo can be treated as rectangles, the lower edge of which is the horizon. One building may span several consecutive pieces, but each piece can only contain one visible building, or no buildings at all.

      - measure the height of each building in that piece.

      - write a program to calculate the minimum number of buildings.

      Mr. B has finished the first two steps, the remaining comes to you.

      Input

      Each test case starts with a line containing an integer n (1 <= n <= 100,000). Following this is a line containing n integers - the height of building in each piece respectively. Note that zero height means there are no buildings in this piece at all. All the input numbers will be nonnegative and less than 1,000,000,000.

      Output

      For each test case, display a single line containing the case number and the minimum possible number of buildings in the photo.

      Example

      Input:
      3
      1 2 3
      3
      1 2 1
      
      Output:
      Case 1: 3
      Case 2: 2
      

      Explanation

      The possible configurations of the samples are illustrated below:


      Added by:[Trichromatic] XilinX
      Date:2012-05-25
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FDU Local Contest 2012









      SPOJ Problem Set (classical)

      11579. Two Famous Companies

      Problem code: COMPANYS

      In China, there are two companies which offer the internet service for the people from all cities: China Telecom and China Unicom. They both are planning to build cables between cities. The government wants to connect all the cities in minimum costs of course. So the minister of finance Mr. B wants to choose some of the cable plans from the two companies and calculate the minimum cost needed to connect all the cities. Mr. B knows that there are N-1 cables should be built in order to connect all N cities of China. For some political reason, Mr. B should choose K cables from the China Telecom and the rest N-1-K cables from the China Unicom. Your job is to help Mr. B determine which cables should be built and the minimum cost to build them. You may assume that the solution always exists.

      Input

      Each test case starts with a line containing the number of cities N (1 <= N <= 50,000), number of cable plans M (N-1 <= M <= 100,000) and the number of required cables from China Telecom K (0 <= K <= N-1). This is followed by M lines, each containing four integers a, b, c, x (0 <= a, b <= N-1, a != b, 1 <= c <= 100, x=[0,1]) indicating the pair of cities this cable will connect, the cost to build this cable and the company this cable plan belongs to. x=0 denotes this cable plan belongs to China Telecom and x=1 denotes this cable plan is from China Unicom.

      Output

      For each test case, display the case number and the minimum cost of the cable building plan.

      Example

      Input:
      2 2 1
      0 1 1 1
      0 1 2 0
      2 2 0
      0 1 1 1
      0 1 2 0
      
      Output:
      Case 1: 2
      Case 2: 1
      

      Explanation

      In the first case, there are two cable plans between the only two cities, one from China Telecom and one from China Unicom. Mr. B needs to choose the one from China Telecom to satisfy the problem requirement even the cost is higher.

      In the second case, Mr. B must choose the cable from China Unicom, which leads the answer to 1.


      Added by:[Trichromatic] XilinX
      Date:2012-05-25
      Time limit:53s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FDU Local Contest 2012









      SPOJ Problem Set (classical)

      11580. A Famous Game

      Problem code: PRLGAME2

      Mr. B and Mr. M like to play with balls. They have many balls colored in blue and red. Firstly, Mr. B randomly picks up N balls out of them and put them into a bag. Mr. M knows that there are N+1 possible situation which the number of red balls are ranged from 0 to N, and we assume the possibilities of the N+1 situation are the same. But Mr. M does not know which situation occurs. Secondly, Mr. M picks up P balls out of the bag and examines them. There are Q red balls and P-Q blue balls. The question is, if he picks one more ball out of the bag, what is the possibility that this ball is red.

      Input

      Each test case contains only one line with three integers N, P and Q (2 <= N <= 100,000, 0 <= Q <= P <= N-1).

      Output

      For each test case, display a single line containing the case number and the possibility of the next ball Mr. M picks out is red. The number should be round to four decimal places.

      The judge is "ignoring extra whitespaces".

      Example

      Input:
      3 0 0
      4 2 1
      
      Output:
      Case 1: 0.5000
      Case 2: 0.5000
      

      Explanation

      For example as the sample test one, there are three balls in the bag. The possibilities of the four possible situations are all 0.25. If there are no red balls in the bag, the possibility of the next ball are red is 0. If there is one red ball in the bag, the possibility is 1/3. If there are two red balls, the possibility is 2/3. Finally if all balls are red, the possibility is 1. So the answer is 0*(1/4)+(1/3)*(1/4)+(2/3)*(1/4)+1*(1/4)=0.5.


      Added by:[Trichromatic] XilinX
      Date:2012-05-25
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:lcosvse's own problem, used in FDU Local Contest 2012









      SPOJ Problem Set (classical)

      11582. A Famous Grid

      Problem code: SPIRALGR

      Mr. B has recently discovered the grid named "spiral grid". Construct the grid like the following figure. (The grid is actually infinite. The figure is only a small part of it.)

      Considering traveling around it, you are free to any cell containing a composite number or 1, but traveling to any cell containing a prime number is disallowed. You can travel up, down, left or right, but not diagonally. Write a program to find the length of the shortest path between pairs of nonprime numbers, or report it's impossible.

      Input

      Each test case is described by a line of input containing two nonprime integer 1 <=x, y<=10,000.

      Output

      For each test case display its case number followed by the length of the shortest path or impossible in one line.

      Example

      Input:
      1 4
      9 32
      10 12
      
      Output:
      Case 1: 1
      Case 2: 7
      Case 3: impossible
      

      Added by:[Trichromatic] XilinX
      Date:2012-05-25
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM/ICPC World Finals 2012 - Dressing Rehearsal Contest, also used in FDU Local Contest 2012









      SPOJ Problem Set (classical)

      11601. With a Pit of Death

      Problem code: DOJO

      Leo is training his martial arts in byteland's dojo.
      The dojo is a rectangular ( n × m ) area with a pit of death, a square located at (i, j), where 1 <= i <= n, and 1 <= j <= m.
      Every night, battles are very hard and the dojo is destructed, and reconstructed during the day around the pit.
      Every evening, Leo's first mission is to make in place tatamis ( 2 × 1 ) in the new dojo.
      Tatamis should cover the whole dojo except the pit of death.
      Sometimes it's possible, sometimes not!


      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are four integers n, m, i and j.

      Output

      For each test case, print the answer of the problem : "Possible." or "Impossible.".

      Example

      Input:
      2
      3 3 2 2
      3 3 1 2
      Output: Possible.
      Impossible.

      Constraints

      1 <= T <= 1 000
      1 <= i <= n <= 32
      1 <= j <= m <= 102000

       

      dojo


      Added by:Francky
      Date:2012-05-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      11603. Polynomial f(x) to Polynomial h(x)

      Problem code: POLTOPOL


      Given polynomial of degree d, f(x)=c0+c1x+c2x2+c3x3+...+cdxd

      For each polynomial f(x) there exists polynomial g(x) such that:

      -> f(x)=g(x)-g(x-1) for each integer x

      -> g(0)=0

      Your task is to calculate polynomial h(x)=g(x)/x

      (Note : degree of polynomial h(x) = degree of polynomial f(x))

      Input

      The first line of input contain an integer T, T is number of test cases (0<T≤104)

      Each test case consist of 2 lines:

      - First line of the test case contain an integer d, d is degree of polynomial f(x) (0≤d≤18)

      - Next line contains d+1 integers c0,c1,...,cd, separated by space, represent the coefficient of polynomial f(x) (-231<c0,c1,...,cd<231 and cd≠0)

      Output

      For each test case, output the coefficient of polynomial h(x) separated by space. Each coefficient of polynomial h(x) is guaranteed to be an integer.

      Example

      Input:
      5
      0
      13
      1
      -1 2
      1
      0 2
      2
      2 -5 9
      3
      23 9 21 104
      
      Output:
      13
      0 1
      1 1
      1 2 3
      31 41 59 26

      ---------------------------------------------------------------
      Explanation for the first test case :
      f(x)=13
      g(x) that satisfy: g(x)-g(x-1)=f(x)=13 and g(0)=0 is: g(x)=13x
      h(x)=g(x)/x so h(x)=13
      output : 13
      Explanation for the second test case :
      f(x)=-1+2x
      g(x) that satisfy: g(x)-g(x-1)=f(x)=-1+2x and g(0)=0 is: g(x)=x2
      h(x)=g(x)/x so h(x)=x=0+1x
      output : 0 1
      Explanation for the third test case :
      f(x)=0+2x
      g(x) that satisfy: g(x)-g(x-1)=f(x)=2x and g(0)=0 is: g(x)=x+x2
      h(x)=g(x)/x so h(x)=1+1x
      output : 1 1
      ---------------------------------------------------------------

       

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2012-05-26
      Time limit:20s
      Source limit:20000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11604. The return of the Cake

      Problem code: REBOUND

      It is well known that, in byteland, when you throw a cake, the angle of reflexion is not the angle of incidence. Measured from the ground, the angle is the double, in byteland!

      rebound

      You stand at point A(0, z), and you want to throw a cake in Leo's face. Leo stands at B(x, y) and is a very dangerous man, so you decide to use the ground in order to make your cake rebound.

      Your shot is precise only if you can use an integer value t in the intervall [0, x], in order to reflect on C(t, 0). Sometimes it's possible, sometimes not!

      Input

      The input begins with the number T of test cases in a single line. In each of the next T lines there are three integers x, y and z, explaining the locations : you A(0, z), Leo B(x, y).

      Output

      For each test case, find and print the only integer t such 0 <= t <= x, that allow this perfect shot. If it's not possible, output "Not this time.".

      Example

      Input:
      3
      5 4 1
      6 5 2
      7 3 1
      
      Output:
      2
      Not this time.
      3
      

      Comment : the last case is the one illustrated above.

      Constraints

      1 < T < 100 000
      0 < x < 1 000 000 000
      0 < y < 1 000 000 000
      0 < z < 1 000 000 000

      Added by:Francky
      Date:2012-05-26
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      11613. Aho-Corasick Trie

      Problem code: AHOCUR

      The Aho–Corasick string matching algorithm is a string searching algorithm invented by Alfred V. Aho and Margaret J. Corasick. It is a kind of dictionary-matching algorithm that locates elements of a finite set of strings (the "dictionary") within an input text. It matches all patterns simultaneously.  

      The Algorithm described above, requires an input file generator. The generator generates a text of length L, by choosing L characters randomly. Probability of choosing each character is given as priori, and independent of choosing others.  Now, given a set of patterns, calculate the probability of a valid program generating “no”.

      Input

      First line contains an integer T, the number of test cases. Each case starts with an integer K, the number of pattern strings. Next K lines each contain a pattern string, followed by an integer N, number of valid characters.  Next N lines each contain a character and the probability of selecting that character, pi. Next an integer L, the length of the string generated. The generated text can consist of only the valid characters, given above.  There will be a blank line after each test case.

      Output

      For each test case, output the number of test case, and the probability of getting a “no”.

      Constraints

      • T  ≤ 100
      • K ≤ 40
      • Length of each pattern string is between 1 and 20
      • Each pattern string consists of only alphanumeric characters (‘a’ to ‘z’, ‘A’ to ‘Z’,’0’ to ‘9’)
      • Valid characters are all alphanumeric characters
      • ∑p= 1
      • L ≤ 100

      Example

      Input 
      2
      1
      a
      2
      a 0.5
      b 0.5
      2
       
      2
      ab
      ab
      2
      a 0.2
      b 0.8
      2
      
      
      Output:
      Case #1: 0.250000
      Case #2: 0.840000
      2
      1
      a
      2
      a 0.5
      b 0.5
      2
       
      2
      ab
      ab
      2
      a 0.2
      b 0.8
      2


      Added by:Chen Xiaohong
      Date:2012-05-27
      Time limit:3s
      Source limit:80000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Data Enhanced from Classic Problem by Manzurur Rahman Khan









      SPOJ Problem Set (classical)

      11642. MAKESUM

      Problem code: MAKESUM

      Pairwise sums of n numbers  (i.e. NC2 sums)are given in sorted order.

      You need to identify the numbers and print then. If there are several solutions print the lexographically smallest one.

      The Output should have natural numbers only.

      Input

      NC2 <=50

      NC2 numbers each <=10^5

      Output

      lexographically smallest set of numbers

      Example

      Input:
      1
      2 
      
      Output:
      1 1

      Input:
      3
      2 2 2 
      
      Output:
      1 1 1
      Input:
      6
      2 2 2 3 3 3
      
      Output:
      1 1 1 2
      Input:
      1
      4 
      
      Output:
      1 3
      (here 2 2 and 3 1 are also possible solutions but we have to print the lexographically smallest one)

      Added by:priyamehtanit
      Date:2012-06-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      11676. Counting diff-pairs

      Problem code: CPAIR2


      You are given sequence A of N integers. You are also given integer K and M queries. Each query consists of two integers l, r. For each query output number of pairs i, j such that l <= i < j <= r and abs(A[i] - A[j]) >= K.

      Indexing starts with 1.

      N <= 50000

      M <= 50000

      1 <= A[i] <= 100000

       

      NOTE: All tests are randomly generated.

      Input

      First line of input contains integers N, M, K in this order.

      Second line contains N integers representing array A.

      Next M lines describe queries.

      Output

      Output answer for each query.

      Example

      Input:
      3 1 2
      1 2 3
      1 3
      Output: 1

      Added by:Buda IM
      Date:2012-06-03
      Time limit:1s-15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      11695. A Summatory (HARD)

      Problem code: ASUMHARD

      f(n) is defined as: f(n) = 1k+2k+3k+...+nk, so it is the sum of the k-th power of all natural numbers up to n.

      In this problem you are about to compute,

      f(1) + f(2) + f(3) + ... + f(n)

      Input

      The first line is an integer T(1 ≤ T ≤ 54,321), denoting the number of test cases. Then, T test cases follow.

      For each test case, there are two integers n(1 ≤ n ≤ 123,456,789) and k(0 ≤ k ≤ 321) written in one line, separated by space.

      Output

      For each test case output the result of the summatory function described above.

      Since this number could be very large, output the answer modulo 1,234,567,891.

      Example

      Input:
      5
      2 3
      10 3
      3 3
      100 0
      100 1 Output: 10
      7942
      46
      5050
      171700

      Warning: A naive algorithm may not run in time

       

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2012-06-07
      Time limit:12s
      Source limit:12345B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PYTH 3.2.3 n
      Resource:Harder version of A Summatory problem.









      SPOJ Problem Set (classical)

      11707. Wrong directions

      Problem code: WRONG

      Farmer John has just purchased a fancy new programmable tractor. To make the tractor move, he types in a string of length N

      (1 <= N <= 100,000) consisting of only the characters F, L, and R. Each 'F' instructs the tractor to move forward one unit,

      and the characters 'L' and 'R' result in left and right turns of 90 degrees, respectively. The tractor starts out at the origin (0,0)

      facing north.

      After programming his tractor by typing in his intended command string, FJ remembers that he typed exactly one character in

      the command string incorrectly, but he can't remember which one!For example, he might have typed 'F' or 'L' when his intended

      string contained the character 'R'. Please compute the number of different locations in the plane at which the tractor might

      end up as a result (the direction the tractor faces in its final location does not matter).

      Input format: 
      * Line 1: Farmer John's intended command string.
      SAMPLE INPUT:
      FF
      INPUT DETAILS:
      Farmer John wants the tractor to advance forward twice, ideally ending at position (0,2).
      OUTPUT FORMAT: 
      * Line 1: The number of positions at which the tractor might end up,given that FJ mistypes one of the characters in his command string.
      SAMPLE OUTPUT
      3
      OUTPUT DETAILS:
      There are 4 possible mistyped sequences: FL, FR, LF, an RF.  These will land the tractor at (0,1), (0,1), (-1,0), and (1,0) respectively, 
      a total of 3 distinct locations.

      Added by:Ikhaduri
      Date:2012-06-09
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Usaco march 2012









      SPOJ Problem Set ()

      11712. Red Cross Hospital

      Problem code: REDCROSS


      The Red Cross is a humanitarian and neutral organization that strives to provide assistance to victims of civil wars and other situations of serious violence.

      Recently, Nlogônia entered into a political crisis that culminated in a great civil war. This war wrecked Dozens of innocent communities across the country. Seeing the calamity situation in which the country joined, the Red Cross decided to help the population in all affected regions in Nlogônia.

      For this, it was decided that a hospital base will be installed to support the Red Cross in the country. However, the summit do not know where to build the base of Red Cross hospital. You and your team were hired to tell the Red Cross the position that they must build the hospital, with the constraint that the distance to the farthest community from the hospital is as small as possible.

      Input

      The input file consists of several test cases. For each test case, the first line contains the number of affected communities N to be served. Each of the following N lines contains a localization of each community. Localization is represented by decimal coordinates X and Y. After the first test case will be another line with a new test case defined by number of communities N. The input never contains repeated coordinates for each community in each test case and the input ends with N=0.

      Suppose:
      0<=N<=100000
      (-100000,-100000)<=X,Y<=(100000, 100000)

      Output

      For each test case of your program prints just a one line with two decimal number separated by
      commas indicating the optimum location for the construction of the base hospital, regardless of the
      area have a built space. Each coordinate must be printed with four decimal place of accuracy.

      Example

      Input:
      2
      -1 0
      1 0
      4
      0.5  0.5
      0.5 -0.5
      0.0  0.5
      0.0 -0.5
      0
      Output:
      0.0000, 0.0000
      0.2500, 0.0000

      Added by:Diogo Soares [UFAM]
      Date:2012-06-11
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11718. Boa viagem, Roim

      Problem code: ROIM


      Computer Engineering student Roim is getting ready for a trip to Mexico. For that, he has studied the airplane network, so he knows the details of all R regular flights currently in operation on all of the N available airports. Unfortunately, one of his school mates is very annoying and keeps saying the same stuff to him all the time. 

      To solve that issue, he will organize two different flight plans: one for the team and one for the annoying guy. The condition is that the flight plans may not contain the same flight (note that it is possible for both to pass through the same airport, and that the same flight may not be used by both even if the times are different). As this may not be possible using only regular flights, he has also considered using some of the C flights chartered by travel agencies, but he'd like to keep those to a minimum as they usually suffer from large delays. Of course, as long as the least number of chartered flights is picked, Roim will pick the plans with the least total cost (defined as the sum of the costs of all flights used).

      Input

      The input consists of several test cases. On the first line of a test case are three integers N (2 ≤ N ≤ 225), R and C (0 ≤ R+C ≤ N(N-1)/2) separated by spaces. The starting airport is 0, and the destination is N-1.

      The next R lines contain integers a, b (0 ≤ a, b ≤ N-1), c (1 ≤ c ≤ 100), meaning that there exists a one-way regular flight between airports a and b, with cost c. The following C lines give details for chartered flights in the same manner. There is a blank line at the end of each test case. The last test case is followed by a line containing three zeros.

      You may assume that any pair of cities is only connected in at most a single direction by a single flight.

      Output

      If it is possible to make the plans, print two integers separated by spaces. The first should be the minimum amount of chartered flights used, and the second is the total cost of the solution.

      If it's impossible that both the team and the guy get to their destination, print "Boa viagem, Roim" instead.

      Example

      Input:
      4 5 0
      0 1 1
      1 3 5
      0 2 5
      1 2 1
      2 3 1

      4 4 1
      0 1 2
      1 3 2
      0 2 2
      1 2 1
      2 3 2

      2 1 0
      0 1 10

      0 0 0

      Output: 0 12
      1 8
      Boa viagem, Roim

      Added by:Fernando Fonseca [ITA]
      Date:2012-06-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11723. HELP ABHISHEK(version-II)

      Problem code: COMPLEX2

      ABHISHEK is weak of mathematics he is not able to solve the sequences frequently. 

      So he invited topcoders to develop a program for solving the sequence. He managed to solve the other kind of sequences except one kind.

      The sequence description is as follows:

      (x-w)(x-w^2)(x-w^3)(x-w^4).............(x-w^n-1)

      here x is a number and w is nth root of unity. 

      Input

      first line contain number of test cases t. Then t line follow x and n. x and n seprated by a space.

      Constraints:-

      2<=x<=1000

      2<=n<=1000

      t<=410

      Output

      print result per case according to above sequence and also keep in mind if there is any term in 

      decimal then write it in form of  num/deno. see the I/O for further detail

      Example

      Input:

      1

      5 10

      Output:

      9765624/4

      warning:

      Time limit is too strict so optimise your solution as you can.First try the tuorial version of this

      http://www.spoj.pl/problems/COMPLEX1/ 

      Added by:Abhishek Mishra
      Date:2012-06-17
      Time limit:0.800s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:My own









      SPOJ Problem Set (classical)

      11726. Asteriod Rangers

      Problem code: ASTERRAN

      The year is 2112 and humankind has conquered the solar system. The Space Ranger Corps have set up bases on any hunk of rock that is even remotely inhabitable. Your job as a member of the Asteroid Communications Ministry is to make sure that all of the Space Ranger asteroid bases can communicate with one another as cheaply as possible. You could set up direct communication links from each base to every other base, but that would be prohibitively expensive. Instead, you want to set up the minimum number of links so that everyone can send messages to everyone else, potentially relayed by one or more bases. The cost of any link is directly proportional to the distance between the two bases it connects, so this doesn't seem that hard of a problem.

      There is one small difficulty, however. Asteroids have a tendency to move about, so two bases that are currently very close may not be so in the future. Therefore as time goes on, you must be willing to switch your communication links so that you always have the cheapest relay system in place. Switching these links takes time and money, so you are interested in knowing how many times you will have to perform such a switch.

      A few assumptions make your task easier. Each asteroid is considered a single point. Asteroids always move linearly with a fixed velocity. No asteroids ever collide with other asteroids. Also, any relay system that becomes optimal at a time t 0 will be uniquely optimal for any time s satisfying t < s < t + 10-6. The initial optimal relay system will be unique.

       

      Input 

      Each test case starts with a line containing an integer n (1<n<51) indicating the number of asteroid bases. Following this are n lines, each containing six integers x, y, z, vx, vy, vz. The first three specify the initial location of an asteroid (- 151 x, y, z < 151 ), and the last three specify the x, y, and z components of that asteroid's velocity in space units per time unit (- 100 <= vx, vy, vz  <= 100).

       

      Output 

      For each test case, display a single line containing the case number and the number of times that the relay system needs to be set up or modified.

       

      Sample Input 

       

      3
      0 0 0 0 0 0
      5 0 0 0 0 0
      10 1 0 -1 0 0
      4
      0 0 0 1 0 0
      0 1 0 0 -1 0
      1 1 1 3 1 1
      -1 -1 2 1 -1 -1

       

      Sample Output 

      Case 1: 3
      Case 2: 3


      Added by:Chen Xiaohong
      Date:2012-06-18
      Time limit:45s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ICPC Finals 2012









      SPOJ Problem Set (classical)

      11736. Prime Time

      Problem code: PTIME

      For your math homework this week your teacher gave you five large numbers and asked you to find their prime factors. However these numbers aren't nearly large enough for someone with knowledge of programming like yourself. So you decide to take the factorial of each of these numbers. Recall that N! (N factorial) is the product of the integers from 1 through N (inclusive). It’s your job now to create a program to help you do your homework.

      Input

      Each test case contains a number N (2 ≤ N ≤ 10000).

       

      Output

      The output should contain a line representing the prime factorization of the factorial given number, which should be of the form: p1^e1 * p2^e2 * ... * pk^ek where p1, p2, ..., pk are the distinct prime factors of the factorial of the given number in increasing order, and e1, e2, ..., ek are their exponents.

       

      Example

       

      Input:
      10
      
      Output:
      2^8 * 3^4 * 5^2 * 7^1
      

      Added by:Amlesh Jayakumar
      Date:2012-06-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:DWITE Programming Contest 2012 (Own Problem)









      SPOJ Problem Set (classical)

      11756. Teaming up for the competition

      Problem code: PONY5

      Since the Iron Pony competition was such fun last year, the ponies have decided to host a similar event this year, but this time it would be in teams. When each pony arrives at the event, they receive a number between 1 and 10^18. It is possible that some ponies receive the same number. Once everypony arrives, Miss Mayor will announce a number X and how to determine which team a pony is on - the pony takes their given number and looks at the result modulo X. That is their team number.

      Dr. Whooves is at the event with a group, and he was wondering about the numbers X that would let his entire group be on the same team. Dr. Whooves likes big numbers, so he is going to suggest to Miss Mayor the number X which is the largest number that would let his entire group be on the same team.

      Your goal is to determine what number Dr. Whooves suggested to Miss Mayor. But because the number might be really big, if there is a valid X larger than 10^18, just print "I can't count that high".

      Input

      The input will contain one line with a number T, the number of test cases in the file.

      On the next T lines, one for each of the cases. The format of the case is "Case #i: N a1 a2 ... aN" where N is the number of ponies in Dr. Whooves's group, and each a_j is the number given to a pony in his group.

      Output

      There will be T lines in your output, one for each of the test cases in the input. The output format for case i is "Case #i: X" where X is the number that Dr. Whooves suggests to Miss Mayor, unless X is too large, and then you print "I can't count that high" [see sample output]

      Example

      Input:
      2
      Case #1: 3 178 928 440
      Case #2: 1 1000000000000000000
      
      Output:
      Case #1: 2
      Case #2: I can't count that high
      

      Limits

      1 <= N <= 1000000 (10^6)
      Warning: Large input files

      Added by:Alex Anderson
      Date:2012-06-21
      Time limit:0.400s-0.899s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:My own problem









      SPOJ Problem Set (classical)

      11769. Kind and gently

      Problem code: RPLK

       Giselle is working on her house, as her husband won't be able to help in the task, she gently asks you for help, the task is very simple, Giselle wants to build some stairs that communicate two floors in the house, the stairs will be made of W segments of wooden, she is very confident on building the stairs, but she wants to build the stairs with some separation between steps. As you know, the end of a step is overlapped by the beginning of the other, and so on, between steps there are a single separation, as Giselle is very conservative, she wants to build the stairs using at most W segments of wood.

       

      The next image will help you to understand the task

       

      Image and video hosting by TinyPic

      As you can see in the image, there is a single separation between each step relating to the height and the width of every step.

       

      Giselle wants to build stairs using E pieces of wood that she wants to cut into at most W steps. You can only cut vertically and can't rotate the given pieces. Each step's width must be exactly M+1. M is the overlap and 1 is a constant width left placing feet.

       

      INPUT:

      The first line of the test data will start with an integer T representing the T test cases, then, T cases will follow.

      Each case starts with four positive integers (E,M,K,W) denoting E pieces of wood, M meters of overlap, K height of separator between each step and W, the maximum number of steps that can be cut out. Next, E lines will follow, each with two integers Eh and Ew representing respectively the height and the width of each piece of wood Giselle has.

       

      OUTPUT:

      You must output the string “Scenario #i: “ where i is the number of test case you're analyzing (starting by 1), followed by the maximum amount of height that you can possibly build

       

       

      INPUT

      OUTPUT

      3

      5 1 1 3

      6 2

      5 10

      4 20

      3 15

      1 1

      3 1 0 5

      3 15

      2 20

      1 60

      2 1 1 25

      15 10

      12 10

      Scenario #1: 19

      Scenario #2: 15

      Scenario #3: 145

       

      Explanation of the first case:

      You can only cut the segment of width 6 into one piece, but the 5 segment of width 10 you can cut it into 5 pieces, as you only need 3 pieces to use, the maximum height will be of 6+5+5+3 = 19

       

      CONSTRAINTS:

       

      (1 <= Width and Height of each wooden piece <= 1000) = WiHi

       

      Small input (40%)

      1<= T <=200

      1<= {E,K,M} <=100

      WiHi <= M <= 100

      1<= W <=100

       

      Large Input (60%)

      1<= T <=10

      1<= {E,K} <=100,000

      WiHi <= M <= 1,000

      1 <= W <= 10,000


      Added by:David Moran
      Date:2012-06-22
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11770. Lifesavers

      Problem code: RPLL


       

       German is the chief of the Rescuers and Principal Lifesavers of the ocean (RPL), he is in charge of commanding the search of survivors on a range given after a ship sinks, this range is established from the time that the ship sunk, he will always know this value, because he is magnificent in maths, however, he isn't good calculating the perfect searching range, this causes problem in rescuing survivors as the ship may exceed the limit of the area of searching.

       

      It is known that German will always send three ships to make the rescue effective, as he can't send all his ships, he wants to maximize the area of the three ships covers. The ships of German aren't sophisticated, so they will be going on a single direction (always) and a constant speed. The ships moves every unit of time.

       

      We say that an area is covered when the area made by the three points (triangular area) is lesser or equal than the maximum area that German knows.

       

      German will give you the initial coordinates of all three ships (given in 2D), the direction the ship will be going and the speed per hour. The direction of the rescuer ship will always be to north, south, east or west and the maximum area of search. Please have in count that the area covered by the three ships must NOT exceed the area that German gives to you.

       

      INPUT:

      The first line of the test data will start with an integer T representing the T test cases, then, T*4 Lines will follow, each of the following lines will contain, respectively, the maximum area of searching, the next three lines will contain, each, three integers and a string, denoting the coordinates the ship is in, the direction and the speed.

       

      OUTPUT:

      You must output the string “Scenario #i: “ where i is the number of test case you're analyzing, followed by the time that

      the three ships will cover the maximum possible area (without exceeding it). Time will always be discrete.

       

      INPUT

      OUTPUT

      2

      150

      1 4 north 2

      2 0 south 2

      3 1 east 2

      12

      0 -2 north 1

      0 0 north 2

      0 0 east 3

      Scenario #1: 5

      Scenario #2: 2

       

      CONSTRAINTS:

      1 <= T <= 100

      -10^6 <= X,Y <= 10^6

      1 <= Speed <= 10

       

      Small Input (30%)

      For the “small” input, the triangles will always be rectangled triangles, making the area of them easier to calculate.

      1 <= Max_Area_Of_Searching <= 10^3

      Large Input (70%)

      Points will form any triangle, time-limit is heavier on these files.

      10^3 <= Max_Area_Of_Searching <= 10^9

       

      Explanation of the second sample:

      At hour two, the ship 1 will be at position (0,0), the ship 2 will be at position (0,4) and the ship 3 will be in (6,0), computing the area of a triangle, we will have a value of 12, as we know that there is no other possible area that satisfies the maximum without exceeding it, we output 2.

       

      It is guaranteed that all three ships will always be distancing themselves, then, the next area will always be bigger.


      Added by:David Moran
      Date:2012-06-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11771. Mountain Cave

      Problem code: RPLM


       

       Charlie is picking some precious stones in a cave, this cave is known worldwide by the stones in it, however, this cave is very delicate and the minimum movement causes an instant collapse, Charlie knows the times that the tunnels will be free (as the instant collapses can free some tunnels) or covered by a pile of stones.

       

      In his backpack, Charlie has some magical hammers that he carries for emergency, in some expeditions he won't have these hammers, but in others he will. The hammer causes an instant opening of any pile of stones blocking his way.

       

      It is also known that Charlie travels some distance d in a time t from room i to room j, and the tunnel connecting them will be free from time x to time y. Charlie can return whenever he wants, so, traveling from room j to room i will be symmetric.

       

      Charlie doesn't have infinite hammers, so, when he use one, the hammer will break, making it useless.

       

      In addition, if Charlie knows that the tunnel will open in a time X, he can choose to stay until the path opens or use a magical hammer to go through the tunnel.

       

      Given that information, your task is to find the minimum time with the minimum distance that Charlie can go from the entrance (0) to the center of the cave (V-1)

       

      INPUT:

      The first line of the test data will start with an integer T representing the T test cases, then, T cases will follow, each of the cases starts with three integers, V E and M, denoting, respectively, the number of the rooms on the cave, the numbers of tunnels in the cave and the number of hammers Charlie will carry, the next E lines will contain six integers, denoting, respectively, the origin room i, the destiny room j, opening time x, collapse time y, distance z, and time t.

       

      OUTPUT:

      You must output the string “Scenario #i: “ where i is the number of test case you're analyzing, followed by the minimum time and the minimum distance associated to it, if Charlie isn't able to arrive to the V-1 room, output -1.

       

      INPUT

      OUTPUT

      4

      6 6 2

      0 1 1 18 3 3

      0 2 1 12 4 4

      0 4 1 3 5 5

      2 3 1 8 2 2

      3 4 1 5 3 3

      4 5 5 20 1 1

      6 6 1

      0 1 1 18 3 3

      0 2 1 12 4 4

      0 4 1 3 5 5

      2 3 1 8 2 2

      3 4 1 5 3 3

      4 5 5 20 1 1

      6 6 0

      0 1 1 18 3 3

      0 2 1 12 4 4

      0 4 1 3 5 5

      2 3 1 8 2 2

      3 4 8 25 3 3

      4 5 5 20 1 1

      3 3 0

      0 1 0 5 4 4

      1 2 0 5 2 2

      0 2 0 5 6 6

      Scenario #1: 6 6

      Scenario #2: 7 6

      Scenario #3: 12 10

      Scenario #4: -1

       

       

      CONSTRAINTS:

       

      1 <= T <= 10

       

      Small input: (20%)

      2 <= V <= 10

      1 <= E <= 30

      M = 0

       

      Medium input: (30%)

      2 <= V <= 100

      1 <= E <= 1,000

      M = 0

       

      Large input: (50%)

      2 <= V <= 100

      1 <= E <= 1,000

      0 <= M <= 50

      It is guaranteed that the distance of the tunnels won't never exceed 10.

       

      1 <= opening and collapse times <= 100,000

       

      Clarifications: You start with time 0. It will be always true that the time x will be lesser or equal than time y. While passing through a tunnel from room i to room j, if the tunnel collapses while you're inside, you can use a hammer to break through, otherwise that path is impossible to take.



      Added by:David Moran
      Date:2012-06-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11772. Negative Score

      Problem code: RPLN

       

       Orianna is a great swimmer and she's going to a swimming competition this month and needs your help as she is highly paranoic about the results of the competition.

       

      The competition consists in some sort of evaluations, every judge makes a score and, based on that score and the score of other contestants she will get a score belonging to her results, those scores are final, meaning that will not change in the competition.

       

      Orianna requires this solution with urgency, she is getting evaluated on a lot of ways and she is very worried about her results, so she wants to know what is the worst score from an evaluation A to other evaluation B inclusive.

       

      INPUT:

      The first line of the test data will start with an integer T representing the T test cases, then, T cases will follow, each of the cases starts with two integers N and Q, denoting the number of evaluations Orianna had, then, N integers will follow denoting the score on each evaluation, after that, Q queries will begin, each query consist on two integers A and B.

       

      OUTPUT:

      You must output the string “Scenario #i:“, a blank line and then the result of each query, remember, Orianna is interested on the worst score from evaluation A to evaluation B inclusive.

       

      INPUT

      OUTPUT

      2

      5 3

      1 2 3 4 5

      1 5

      1 3

      2 4

      5 3

      1 -2 -4 3 -5

      1 5

      1 3

      2 4

      Scenario #1:

      1

      1

      2

      Scenario #2:

      -5

      -4

      -4

       

      CONSTRAINTS:

       

      1 <= T <= 100

       

      Small input (30%):

      1 <= N <= 1,000

      1 <= Q <= 1,000

      -10^9 <= Ni <= 10^9

      1 <= A <= B <= N

       

      Large input (70%):

      1 <= N <= 100,000

      1 <= Q <= 100,000

      -10^9 <= Ni <= 10^9

      1 <= A <= B <= N

       

      Solutions rejudged due to weak test cases.



      Added by:David Moran
      Date:2012-06-22
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used for the RPL contest









      SPOJ Problem Set (classical)

      11777. Easy Sequence!

      Problem code: SEQAGAIN


      Your task is to find the nth term of the following sequence :

      F(n) = [F(n-1)*F(n-2)]K for n>1

      F(0), F(1), n and K will be provided as input. Modulus for all calculations is 1000000007. You should print the answer modulo 1000000007 i.e. F(n)%1000000007

      Input

      Input starts with a line containing an integer T ≤ 5000 which is the number of test cases in the file. Your program will be run on several input files.

      Each test case consists of four space separated integers : F(0), F(1), n and K.

      Output

      T lines containing one integer each, corresponding to the answers for the T test cases.

      Constraints

      0 ≤ n ≤ 1018

      0 ≤ K ≤ 109

      0 ≤ F(0), F(1) ≤ 106

      Example

      Input:
      1
      1 1 2 1

      Output: 1

      Added by:Himanshu Sachdeva
      Date:2012-06-26
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11789. Aliens at the subway

      Problem code: ALIEN3

      The female Alien moved to the biggest city in the world, this city has a giant subway system, this subway is always full of people, the Alien doesn't want to see humans and she wants to stay the least time possible in the subway system.

      Preventing this scenario, the Alien brought from her planet some interesting and very rare objects, she calls this objects “Portable Teleporters”, with these objects the alien is on the capacity to teleport and ignore the next K stations, as you may know, this objects are limited and it can be used once.

      As the city is so big that the subway is always full, she wants to stay the least number stations as possible, the Alien will start from station 0, wishing to go up to an station L, the subway is formed by N+1 (0 through N) stations and the Alien has K “Portable Teleporters”.

      When the Alien uses a “Portable Teleporters” she will be teleported immediately to the I+Kj station, being I the station the alien was on and Kj the value of the Portable Teleporter.

      If she is unable to use a teleporter or is better for her to go into the next station using the subway, she can do it, however, she can only move forward, NEVER backwards, furthermore, the Alien may not leave the limits of the stations (that means she can't go to any station before station 0 or any station after station N).

       As you may know, the Alien doesn't wants to see a large number of people, to prevent this, she wants to visit as maximum T stations, if she can't reach her destination on T stations, she will simply exit the subway and will start walking on the city.

      Your task is simple, given the N stations, the K objects and their values and the station the Alien wants to go, the L station the alien wants to go and the T number of tries, output the least stations visited so she can reach her destination.

       

      INPUT:

      The Input will start with an integer P denoting the test cases, then P cases will follow, each case have three lines, the first line contains two integers N and K, denoting the N stations and the K portable teleporters, next line will contain K integers, denoting the value of each teleporter, the last line for each case will contain two integers L and T, that it will be the last station the alien wants to go and the T number of stations she wants to visit as maximum.

      OUTPUT:

      The output will consists on P lines, each line containing the string "Scenario #i: " where i is the test case you're analyzing (starting by 1), followed by the minimum stations visited by the Alien to reach her destination, if she can't reach her destination on maximum T stations, print -1.

       

      INPUT

      OUTPUT

      4

      12 6
      1 3 4 1 2 -2
      10 10

      12 6
      1 3 2 1 2 -2
      10 10

      10 2
      6 -2
      5 10

      10 2
      1 1
      10 5

      Scenario #1: 4
      Scenario #2: 6
      Scenario #3: 3
      Scenario #4: -1

      "Blank line between input sample data is just for clarification and understanding of the problem"

       

      Explanation of the first test case:

      She teleports from station 0 to station 4 using the third teleporter, from 4 to 7 using the second teleporter, from 7 to 9 using the fifth teleporter and she can either walk to the next station or use another teleporter.

      Explanation of the last case:

      She can't reach the station 10 going through only 5 stations, the answer should be then -1.

       

      CONSTRAINTS:

      1 <= P <= 50

      1 <= N <= 100

      1 <= K <= 17

      -100 <= Ki <= 100

      0 <= L <= N

      1 <= T <= 50


      Added by:David Moran
      Date:2012-06-28
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set ()

      11808. Max 2214

      Problem code: MAX2214

      Max2214 is a game that consists of a board of R rows and C columns and two kinds of blocks: Some of the blocks are 2 cells high and 2 cells wide, the others are 1 cell high and 4 cells wide. Some of the cells of the board might be marked. The objective of the game is to place the most blocks on top of the board in a way that the blocks are aligned to the rows and columns, no pair of blocks overlap, marked cells do not contain any block, and the 1x4 blocks are placed horizontally exclusively. Also, blocks must be completely inside the board.

      Input

      The input consists in a single test case with a 15 seconds execution limit.

      The test case begins with 2 integers R and C in a single line: (1 <= R <= 52) (1 <= C <= 22).

      The next R lines contain C characters. Each character represents a cell. If a character is X, it means the cell is a marked cell. If the character is '.' (A dot character) it means the cell is not marked.

      Output

      Show a single line containing the maximum quantity of blocks that can be placed in the board following the rules mentioned above.

      Example

      Input:
      
      4 5
      X....
      X..XX
      X..XX
      ....X
      Output:
      3


      Added by:Vexorian
      Date:2012-07-01
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:First international programming camp - Bolivia









      SPOJ Problem Set (classical)

      11813. Count weighted paths

      Problem code: CNTPATHS

      John likes to take a walk from his house to university. He needs to arrive his university in at most T seconds after leaving his home. We can represent the situation as a N vertices graph. Vertex 0 of the graph will be John's home and vertex 1 John's university. There can be bidirectional roads connecting pairs of vertices, each road will take John some seconds to cross.

      John likes variety. We consider a valid path to be a sequence of vertices that starts with vertex 0 (John's house) and finishes with vertex 1 (The University) and there exists a road connecting each pair of consecutive vertices in the sequences (Note that a vertex may appear multiple times in the path). The total time John needs to traverse a path is equal to the sum of the times needed to cross each individual road in it. Please count the total number of different paths that need at most T minutes to be traversed in total. Two paths are different if there is at least one moment at which they visit different vertices.

      Given T, N and the roads between the vertices,  ¿How many different paths that need at most T seconds exist? Print the result modulo 1000000007  (109+7).

       

       

      Input

      The first line consists of a integer TOTAL, the total number of test cases (1 <= N <= 10).

      Each of the following test cases begins with a single line that contains two integers : N and T. (2 <= N <= 5), (1 <= T <= 1000000000 (109) ).

      The N following lines are indexed from i=0 to N-1.   The i-th line will represent the roads that connect vertex i  with other vertices. The line will consist of N character  indexed from j=0 to N-1 The j-th character of the i-th line represents the road connecting vertex i with vertex j. If the character is '-', this means no road connectes vertices i and j. Otherwise, the character will be a digit equal to 1,2 or 3, determining the number of minutes it takes John to move between vertices i and j.

      For every pair (i,j), the road character between i and j will be the same as the one between j and i.

      For each i, there will never be a road cannecting vertex i with itself.

      Vertex 0 represents John's house and Vertex 1 John's university.

      Output

      For each test case, show in a single line: "Case #i: R", where R is the total number of valid paths between vertices 0 and 1 donde R that need a quantity of at most T segundos .

      Example

      Input:
      3
      2 9
      -3
      3-
      5 4
      --123
      --123
      11---
      22---
      33---
      3 100
      -21
      2-3
      13- Output: Case #1: 2
      Case #2: 4
      Case #3: 924247768

      Notes

      There are two paths in the first case that need 9 minutes or less:

      • 0 -> 1 (3 minutes)
      • 0 -> 1 -> 0 -> 1 (9 minutes)

      The second case contains 4 paths that need at most 4  minutes to be traversed:

      • 0 -> 2 -> 1 (2 minutes)
      • 0 -> 3 -> 1 (4minutes)
      • 0 -> 2 -> 0 -> 2 -> 1 (4 minutes)
      • 0 -> 2 -> 1 -> 2 -> 1 (4minutes)

      0 -> 4 -> 1 is a path that needs 6 minutes.

       


      Added by:Vexorian
      Date:2012-07-02
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource: First international programming camp - Bolivia









      SPOJ Problem Set (classical)

      11814. Eko

      Problem code: EKO

       

      Lumberjack Mirko needs to chop down M metres of wood. It is an easy job for him since he has a nifty 
      new woodcutting machine that can take down forests like wildfire. However, Mirko is only allowed to 
      cut a single row of trees.
      Mirko‟s machine works as follows: Mirko sets a height parameter H (in metres), and the machine raises 
      a giant sawblade to that height and cuts off all tree parts higher than H (of course, trees not higher than 
      H meters remain intact). Mirko then takes the parts that were cut off. For example, if the tree row 
      contains trees with heights of 20, 15, 10, and 17 metres, and Mirko raises his sawblade to 15 metres, the 
      remaining tree heights after cutting will be 15, 15, 10, and 15 metres, respectively, while Mirko will take 
      5 metres off the first tree and 2 metres off the fourth tree (7 metres of wood in total).
      Mirko is ecologically minded, so he doesn‟t want to cut off more wood than necessary. That‟s why he 
      wants to set his sawblade as high as possible. Help Mirko find the maximum integer height of the 
      sawblade that still allows him to cut off at least M metres of wood.

      Lumberjack Mirko needs to chop down M metres of wood. It is an easy job for him since he has a nifty 

      new woodcutting machine that can take down forests like wildfire. However, Mirko is only allowed to 

      cut a single row of trees.

      Mirko‟s machine works as follows: Mirko sets a height parameter H (in metres), and the machine raises 

      a giant sawblade to that height and cuts off all tree parts higher than H (of course, trees not higher than 

      H meters remain intact). Mirko then takes the parts that were cut off. For example, if the tree row 

      contains trees with heights of 20, 15, 10, and 17 metres, and Mirko raises his sawblade to 15 metres, the 

      remaining tree heights after cutting will be 15, 15, 10, and 15 metres, respectively, while Mirko will take 

      5 metres off the first tree and 2 metres off the fourth tree (7 metres of wood in total).

      Mirko is ecologically minded, so he doesn‟t want to cut off more wood than necessary. That‟s why he 

      wants to set his sawblade as high as possible. Help Mirko find the maximum integer height of the 

      sawblade that still allows him to cut off at least M metres of wood.

       

      Input

       

      The first line of input contains two space-separated positive integers, N (the number of trees, 1 ≤ N ≤ 

      1 000 000) and M (Mirko‟s required wood amount, 1 ≤ M ≤ 2 000 000 000).

      The second line of input contains N space-separated positive integers less than 1 000 000 000, the 

      heights of each tree (in metres). The sum of all heights will exceed M, thus Mirko will always be able to 

      obtain the required amount of wood.

       

      Output

      The first and only line of output must contain the required height setting.

       

      Example

      Input:
      4 7
      20 15 10 17
      
      Output:
      15
      Input:
      5 20
      4 42 40 26 46
      Output:
      36

      Added by:Goran Horvat
      Date:2012-07-02
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2011/2012









      SPOJ Problem Set (classical)

      11830. DOJO Corridor I

      Problem code: DOJ1


      There's a long rectangular corridor in the hall's dojo, one place is already taken by a magic hanjō (1×1 square). You have to put tatamis (1×2 rectangle) in order to cover exactly the rest of the corridor. Sometimes it's possible, sometimes not!

      Input

      The input begins with the number T of test cases in a single line. In each of the next T lines there are two integers : N, M the size of the corridor, I,J coordinates of the magic hanjō, and K the modulo for the output.

      Output

      For each test case, print the number of possibility to do the job, modulo K.

      Example

      Input:
      3
      1 3 1 3 100
      2 3 2 2 100
      3 7 1 3 100
      
      Output:
      1
      0
      56
      

      Corridor

      Constraints

      1 <= T <= 30000

      1 <= N <= 4

      1 <= M <= 10^9

      1 <= I <= N

      1 <= J <= M

      1 <= K <= 10^9

      Uniform, independent, random input in the range.

      Time limit is set to allow one half kB of python3 code to get AC.


      Added by:Francky
      Date:2012-07-06
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      11834. DOJO Corridor II

      Problem code: DOJ2


      There's a 5×N rectangular corridor in the hall's dojo, one place is already taken by a magic hanjō (1×1 square). You have to put tatamis (1×2 rectangle) in order to cover exactly the rest of the corridor. Sometimes it's possible, sometimes not!

      Input

      The input begins with the number T of test cases in a single line. In each of the next T lines there are an integer N the H-length of the corridor, and I, J the coordinates of the magic hanjō. See sample input for details format.

      Output

      For each test case, print the number of possibility to do the job, modulo 1000000007.

      Example

      Input:
      3
      1 C 1
      3 B 2
      5 A 1
      
      Output:
      1
      8
      192
      

      Corridor

      Constraints

      1 <= T <= 40 000

      1 <= N <= 20 000

      A <= I <= E

      1 <= J <= N

      Uniform, independent, random input in the range. Input had been 'filtered' to let only possible configurations.

      You may try too : Grid Tiling, or Blocks for kids


      Added by:Francky
      Date:2012-07-08
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      11840. Sum of Squares with Segment Tree

      Problem code: SEGSQRSS

      Segment trees are extremely useful.  In particular "Lazy Propagation" (i.e. see here, for example) allows one to compute sums over a range in O(lg(n)), and update ranges in O(lg(n)) as well.  In this problem you will compute something much harder:  

      The sum of squares over a range with range updates of 2 types:

      1) increment in a range

      2) set all numbers the same in a range.

      Input

      There will be T (T <= 25) test cases in the input file.  First line of the input contains two positive integers, N (N <= 100,000) and Q (Q <= 100,000). The next line contains N integers, each at most 1000.  Each of the next Q lines starts with a number, which indicates the type of operation:

      2 st nd  -- return the sum of the squares of the numbers with indices in [st, nd] {i.e., from st to nd inclusive} (1 <= st <= nd <= N).

      1 st nd x -- add "x" to all numbers with indices in [st, nd(1 <= st <= nd <= Nand -1,000 <= x <= 1,000).

      0 st nd x -- set all numbers with indices in [st, nd] to "x" (1 <= st <= nd <= Nand -1,000 <= x <= 1,000).

       

      Output

      For each test case output the “Case <caseno>:” in the first line and from the second line output the sum of squares for each operation of type 2.  Intermediate overflow will not occur with proper use of 64-bit signed integer. 

      Example

      Input:

      2
      4 5
      1 2 3 4
      2 1 4
      0 3 4 1
      2 1 4
      1 3 4 1
      2 1 4
      1 1
      1
      2 1 1

      Output:
      

      Case 1:
      30
      7
      13
      Case 2:
      1

       

      Added by:Chen Xiaohong
      Date:2012-07-11
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set ()

      11844. Binary Sequence of Prime Number

      Problem code: BSPRIME

      Binary Sequence of Prime Number is a binary sequence that created by converting prime number to base-2 (Without leading zeros):

      (2)10=(10)2
      (3)10=(11)2
      (5)10=(101)2
      (7)10=(111)2
      ...

      If all base-2 of prime number joined, then we get the binary sequence like this: 10111011111011110110...

      Now your task is to count how many digit '1' appear in the first N terms of the sequence, example:

      -->If N=3, digit '1' appear 2 times: 101110...
      -->If N=10, digit '1' appear 8 times: 1011101111101...

      Input

      The first line is an integer T(1 ≤ T ≤ 50,000), denoting the number of test cases. Then, T test cases follow.

      For each test case, there is an integer N(0 ≤ N ≤ 150,000,000) written in one line.

      Output

      For each test case, output the number of digit '1' appear in the first N terms of the sequence

      Example

      Input:
      3
      3
      10
      50
      
      Output:
      2
      8
      36

       

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2012-07-12
      Time limit:1s
      Source limit:10000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11848. Power with Combinatorics

      Problem code: POWPOW


      Your task is to find a^(exp^(b)),

      a:Provided in input,10^5=>a>=0

      b:Provided in Input,10^5=>b>=0

      exp=(nC0)^2 + (nC1)^2 +(nC2)^2+..........+(nCn)^2,

      n:Provided in the input, 10^5=>n>=0

      As the answer can be too large , you need to output modulo 10^9+7.

      nCr denotes n choose r.

      Input

      The first line of each input file contains number of test cases t(t<=1000).

      Then follow a new line.

      Then follow t lines,each conating 3 integers,(i.e a b n  in order) each of them seperated by a space.

      Output

      Output Contains t lines,ith line conatins the answer of the ith test case .

      Example

      Input:
      1
      1 1 1
      Output:
      1
      Explanation: In First test case, the Value of exp is 2, value of 1^(2^1) is 1,so output is 1.

      Click here to see my set of problems at Spoj.


      Added by:Devendra Agarwal
      Date:2012-07-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      11851. Power with Combinatorics(HARD)

      Problem code: POWPOW2

      Your task is to calculate a^(b^(exp))

      a:provided in input,10^5=>a>=0

      b:provided in input,10^5=>b>=0

      exp=(nC0)^2 + (nC1)^2 + (nC2)^2 + ......+(nCn)^2

      n:provided in input,10^5=>n>=0

      Note: The Output for 0^0 should be 1.

      nCr denotes n choose r.

      As the answer can be too large , you need to output modulo 10^9+7.

      Input

      The first line of each input file contains number of test cases t(t<=1000).

      Then follow a new line.

      Then follow t lines,each conating 3 integers,(i.e a b n  in order) each of them seperated by a space.

      Output

      Output Contains t lines,ith line conatins the answer of the ith test case.

      Example

      Input:
      1
      1 1 1
      
      Output:
      1
      Explanation: In First test case, the Value of exp is 2, value of 1^(1^2) is 1,so output is 1.
      Note: First try out the tutorial version where limits are low. POWRTU

      Click here to see my set of problems at Spoj.


      Added by:Devendra Agarwal
      Date:2012-07-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Utkarsh Lath









      SPOJ Problem Set (classical)

      11875. Jobs

      Problem code: POSAO

      Little Domagoj has hands full of work. His jobs are organized in NxN matrix such that each cell represents one job. He can start doing job at cell (x,y) if and only if jobs at cells (x,y-1) and (x-1,y) are done(if they exist). 


      On the picture required jobs are shown for gray cells. 

      Domagoj has K computers which he will use for doing jobs. One computer is able to do at most one job in one second. Also, all computers need not to be used all the time. Help Domagoj and organize order in which computers will do jobs in least possible time.

      Input

      In the first line there are two integers N and K (1 ≤ N≤ 109)

      Output

      Print least possible time in which all jobs can be done.

      Example

      Input:
      3 2
      Output:
      6
      Input:
      5 1
      Output:
      25
      Input:
      4 4
      Output:
      7

      Added by:Ivan Kataniæ
      Date:2012-07-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Croatian Junior Olympiad in Informatics, Matija Osrecki









      SPOJ Problem Set (classical)

      11885. Drawing Triangles with Brainf##k

      Problem code: BFTRI

      Your task is just to draw triangles! seems easy(?) but only brainf**k programming language is allowed.

      Input

      The first line is an integer T(0 < T < 100), denoting the number of test cases. Then, lines follow.

      For each test case, there are one character c(ASCII(32) < c < ASCII(127)) and one integer i(0 < i < 100) written in one line, separated by a space. Each line end with ASCII(10).

      Output

      For each test case, output triangle size i (draw triangle using character c). See example.

      Example

      Input:
      3
      & 1
      @ 3
      ? 5
      Output:
      &
      @
      @@
      @@@
      ?
      ??
      ???
      ????
      ?????

       

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2012-07-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:BF
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11895. DONALDO

      Problem code: DONALDO

      Donaldo

      Donaldo is a great footballer. Since he is famous, he has lots of girlfriends. But the problem is, he isn't certain about the actual number of his girlfriends. So, he checked his mobile inbox. His girlfriends send him a lot of texts. But he knows that, none of them will send more than 1 text between I seconds of time interval. Given the exact times of received texts, Donaldo has to guess the minimum possible number of girlfriends he has.

      Input

      The first line contains T(the number of test cases, 0<=T<=50). Then T test cases follows.
      Each test case starts with a line with N(number of texts in Donaldo's inbox, 0<=N<=20000). The following N lines contain a time of the format H:M:S (H=hour , M=minute, S=second, 0<=H<=23, 0<=M<=59, 0<=S<=59). The i-th time is the exact time when i-th text was received (1<=i<=N). The last line contains I (1<=I<=86400).

      Note that,
      1. A specific time can occur more than once.
      2. The texts are opened randomly, so the times don't have any particular(increasing/decreasing) order.
      3. The duration between sending and receiving a text is negligible.
      4. Intervals are inclusive. (e.g. If an interval of 5 seconds starts at 0:0:55, it will end at 0:0:59).

      Output

      For each testcase, output a line containing “Case X: Y”, where X is the case number and Y is the minimum possible number of Donaldo's girlfriends.

      Sample Input

      Output for Sample Input

      2
      3
      8:39:17
      17:17:17
      21:59:59
      86400
      3
      17:17:17
      21:59:59
      8:39:16
      48042

      Case 1: 3
      Case 2: 2

       

      Explanation

      In the first test, all the texts are inside 86400 seconds duration. That means, each text is sent by a distinct girlfriend. So, number of Donaldo's girlfriends has to be greater or equal to 3.

      In the second case, there are 2 possible time intervals containing 2 texts. One is containing the 1st and the 3rd time, and the other is containing the 1st and the 2nd time. So, any answer smaller than 2 is not possible.


      Added by:Bidhan Roy ( বিধান )
      Date:2012-07-23
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem (Used in University of Dhaka's internal contest). Alternate Writer : Shiplu Hawlader, Zobayer Hasan.









      SPOJ Problem Set (classical)

      11900. Spelling Suggestion

      Problem code: PK11F

      A spelling suggestion is a part of spelling correction program that generates a set of plausible replacements for words that are likely to be misspelled. One way to measure the plausibility of these replacements is to compute their edit distance against a given misspelled word. The edit distance between two words is the total number of edit operations that have to be done in order to transform one word into the other. Normally these edit operations are insertion, deletion and substitution of a single character including transposition of 2 consecutive characters.

      For example, for a word “wonder”, if the deletion is applied at the character 'o', this word will transform into “wnder”. And if the substitution with 'a' is applied at 'o', it will become “wander”. And if the transposition is applied at “er”, it will become “wondre”.

      In this edit distance strategy, the degree of similarity between two words is up to their minimum edit distance. If the minimum edit distance between word1 and word2 is lower than the distance between word1 and word3, then word1 is more similar to word2 than to word3. So the word2 is a better spelling suggestion for word1, comparing with word3.

      Suppose that you are an employee of a software company which needs to build up a prototype of spelling suggestion program. This prototype tends to be a part of word processing software. The requirement is that it has to use the edit distance strategy for their spelling suggestion. But the substitution operation has to be redefined to match the behavior of mistyping. The cost of substitution of a character with another character depends on the position of them on the keyboard layout. If they are close to each other, the cost is only half of the normal one. For this purpose, the substitution is categorized into near-substitution and far-substitution. Their costs are defined as 1 and 2 respectively. And the costs for insertion, deletion and transposition are 2. In addition, this program must run fast enough to pass the time limit that is set by your manager. By the way for this prototype, an English QWERTY keyboard layout is chosen to be used.

      Goal

      To generate optimum spelling suggestions for each input word, where each optimum spelling suggestion is a word in dictionary that has the least minimum edit distance from the given input word. The time limit for 5,000 misspelled words is less than or equal to 5 minutes.

      Input

      Input is a standard input which contains 3 parts of data. Each of these three parts ends with a blank line.

      ·        The first part is a set of near-substitution rules, where each rule is kept in one line. Each line has two fields. Each filed is separated by a space. The total no. of rules is less than or equal to 150

      o       The first field is a character where it can be near-substituted with other characters.

      o        The second field is a sequence of characters which can be near-substituted for the character in the previous field. There is no space in this field.

      o       The characters that may be contained in this part are characters that can be typed in using a generic English keyboard layout, which are alpha-numeric characters and some punctuations without space or tab.  They are listed as the following.

       

      abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+\|[{]};:'”,<.>/?

       

      ·        The second part is a sequence of words in dictionary, where each word is kept in one line. The total no. of words is less than or equal to 150,000.

      o       The characters in dictionary are alphabetical characters with an apostrophe punctuation.

      abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’

      ·        The third part is a sequence of words that need to be checked for their spellings. Each of these words is also kept in one line. The total no. of words is less than or equal to 5,000.

      o       The characters that may be contained in this part are the same as characters in the first part, which are alpha-numeric characters and some punctuation. (See the first part.)

      ·        Since each of these three parts end with a blank line, the third blank line is the termination of the input.

       

      Output

      For each word in the third part, write a line which contains 3 parts of information, separated with a colon.

      ·        The first part is the given input word.

      ·        The second part is the minimum edit distance between the input word and suggestion word(s).

      ·        The third part is an ascending sorted sequence of suggestion word(s), separated with a space. There is no space left after the last word.

       


      Example

      Line no.

      Sample Input

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      22

      23

      24

      25

      26

      27

      28

      29

      30

      a AqQsSzZ

      b BgGvVnN

      p P0);:oO[{

      r R4$fFeEtT

      z ZaAxX

       

      a

      A

      b

      B

      Z

      angel

      angle

      anger

      angry

      ABC

       

      x

      s

      z

      xx

      xxx

      angre

      angri

      angrt

      angel

      ACB

      BAC

      CAB

      Line no.

      Sample Output

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      x:2:A B Z a b

      s:1:a

      z:1:A Z a

      xx:4:A B Z a b

      xxx:6:A ABC B Z a b

      angre:2:anger angle angry

      angri:2:angry

      angrt:2:anger angry

      angel:0:angel

      ACB:2:ABC

      BAC:2:ABC

      CAB:4:A ABC B

       

      More Explanations

       

      In this sample input, there are 5 near-substitution rules (line no. 1-5), 10 words in dictionary (line no. 7-16) and 12 words looking for their suggestions (line no. 18-29).

      In the sample output, there are 12 lines for each corresponding 12 words from the input.

      For the 1st word, the minimum edit distance between x and its suggestions (A B Z a b) is 2. All of them are the (far) substitution costs.

      For the 2nd word, the minimum edit distance between s and its suggestion (a) is 1, which is a near-substitution cost, guided by the 1st substitution rule.

      For the 3rd word, the minimum edit distance between z and its suggestion (A Z a) are 1, which is a near-substitution cost, guided by the 1st or 5thsubstitution rule.

      For the 4th word, the minimum edit distance is 4, which are summed from one far-substitution cost and one deletion cost.

      For the 5th word, the minimum edit distance is 6. The costs between xxx and (A B Z a b) are from two deletion and one far-substitution costs. 

      The cost between xxx and ABC re from three far-substitution costs.

      For the 6th word, the cost between angre and anger is from one transposition costs. The costs between angre and (angle angry) are from one far-substitution costs.

      For the 7th word and 8th word, seem to be similar. But the cost of 7th word is from one far-substitution costs. 

      But the cost between angrt and anger is from 2 near-substitution costs (r substitutes with e and t substitutes with r) according to the near-substitution rule no. 4.

      For the 9th word, the word is exactly matched within dictionary. So the cost is 0.

      For the 10th and 11th words, each cost is from one transposition costs.

      For the 12th words, the cost between CAB and (A B) is from two deletion costs. The cost between CAB and (ABC) is from one deletion and one insertion costs. 

      Please be notify that it is not from 2 transpositions of CAB to ACB and then ACB to ABC.   


      Added by:Race with time
      Date:2012-07-25
      Time limit:100s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC Regional Phuket 2011









      SPOJ Problem Set (classical)

      11904. A Classic Myth - Flatland Superhero

      Problem code: FLATAND

      Description
      Figure 2: A Frozen Swarm of Ants
      in Flatland
      Flatland needs a superhero! Recently swarms of killer ants
      have been invading Flatland, and nobody in Flatland can
      figure out how to stop these dastardly denizens. Fortunately,
      you (as a higher dimensional being) have the opportunity
      to become a superhero in the eyes of the Flatland citizens!
      Your job is to “freeze” swarms of ants using parallelograms.
      You will do this by writing a program that finds a minimal
      area enclosing parallelogram for each swarm of ants. Once a
      minimal area parallelogram is placed around the ant swarm,
      they are effectively frozen in place and can no longer inflict
      terror on planar inhabitants.

      Flatland needs a superhero! Recently swarms of killer ants have been invading Flatland, and nobody in Flatland

      can figure out how to stop these dastardly denizens. Fortunately, you (as a higher dimensionalbeing) have the

      opportunity to become a superhero in the eyes of the Flatland citizens!

      Your job is to “freeze” swarms of ants using parallelograms. You will do this by writing a program that finds a

      minimal area enclosing parallelogram for each swarm of ants. Once a minimal area parallelogram is placed around

      the ant swarm, they are effectively frozen in place and can no longer inflict terror on planar inhabitants.

       

      Input

      The input will consist of the following:

      • A line containing a single integer, s (1<=s<=20), which denotes the number of killer ant swarms.

      • Each swarm will start with a single line containing an integer, n (4<=n<=1000), which indicates the number of killer ants in the swarm.

      • The next n lines contain the current location of each killer ant in the swarm.

      • Each killer ant is represented by a single line containing two numbers: x (−1000<=x<=1000) and y (−1000<=y<=1000) separated by a space.

      • Only one killer ant will occupy each (x, y) location in a particular swarm. Each swarm should be dealt with independently of other swarms.

      • All data inputs are in fixed point decimal format with four digits after the decimal (e.g., dddd.dddd).

      • There may be multiple parallelograms with the same minimum area.

       

      Output

      For each swarm, your algorithm should output a line that contains “Swarm i Parallelogram Area: ”, 

      where i (1<=i<=s) is the swarm number, followed by the minimum area (rounded to 4 decimal

      digits and using fixed point format) of an enclosing parallelogram for that swarm. All computations

      should be done using 64 bit IEEE floating point numbers, and the final answers displayed in fixed

      point decimal notation and rounded to four decimal digits of accuracy as shown in the sample input

      and output.

       

      Example

      Input:
      2
      6
      0.0000 0.0000
      -0.5000 -0.5000
      -1.0000 0.0000
      -0.7000 -7.0000
      -1.0000 -1.0000
      0.0000 -1.0000
      5
      2.0000 2.0000
      0.0000 0.0000
      0.5000 2.0000
      1.0000 1.0000
      1.5000 0.0000
      
      Output:
      Swarm 1 Parallelogram Area: 7.0000
      Swarm 2 Parallelogram Area: 3.0000

      Added by:Gareev
      Date:2012-07-26
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:North America - Pacific Northwest 2011









      SPOJ Problem Set (classical)

      11905. Tree Count

      Problem code: TRECOUNT


       

      Our superhero Carry Adder has uncovered the secret method that the evil Head Crash uses to
      generate the entrance code to his fortress in Oakland. The code is always the number of distinct
      binary search trees with some number of nodes, that have a specific property. To keep this code
      short, he only uses the least significant nine digits.
      The property is that, for each node, the height of the right subtree of that node is within one of
      the height of the left subtree of that node. Here, the height of a subtree is the length of the longest
      path from the root of that subtree to any leaf of that subtree. A subtree with a single node has a
      height of 0, and by convention, a subtree containing no nodes is considered to have a height of −1.

      Our superhero Carry Adder has uncovered the secret method that the evil Head Crash uses to

      generate the entrance code to his fortress in Oakland. The code is always the number of distinct

      binary search trees with some number of nodes, that have a specific property. To keep this code

      short, he only uses the least significant nine digits.

      The property is that, for each node, the height of the right subtree of that node is within one of

      the height of the left subtree of that node. Here, the height of a subtree is the length of the longest

      path from the root of that subtree to any leaf of that subtree. A subtree with a single node has a

      height of 0, and by convention, a subtree containing no nodes is considered to have a height of −1.

       

      Input

      Input will be formatted as follows. Each test case will occur on its own line. Each line will contain

      only a single integer, N, the number of nodes. The value of N will be between 1 and 1427, inclusive.

      Output

      Your output is one line per test case, containing only the nine-digit code (note that you must print

      leading zeros).

      Example

      Input:
      1
      3
      6
      21
      
      Output:
      000000001
      000000001
      000000004
      000036900
      

      Added by:Gareev
      Date:2012-07-26
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:North America - Pacific Northwest 2011









      SPOJ Problem Set (classical)

      11906. Rescue On Time

      Problem code: ROT

       

      In the future there is an agency that works on rescuing people from the “bad guys”, those guys are a super secret evil agency that is on a super secret bunker that everybody knows, especially the agency we mentioned before. This agency (the good one) has a very particular thing, they can do time travel either to the future or to the past and they can do it how many times they want, but only one minute to the future or one minute to the past,or even stay in the present, it is impossible to go for example three minutes to the future or two minutes to the past; our agency wants to rescue only one hostage since the “bad guys” are really dumb and they can kidnap only one person and keep it hidden (it is dumb because the bunker is huge), now here is the deal, the agency has contracted us to do a program that tells the minimum number of time steps the agent of our agency should make to save the hostage (I am so lazy that you will do it all by yourself). It is important to know that at some point after certain amount of time the hostage will be killed so we don´t want to go over that time, never! And also we don´t want to get back on a time where the hostage isn´t in the bunker yet so remember that!, he can take a step into any adjacent direction but not in diagonals, and it is no meaning into wait on a position because the agent can use time as he wants.

       

      ‘X’-> represents the place where the agent starts, it is guaranteed that the agent starts at the time 1

      ‘#’-> represents a wall

      ‘s’->represents a free space

      ‘!’-> represents a “bad guy”

      ‘O’->represents our objective

      Input

      The first line of input is T the number of test cases, there will be several test cases T<=10. Next line of input contains C,R,Time, which are Columns<=15, Rows<=15 and of course the Time<=10 (Right after that maximum time the hostage will be killed and before time 1 there will be no hostage to save so is useless to go there) Time is measured in minutes, after that, Time lines will follow with a matrix of RxC Representing the actual position of guards and new free spaces after time traveling (Obviously walls will not move, and neither does the hostage because he is tide up)

      Output

      Just output the minimum number of time steps that takes to our agent to get to the hostage, if it is impossible to get to the Hostage then should output: “Hostage is death, destroy the bunker”

      Example

      Input:
      

      2

      3 3 1

      sss
      ssX Oss

      3 3 3 Xss       #s! s!O sss #!s !sO ss! #s! ssO

      Output: 3
      4

      Added by:Rodolfo Miquilarena
      Date:2012-07-27
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      11909. C You and Me

      Problem code: PUCMM223


      You and Me is a board game between two players, the board is MxN, with 1 ≤ M,N ≤ 20. Initially each player has one piece, piece 'a' and piece 'b', both players move at the same time its piece, a valid move is to move the piece one square on each of the 4 cardinal directions (North, South, East, West),or stay in the same square, that is, if a piece is at x,y it can move to(x-1, y), (x, y-1), (x, y), (x, y+1), (x+1, y), so with the two pieces combined there are 5x5=25 possibilities in one move. The game has a goal, piece 'a' must finish at position initially accupied by 'b', and viceversa. To make this game more interesting the cells can be occupied by a block('#'), or can be unocuppied('.'). What is the minimum number of moves required to achieve this goal, if the pieces cannot occupy the same square at a given time and can't cross each other. See examples for further details.

      Input

      For each test case the first line contains two separated integers, M and N, rows and columns of the board.

      then M strings of N characters follow.

      Each character could be '.', '#', 'a', 'b'.

      Just one 'a' and one 'b' exists.

      The last case is followed by 0 0.

      Output

      Output the minimum number of moves required to achieve the goal. Output IMPOSSIBLE if it is not possible.

      Example

      Input:
      3 4
      #..#
      a..b
      ####
      3 7
      #######
      #a...b#
      #######
      4 4
      a...
      ###.
      ##..
      b...
      0 0
      Output:

      5
      IMPOSSIBLE
      11

      Note:
      1st case:
      one possibility is
      #..# #..# #.b# #..# #..# #..#
      a..b--->.ab.--->..a.--->..ba--->.b.a--->b..a
      #### #### #### #### #### ####

      Added by:Olson Ortiz
      Date:2012-07-27
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C# C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Used in 3rd PUCMM Olympiad 2012 (1st phase)









      SPOJ Problem Set (classical)

      11921. Ball Stack

      Problem code: BALLLSTA



      The XYZ TV channel is developing a new game show, where a contestant has to make some choices in order to get a prize. The game consists of a triangular stack of balls, each of them having an integer value, as the following example shows.

       

      \epsfbox{p12357.eps}

      The contestant must choose which balls he is going to take and his prize is the sum of the values of those balls. However, the contestant can take any given ball only if he also takes the balls directly on top of it. This may require taking additional balls using the same rule. Notice that the contestant may choose not to take any ball, in which case the prize is zero.

      The TV show director is concerned about the maximum prize a contestant can make for a given stack. Since he is your boss and he does not know how to answer this question, he assigned this task to you.

       

      Input:

      Each test case is described using several lines. The first line contains an integer N representing the number of rows of the stack ( 1$ \le$N$ \le$1000). The i-th of the next N lines contains i integers Bij ( -105$ \le$Bij$ \le$105 for 1$ \le$j$ \le$i$ \le$N); the number Bij is the value of the j-th ball in the i-th row of the stack (the first row is the topmost one, and within each row the first ball if the leftmost one).

      The last test case is followed by a line containing one zero.

       

      Output:

      For each test case output a line with an integer representing the maximum prize a contestant can make from the stack.

      Sample input:

      4
      3
      -5 3
      -8 2 -8
      3 9 -2 7
      2
      -2
      1 -10
      3
      1
      -5 3
      6 -4 1
      0
      

       

      Sample output:

      7
      0
      6

      Added by:Gareev
      Date:2012-07-30
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM Latin America 2011









      SPOJ Problem Set (classical)

      11931. AMZ Word

      Problem code: AMZSEQ


      AmzMohammad is a novice problem setter in Spoj. for start of his work he decided to write a classical and sample problem. ( for UI ACM summer program ) 

      how many N-words(words with n letters) from the alphabet {0,1,2} are such that neighbors differ at most by 1? 

      Input

      an integer N.

      Output

      Number of N-words with told conditions.

      answer is less than 1000000000. it is the only constraint :)

      Example

      Input:
      2
      
      Output:
      7

      Added by:mohammad mahmoodi
      Date:2012-07-31
      Time limit:0.400s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:AmzMohammad ( Mohammad Mahmoodi )









      SPOJ Problem Set (classical)

      11932. Amz Rock

      Problem code: AMZRCK

      To many people in many cultures, music is an important part of their way of life.

       

      AmzMohammad is a fan of rock music. and he have n rock tracks (labled from 1 to n) now he wanna select a playlist.
      in his opinion a good playlist is one that have no two successive tracks.
      in how many ways?

       

      AmzMohammad is a fan of rock music. and he have n rock tracks (labled from 1 to n) now he wanna select a playlist.

      in his opinion a good playlist is one that have no two successive tracks.

      in how many ways?

       

       

       

      Input

      first line = number of test cases

      each testcase in an integer n(number of tracks)

      Output

      Output number of good playlists he can make.

      answer is less than 1000000000. it is the only constraint :)

      Example

      Input:
       2
      1
      2
      
      Output:
      2
      3
      note: a good play list may consist 0 track :)
      note 2: how many persian rock tracks we have?

      Added by:mohammad mahmoodi
      Date:2012-08-01
      Time limit:0.600s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK BASH C# GO ICON ICK WSPC
      Resource:AmzMohammad ( Mohammad Mahmoodi )









      SPOJ Problem Set (classical)

      11933. DIAGONAL

      Problem code: DIG

      You are a given a n sided convex polygon. Find total number of intersections of all diagonals.

      Assume that all the intersection points are different.

      If in case answer exceeds 10^9 + 7 , take modulo 10^9 + 7

      1<=n<=10^8

      Input

      First Line : T (no of test cases)

      Next T line will contain N no of vertices

      Output

      No of intersections of diagonals as specified.

       

      Example

      Input:
      2
      4
      5
       Output:

      1
      5

      Added by:praveen123
      Date:2012-08-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:general problem









      SPOJ Problem Set (classical)

      11935. Decorating the Palace

      Problem code: DEC123

      Problem Statement:
          King of DragonLand likes decorating towers , So one day he decided to decorate  a tower with flowers.
          Heighest floor of tower contains only one room and floor just below every floor except the base floor ,  will have two of it's child buildings on which it is built,
          Note that it's structure is like a binary tree .
          
          for height = 3    
          
                       *
                  *       *
                *   *   *  *
          
          You are given the task of decorating it, But there is a constraint in decorating it , Sum of child floors of a floor will have be equal to no of flowers in parent building and your child floors will have as less difference between number of flowers in them as possible to look your tower beautiful.

          Given that top building contains N flowers and Height of tower H , find out no of ways of decorating it , As this value may be large , output it's modulo 10^ 9 + 7.
          Two decorations are considered different if any floor in them contains different no of flowers
          
          Input :
          T: no of test cases (<= 10)
          than next T line contain H , N
          
          Output : no of different decorations % (10 ^ 9 + 7)
          
          constraint : 1<=H<=50
                       1<=N<=50000
          Example:
          Input:
                  2
                  1 1

                 2 1
          Output:
                  1

                     2

       

      Explanation:

      for 1 1 , it is obvious.

      for 2 1 ,

      There can be two ways: 

           1

      1      0

          1

      0       1


      Added by:praveen123
      Date:2012-08-02
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:general problem









      SPOJ Problem Set (classical)

      11946. Zig-Zag Permutation 2

      Problem code: ZZPERM2


      See ZZPERM problem description. This an improved version with more demanding test cases.

      Input

      The input consists of at most 15 test cases. Each case contains a word (W) not longer than 64 letters and one positive number (D <= 1000000000). The letters of each word are in increasing order. Input is terminated by EOF.

      Output

      For each case output all of the zig-zag permutations of W whose rank is divisible by D, in increasing lexicographic order, one word per line. In the next line print the total number of zig-zag permutations of W. There is no case that produces more than 365 lines of output. Print an empty line after each case.

      Example

      Input:
      j 1
      abc 2
      aaabc 1
      aaabb 2
      aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbcccdd 123456
      aaaaaaaaabbbbbbbbbcccccccccddddddddd 1000000000
      
      
      Output:
      j
      1
      
      bac
      cab
      4
      
      abaca
      acaba
      2
      
      1
      
      babacbcabacabadabababababababababadab
      213216
      
      abacbcacbdadcdbcadbdacbdacbdadbcbcad
      abadadcdcdcdbdbdadbcabacacbdbcbcacab
      acabacbcbdbcbdcdadadacbcadbcbcadadbd
      acacbcbdacbdcdacbcadbdbcbcadadbdabad
      acadbcadbdbcacadbdbcacbdbdacbdbcadac
      acbcacbcadbdadadadbcbdcdabacacbdbdbc
      acbcbdadbdcdbcbcbcacbdadadadadbcacab
      acbdadcdcdadadbdababacbcbcbcacbdbdac
      acbdcdbdbcacbcbcadabadbcabadbdcdacad
      adacbcacbcbcbdcdcdbdadadabadbdbcacab
      adadbcbcadbcabacadbdbcbdabadcdcdacbc
      adbcadbcabacbdacacbcbcbdcdadbdadbdac
      adbdacababacadadcdbcbcadbdacbcbdcdbc
      adbdcdacbdbcbdbcadadadbcadacbcacbcab
      adcdbdacadacbdbcbdadacbcbcadbdbcacab
      babacbdcdbdcdbcadcdbcabacacadadbdacb
      bacacadbdcdbcbdbdcdacbdacabacadbcadb
      bacadcdbcbdabacbcacacadadadcdbdbdbcb
      bacbdadacabacadacbdcdbcadbcbdbcbdadc
      badacadbcadacbcbdadbdbcacbcbdcdabadc
      badbcacbdabadcdbcadbdacabacbdacbdcdc
      badbdcdbdadacbcbcacacbdbdacbdadbcaca
      bcabacadbdbdacacbdadcdadbcbcbcadacbd
      bcacadacbcbdcdbdbcbdbdadadabacbdacac
      bcacbdbdcdcdababadacbcadacacbdbdbcad
      bcadbcadbdbdcdcdadbcbcacbcababadacad
      bcbcabadacadcdadacbdadbcbdcdbcacbdab
      bcbcbcadbcadbcadbdadbcbcadabacadadcd
      bcbdacbdacbdbcbdadacacbdcdbdadacabac
      bcbdbdbdcdacacacbdbcadadbcababacadcd
      bdabadcdbdadbcadcdbcbdcdbcabacabacac
      bdacbcbcbcadadbcadcdabadbcacbdcdabad
      bdadbcabacbcbcababadacadcdcdbdcdacbd
      bdbcacacbdbcadbcbdabacbcadacadadbdcd
      bdbcbdacacbdadbdcdababadadcdbcacbcac
      bdbdbcadbcacadbcadacadbdbdcdbcacacab
      bdcdacbdadadbcbcacacbcacabadbdbcadbd
      bdcdcdadacadcdbdbcababadbcacbcadbcab
      cabacbdcdbdadacacadbcbcacadbcbdbdadb
      cacabadcdbdbdbcbcbdacabadbdacbdacadc
      cacadcdbcbcbdcdacababacbcadbdbdbdada
      cacbdadbdadacbdababacbcbdcdcdcdabacb
      cadacadbdabacbcacbdbdcdadbcadadbcbcb
      cadbcacbcbdcdbdbcadbcbdadabacbdacada
      cadbdbcbdacadbdacadacbdbcbcadbcabadc
      cbcabacbcbdadabacbcadbdadcdcdadacbdb
      cbcadacadadbdbcacbcadbdbdacbcabadcdb
      cbcbcadacbcadadadbcbdacadbcbdbdacadb
      cbcbdbcadcdacbdadacbdbcacadacbdabadb
      cbdacadacbcbdcdbdabadbcbcacabadcdadb
      cbdadbdadabadcdabadcdacbcbcabacbcbdc
      cbdbcbdcdbcbdacacbdadadcdababacabadc
      cbdcdacbdbcbdadacacadbcabababadcdbdc
      cdabadacabadcdbdcdbdbcabadbcbcacadbc
      cdacbcbcadabadcdbdbcbcacbdadadabadbc
      cdadbcacacbcadadbdbdbcabadbcbcbcadad
      cdbcacadbcbdbcadbdadadbdbcacbcadabac
      cdbcbdadadacbdbcabacbcbcabadacadcdbd
      cdbdbcabadcdbdbdcdacacababadbdacacbc
      cdcdacacbcadbcabadbdcdbcbcabadadbdab
      dababacbcbcadbdacacbcacbdbdcdadcdadb
      dabadbdcdacacadabadcdbdbcbcbcacbdbca
      dacadacbdbdbcacbcadbdbcacbcadbdcdaba
      dacbcbdadadcdbdacadcdababacbcacbdbcb
      dadabadbcbcadcdbdacbcadacadbcbcbdbca
      dadbcadadbdcdcdabacbcbdbcacbdbcabaca
      dadcdbcacabadadbcabadbcadcdadbcbcbcb
      dbcacbcadacadbcacbdadacbcbdacbdbdadb
      dbcadcdbcbdbdadbdadbcacbcacacbcabada
      dbcbdacbcadbdacbdadbdacbcadbcacadacb
      dbdacacbdadbcbcbcbcadbdadbcadbcadaca
      dbdbcacadacabacbcadacbdadcdbdbdbcbca
      dbdcdabacadadbcbdcdbcacacbcbdbdacaba
      dcdacadadbcbcabacbcacbdbcbdbcadadadb
      dcdbcadadbcbcadbcbcadabadbdcdbcacaba
      dcdcdacabadbdbdacacbcacbdababadbcbdc
      76317369490
      
      

      Added by:Pawel Gawrychowski
      Date:2012-08-05
      Time limit:12s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:harder version of ZZPERM









      SPOJ Problem Set (classical)

      11947. Counting Words

      Problem code: GSWORDS

      Supervin likes counting. In this problem, he invites you to count together

      Supervin defines a word as "a string only consist of 'o' or 'x'", and additional requirement, for each substring with prime-length, the number of 'o' is not less than the number of 'x'.

      Supervin gives you an integer N (1 <= N <= 10^12). Supervin challenges you to determine how many words can be made with exactly N-length.

      You are having difficulties, make a program to determine how many N-length words. Because the output can be too big, output the number of words modulo 1 000 000 007

      Input

      One line, an integer N

      Output

      One line, an integer indicates how many N-length words modulo 1 000 000 007

      Example

      Input:
      2
      
      Output:
      3
      Input:
      3
      Output:
      4
      Explanation :
      In the first sample, the words can be made are : "oo", "ox", "xo".
      In the second sample, the words can be made are : "ooo", "oox", "oxo", "xoo"

      Added by:Jonathan Irvin Gunawan
      Date:2012-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Jonathan Irvin Gunawan, used in TOKI OpenContest March 2012









      SPOJ Problem Set (classical)

      11948. Dark Assault

      Problem code: DARKASLT


      Original statement

      Rainbowland is a planet full of life and adorable beings, however, this night, the spies Andreina, Marge and Teresa agreed to breakdown the security of a building led by a teddy bear, this teddy bear is mean! Don't get the wrong idea, the rainbowland spies agency (RSA) just want to make things go right in they colorful and lovable world.

      Andreina offered a plan to take control of the building, she and Teresa will go to the roof of another building, seeing the target building, they will tell Marge to take down N rivals on a building of F floors, as she won't use the stairs, there are a series of E elevators that are in the building, the elevator can only go up or down P floors (more explanation on input details).

      While Andreina and Teresa sees from outside, Marge must take down immediately the rivals, so they cannot leave them alive, otherwise, they will alert the others and the mission will be failed, when fighting a rival, the rival loses K points of life during each second using normal abilities, you can always assume that Marge won't fail at any fight, in addition, Marge can use some special abilities, these abilities allow Marge to deliver powerful blows, however, these special abilities can only be used once, so she must use it wisely, as Marge doesn't want to waste energy on a single enemy, she will give two special ability punches at most, if she can do it. She can always combine, so at last, she will choose between what is best (If normal attacking, if using one special ability or two and normal attacking).

      Help the spies Andreina, Teresa and Marge to find the minimum time so they can take the building and defeat all the rivals, having in consideration that:

      1. Marge takes one minute to use the elevator.

      2. Each round of fight lasts one minute.

      3. Marge starts from floor 1 and she can go from floor 1 to F, never lower nor higher.

      4. If Marge uses an special ability or two special abilities, it will still count as she uses on one round (see point 2).

      5. There will be from 1 to 7 rivals in all the building.

      6. The floor 1 will be always rival free, therefore, the floor 1 will have a value of zero (0).

       

      INPUT DETAILS:

      First line will contain an integer T denoting T description of the test cases.

      For each T you will have four integers F, N, K, E denoting, respectively, the number of floors in the building, the number of special ability that Marge can use, the damage K that Marge delivers after a single blow and the number E of elevators.

      Then, in the next line, F integers separated by a single space will follow, denoting the description of the building, a number 0 means that there are no rivals at the floor, a positive number will represent the life points that the rival has at the moment of the assault.

      The next line will contain N integers separated by a single space representing the values of a special blow given by Marge, remember that she can only deliver two blows at most for each rivals and she can use only once the special blow.

      The next line will contain E integers separated by a single space, meaning the description of the elevators, for each positive number means that the elevator will go up P floors, if the number is negative, means that the elevator will go down P floors, you can always asume that P will never be 0.

       

      OUTPUT DETAILS:

      For each test case, print the string “Scenario #i: V“ where i denotes the i-th test case you're analyzing (starting from 1) and V is the minimum time that the team can defeat the all rivals, print -1 if the mission will fail.

       

       

       

      INPUT

      OUTPUT

      3

      4 2 3 2

      0 10 0 15

      10 5

      2 -1

      10 4 2 5

      0 0 0 10 0 8 7 8 10 100

      10 10 10 80

      2 -1 5 -3 1

      3 3 2 1

      0 100 100

      150 200 150

      2

      Scenario #1: 8

      Scenario #2: 26

      Scenario #3: -1

       

      Explanation of the first test case:

      At time 1, Marge goes from floor 1 to floor 3, then, from floor 3 to floor 2, she choose to beat the rival with life 10 with normal blows (it will take 4 units of time to beat it), at this time Marge has already wasted 6 minutes of time, then, she will take the elevator up to floor 4, then will use her two special abilities to deliver a powerful blow on rival at floor 4 with 15 life points (15-10-5 = 0) beating it. Final time of the mission, 8.

       

      CONSTRAINTS:

       

      1<=T<=10

      2<=F<=128

      1<=N<=7

      1<=K<=1000

      1<=E<=50

      0<=Fi<=1000

      1<=Ni<=1000

      -F<=Ei<=F with Ei != 0

       

      Clarification: There is no blank lines between Scenarios in the output.


      Added by:Venezuelan Programming League
      Date:2012-08-07
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      11952. Intergalactic Highways

      Problem code: IGALAXY

      ORIGINAL STATEMENT 

      The world is on constant evolution, the humans evolved to a galactic civilization at the year 700,000, they are now capable of going instantly to any other planet in 1 unit of time, however, they must stop sometimes in a planet to avoid a horrible collision against an asteroid.

      Rudolph-X3000, a single humanoid, wants to visit his family visiting as fewer planet as possible from planet A to planet B inclusive without repeating any planet, he is in a hurry so he need the answer quickly. Can you determine how many planets is going to visit?

      As Rudolph-X3000 is an intergalactic traveler, he want to determine the planets he is going to visit as well, if there exists more than a single shortest path between planet A and B, print the one lexicographically smallest, if there isn't exists such route, print -1.

      The human race knows now the Delta Velocity, this velocity allows to move in a single unit of time at a very fast speed from a place i to place j. So you can consider the distance between planets will be always of 1.

       

      INPUT:

      The first line will contain an integer T representing T test cases

      Then, in the next line, there will be an integer R denoting the number of relations between planet, a relation is considered so that from a planet i you can go to planet j, this relation is symmetric, so the path between (i,j) is the same as (j,i)

      The next R lines will contain two strings P and Q, these strings will denote the name of a planet P and a name of a planet Q and their relation.

      The last line will contain two strings S and D, representing the origin planet and the destiny planet.

      Note: All the strings will have the combination of uppercase and lowercase letters [A-Z] [a-z].

       

      OUTPUT:

      For each test case you shall print the string “Scenario #i: “ where i is the test case you're analyzing (starting from 1) followed by the minimum number of planets, then, in the next line, you should list each planet visit (including origin and destiny), each one separated by a single space.

      SAMPLE CASE:

      INPUT

      OUTPUT

      3

      8

      Mercury Venus

      Venus Earth

      Earth Mars

      Mars Jupiter

      Jupiter Saturn

      Saturn Uranus

      Uranus Neptune

      Neptune Pluto

      Earth Pluto

      7

      Mesopotamia Merrick

      Merian Earth

      Earth Venus

      Merian Merrick

      Venus Mesopotamia

      Pluto Earth

      Mesopotamia Pluto

      Mesopotamia Earth

      2

      Earth Sun

      Moon Venus

      Earth Moon

      Scenario #1: 7

      Earth Mars Jupiter Saturn Uranus Neptune Pluto

      Scenario #2: 3

      Mesopotamia Pluto Earth

      Scenario #3: -1

       

      Explanation of the second case:

      There are two possible routes for going from Mesopotamia to Earth, one is “Mesopotamia → Pluto → Earth”, the other one is “Mesopotamia → Venus → Earth”, we select the lexicographically smaller.

       

      CONSTRAINTS:

      1<=T<=100

      1<=R<=100,000

      1<=|{P.Q.S.D}|<=50

       

      It is safe to say that there will be no more than 10,000 distinct planets.


      Added by:Venezuelan Programming League
      Date:2012-08-08
      Time limit:25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set ()

      11956. Addicted

      Problem code: TLL237

      jhon is compulsive saver, he keeps and amount "n" of piggy banks locked in his room.
      
      He has a list which he wrote with a sequence of 1's and 2's that indicate the way that Jhon will 
      deposit his money on the piggy banks. Every time Jhon gets a penny he rushes to his room and 
      picks the 2 piggy banks who have the less amount of money, then he looks at the next number 
      on the sequence. If that number is one (1) he deposits the penny on the piggy bank with the lesser 
      amount of money. If that number is two (2) he deposits the penny on the next piggy bank with 
      the lesser amount of money.
      
      Your task is to write a program to help Jhon to determine what is the amount in the 2 piggy 
      banks with less money once the sequence is over
      
      if more than two have the lowest amount of money choose those with lowest indexes.
      you can assume that n <= s

      Input

      the input is a unique date set
      
      n is the number of piggy banks, 2 <= n <= 10^5
      s is the sequence with 1's and 2's, 1 <= size(s)  <= 10^5

      Output

      a line containing what is the amount in the 2 piggy banks with less money once the sequence is over, 
      sorted from lowest to highest.

      Example

      Input:
      3
      111112
      
      Output:
      1 2

      Added by:tille
      Date:2012-08-10
      Time limit:0s-0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:tille









      SPOJ Problem Set (classical)

      11962. Arya Rage

      Problem code: MNNITAR

       

      Arya is very fond of fibonacci numbers.He claimed he can solve any problem on fibonacci number.His clever friend golu gave him a challengeÂ

      to prove his skills.He gave him a sequence which he called exponacci.The sequence is given by
      g(n)=2^f(n-1)for n>0
      g(0)=1for n==0
      f(n) denotes the nth fibonacci number where
      f(0)=1
      f(1)=1(Obviously golu is not as good as arya in fibonacci numbers so he believes f(0)=1,anyways we have chosen not to disturb him)
      f(n)=f(n-1)+f(n-2)for n>1
      Help arya to find the nth exponacci number.Since the numbers can be very large take mod 10^9+7

      Input :Â
      The first line of the input will be the number of test cases(T<=2000). For each test case first line contains one integers n 0 <= n <= 10^15

      Output :
      The value of g(n)%(10^9+7)

      Warning: value of n won't fit in int,use long long int instead

      Sample Cases :
      Input:
      2
      3
      5
       
      Output:
      4
      32
      

      Added by:bashrc is back
      Date:2012-08-10
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11963. Packing Rectangles

      Problem code: PACKRECT

      Four rectangles are given. Find the smallest enclosing (new) rectangle into which these four may be fitted without overlapping. By smallest rectangle, we mean the one with the smallest area.

      All four rectangles should have their sides parallel to the corresponding sides of the enclosing rectangle.

      Rectangles may be rotated 90 degrees during packing.

      There may exist several different enclosing rectangles fulfilling the requirements, all with the same area. You must produce all such enclosing rectangles.

      Input

      Four lines, each containing two positive space-separated integers that represent the lengths of a rectangle's two sides. Each side of a rectangle is at least 1 and at most 50.

      Output

      The output file contains one line more than the number of solutions. The first line contains a single integer: the minimum area of the enclosing rectangles. Each of the following lines contains one solution described by two numbers p and q with p<=q. These lines must be sorted in ascending order of p, and must all be different.

      Example

      Input:
      
      1 2
      2 3
      3 4
      4 5
      
      Output:

      40
      4 10
      5 8

      Added by:nhs
      Date:2012-08-10
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOI 95









      SPOJ Problem Set (classical)

      11984. Dome of Circus

      Problem code: DOMECIR


      Description

      A travelling circus faces a tough challenge in designing the dome for its performances. The circus has a number of shows that happen above the stage in the air under the dome. Various rigs, supports, and anchors must be installed over the stage, but under the dome. The dome itself must rise above the center of the stage and has a conical shape. The space under the dome must be air-conditioned, so the goal is to design the dome that contains minimal volume. 
      You are given a set of n points in the space; (xi, yi, zi) for 1 <= i <= n are the coordinates of the points in the air above the stage that must be covered by the dome. The ground is denoted by the plane z = 0, with positive z coordinates going up. The center of the stage is on the ground at the point (0, 0, 0). 
      The tip of the dome must be located at some point with coordinates (0, 0, h) with h > 0. The dome must have a conical shape that touches the ground at the circle with the center in the point (0, 0, 0) and with the radius of r. The dome must contain or touch all the n given points. The dome must have the minimal volume, given the above constraints. 

      Input

      The first line of the input file contains a single integer number n (1 <= n <= 10 000) — the number of points under the dome. The following n lines describe points with three floating point numbers xi, yi, and zi per line — the coordinates of i-th point. All coordinates do not exceed 1000 by their absolute value and have at most 2 digits after decimal point. All zi are positive. There is at least one point with non-zero xi or yi.

      Output

      Write to the output file a single line with two floating point numbers h and r — the height and the base radius of the dome. The numbers must be precise up to 3 digits after decimal point.

      Sample Input

      #11
      1.00 0.00 1.00
      #22
      1.00 0.00 1.00
      0.00 1.50 0.50
      #33
      1.00 0.00 1.00
      0.00 1.50 0.50
      -0.50 -0.50 1.00

      Sample Output

      #13.000 1.500
      #22.000 2.000
      #32.000 2.000

      Added by:Gareev
      Date:2012-08-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Northeastern Europe 2010









      SPOJ Problem Set (classical)

      11985. Gao on a tree

      Problem code: GOT


      There's a tree, with each vertex assigned a number. For each query (a, b, c), you are asked whether there is a vertex on the path from a to b, which is assigned number c?

      Input

      There are multiple cases, end by EOF.
      For each case, the first line contains n(n<=100000) and m(m<=200000), representing the number of vertexes (numbered from 1 to n) and the number of queries.
      Then n integers follows, representing the number assigned to the ith vertex.
      Then n-1 lines, each of which contains a edge of the tree.
      Then m lines, each of which contains three integers a, b and c(c<=n),  representing a query.

       

       

      Output

      You should output "Find" or "NotFind" for every query on one line.
      Output a blank line AFTER every case.

       

       

      Example

      Input:
      
      5 5
      1 2 3 4 5
      1 2
      1 3
      3 4
      3 5
      2 3 4
      2 4 3
      2 4 5
      4 5 1
      4 5 3
      Output:
      NotFind
      Find
      NotFind
      NotFind
      Find

      Added by:lxyxynt
      Date:2012-08-17
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      11986. ROMAN NUMERALS

      Problem code: ROMAN008

      You are given two numbers in Roman system(modern  Roman Numerals) and an operator. Output is the result in roman system.

      Input

      You are given two space separted number in roman system and after space an operator on the same line.Operator can be +,-,/,*,%.

      Numbers a,b: 1<=a,b<5000

      eg:4000=MMMM, for numbers >=4000, you should use MMMM.....

      for others as per definition

      Input consists of 5 testcases.

      Output

      Output is the result<5000 of performing the operation. Print on separte line

      Example

      Input:
      LX XV +
      X V *
      
      Output:
      LXXV
      L
      //problem placement changed to challenge

      Added by:himanshu jain
      Date:2012-08-17
      Time limit:0.119s
      Source limit:2000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: F# JS
      Resource:own problem









      SPOJ Problem Set (classical)

      11997. Trip To London

      Problem code: DCEPC803

      Mary and Saina participated in London Olympics 2012 and won medals for IndiaJ. After these historic moments, they planned to travel and see various places in London. Since it was their first time in the city, they bought a map to various connecting routes across London. However, the map was not proper as it had a missing entry for one route. They asked the tour planning authorities to get the correct map but all they could get was the shortest distance route map rather than the original map which gives direct distance between any 2 places in London. Mary and Saina prefer taking the direct route rather than the shortest route for travelling. Can you help them calculate the no. of possible values of direct distance which is unknown in the original map? Assume that the places are never more than 100km apart (i.e. direct distance).

      Input

      First line contains N, the no. of places in London.

      Next N lines contains total N^2 integers, N space separated integers per line (the direct distance map). The jth column in the ith line contains either a non-negative integer (the distance from ith place to jth place), or -1 indicating the missing entry in the map.

      Next N lines contains total N^2 integers, N space separated integers per line (the shortest distance map). The jth column in the ith line contains a non-negative integer (the shortest distance from ith place to jth place).

      Note that direct distance from ith to jth city is not always equal to direct distance between jth to ith city and distance between a city to itself is always 0.

      Output

      Output the no. of possible values the missing entry (marked -1 in the original map) takes assuming that shortest distance map is correct.

      Output

      2<=N<=20

      All distances are between 0 to 100 (including both).

      Example

      Input:
      
      4
      0 51 61 63
      -1 0 66 24
      80 83 0 71
      60 64 52 0
      0 51 61 63
      84 0 66 24
      80 83 0 71
      60 64 52 0
      Output: 17

      Added by:dce coders
      Date:2012-08-19
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set ()

      11998. Totient Fever

      Problem code: DCEPC804

      Another Totient problem by Ankur Sir J. He is madly in love with totient. Let’s see what he has prepared this time.

      Recently he was studying integral properties of Quadratic functions. He found some interesting notions of real and complex numbers through Quadratic functions. But as you know he is a big totient fan, he mixed totient with quadratic functions this time and that resulted into a nice problem. He wants to find out if there exists a real root ‘x’ in the equation below:

      Totient(a*x^2 + b*x + c) = k

      Given ‘a’, ‘b’, ‘c’ and ‘k’, output “Yes” if a real root exists or “No” if no real root exists.

      Input

      First line contains T, the no. of test cases.

      Each of the next T lines contains a, b, c and k.

      Output

      Output T lines, each for a single test case, containing either a “Yes” or a “No” corresponding to the test case.

      Constraints

      0<T<=100

      0<a<=10^6

      0<b<=10^6

      0<c<=10^6

      0<k<=10^6

      b^2 >= 4*a*c

      Example

      Input:
      2
      1 4 3 4
      1 21 11 10
      
      Output:
      Yes
      Yes

      Added by:dce coders
      Date:2012-08-19
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12001. Bit by Bit

      Problem code: DCEPC807


      Alice and Bob play an interesting game. They start with a number “n” and follow some rules until the game ends. The rules for the game are:

      1. Let F(n) denotes the total no. of set bits in binary representation of numbers from 0 to (2^n) -1.
      2. Each player plays alternatively until the game ends and one of them wins the game.
      3. In each turn a player either unsets a single set bit from binary representation of “n” or unsets 2 consecutive set bits from the binary representation of “n”. Let’s call the resulting number after such move as “x”.
      4. The game ends when F(x) is a power of 2. (0 is also a power of 2).
      5. The player with no move loses the game and so other player wins the game.
      6. Alice starts the game always.
      7. Both of them play optimally.

      Given “n” can you predict the winner of the game?

      Input

      First line contains T, the no. of test cases.

      Next T lines contains one integer per line, “n” (quotes for clarity).

      Output

      Output T lines, each containing either “Alice” if Alice wins the game or “Bob” if Bob wins the game. 

      Constraints

      1<=T<=10

      0<=N<=10^6

      Example

      Input:
      2
      4
      10
      Output:
      Bob
      Alice

      Added by:dce coders
      Date:2012-08-19
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA NODEJS PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set ()

      12004. Cousin Wars

      Problem code: DCEPC810

      Sunny is fond of words. He got a new game to play with his cousin Sonali.He gives her a long string and two other smaller strings(A and B).Now he asks Sonali to find the number of all the subsequences of the long string that are greater than equal to smaller string A and less than equal to smaller string B.

      Help Sonali to find the answer.

      Note : Comparison of two strings is regarded same as that done by the string:compare function.

      Empty string is not regarded as a subsequence.

      Input

      Each input consists of 3 lines.First line has the TEXT string.

      2nd and 3rd line contain two smaller strings A and B .

       

      Output

       

      One number which gives the count such that

      A <= subsequence of (TEXT) <= B

       

      Constraints

      Input will consist of all lowercase characters.

      1 <= Length of TEXT <= 25

      1<= Length of A and B <= Length of TEXT

       

       

      Example

      Input:
      coforc
      co
      fc
      
      Output:
      24

      Added by:dce coders
      Date:2012-08-19
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12005. Grass Planting

      Problem code: GRASSPLA


       

      Farmer John has N barren pastures (2 <= N <= 100,000) connected by N-1 
      bidirectional roads, such that there is exactly one path between any two 
      pastures.  Bessie, a cow who loves her grazing time, often complains about 
      how there is no grass on the roads between pastures.  Farmer John loves 
      Bessie very much, and today he is finally going to plant grass on the
      roads.  He will do so using a procedure consisting of M steps (1 <= M <=
      100,000).
      At each step one of two things will happen:
      - FJ will choose two pastures, and plant a patch of grass along each road in
      between the two pastures, or,
      - Bessie will ask about how many patches of grass on a particular road, and 
      Farmer John must answer her question.
      Farmer John is a very poor counter -- help him answer Bessie's questions!
      PROBLEM NAME: grassplant
      INPUT FORMAT:
      * Line 1: Two space-separated integers N and M
      * Lines 2..N: Two space-separated integers describing the endpoints of
              a road.
      * Lines N+1..N+M: Line i+1 describes step i. The first character of
              the line is either P or Q, which describes whether or not FJ
              is planting grass or simply querying. This is followed by two
              space-separated integers A_i and B_i (1 <= A_i, B_i <= N)
              which describe FJ's action or query.
      SAMPLE INPUT (file grassplant.in):
      4 6
      1 4
      2 4
      3 4
      P 2 3
      P 1 3
      Q 3 4
      P 1 4
      Q 2 4
      Q 1 4
      OUTPUT FORMAT:
      * Lines 1..???: Each line has the answer to a query, appearing in the
              same order as the queries appear in the input.
      SAMPLE OUTPUT (file grassplant.out):
      2
      1
      2

      Problem description:

      Farmer John has N barren pastures (2 <= N <= 100,000) connected by N-1  bidirectional roads, such that there is exactly one path between any two  pastures.  Bessie, a cow who loves her grazing time, often complains about  how there is no grass on the roads between pastures.  Farmer John loves  Bessie very much, and today he is finally going to plant grass on the roads.  He will do so using a procedure consisting of M steps (1 <= M <= 100,000).


      At each step one of two things will happen:

      - FJ will choose two pastures, and plant a patch of grass along each road in between the two pastures, or,

      - Bessie will ask about how many patches of grass on a particular road, and  Farmer John must answer her question.


      Farmer John is a very poor counter -- help him answer Bessie's questions!


      INPUT FORMAT:


      * Line 1: Two space-separated integers N and M

      * Lines 2..N: Two space-separated integers describing the endpoints of a road.

      * Lines N+1..N+M: Line i+1 describes step i. The first character of the line is either P or Q, which describes whether or not FJ is planting grass or simply querying. This is followed by two space-separated integers A_i and B_i (1 <= A_i, B_i <= N) which describe FJ's action or query.


      SAMPLE INPUT :


      4 6

      1 4

      2 4

      3 4

      P 2 3

      P 1 3

      Q 3 4

      P 1 4

      Q 2 4

      Q 1 4


      OUTPUT FORMAT:


      * Lines 1..???: Each line has the answer to a query, appearing in the same order as the queries appear in the input.


      SAMPLE OUTPUT:


      2

      1

      2

       


      Added by:Gareev
      Date:2012-08-19
      Time limit:2s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:USCAO contests









      SPOJ Problem Set (classical)

      12007. Fibonaccibonacci (easy)

      Problem code: FRS2

      Leo would like to play with some really big numbers, OK...

      Let FIB the Fibonacci function :
      FIB(0)=0 ; FIB(1)=1
      and
      for N>=2 FIB(N) = FIB(N-1) + FIB(N-2)

      Example : we have FIB(6)=8, and FIB(8)=21, so FIB(FIB(6))=21

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are an integer N.

      Output

      For each test case, print FIB(FIB(N)) ,
      as the answer could not fit in a 64bit container,
      give your answer modulo 1000000007.

      Example

      Input:
      3
      0
      5
      6
      
      Output:
      0
      5
      21
      

      Constraints

      1 <= T <= 10^4
      0 <= N <= 10^100
      

      Time limit is set to allow (sub-optimal) 500B of python3 code to get AC.
      A near optimal solution is within 0.02 and 0.04s with a fast language, and around 1s in Python2 without psyco.


      Added by:Francky
      Date:2012-08-19
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      12008. Fibonacci recursive sequences (medium)

      Problem code: FRSKT

      Let FIB the Fibonacci function :
      FIB(0)=0 ; FIB(1)=1
      and
      for N>=2 FIB(N) = FIB(N-1) + FIB(N-2)

      Example : we have FIB(6)=8, and FIB(8)=21.

      Let F(K, N) a new function:
      F(0, N) = N for all integers N.
      F(K, N) = F(K-1, FIB(N) ) for K>0 and all integers N.

      Example : F(2, 6) = F(1, FIB(6) ) = F(0, FIB( FIB(6) ) ) = FIB( FIB(6) ) = FIB(8) = 21

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are three integers: K, N, M.

      Output

      For each test case, print F(K, N),
      as the answer could not fit in a 64bit container,
      give your answer modulo M.

      Example

      Input:
      3
      4 5 1000
      3 4 1000
      2 6 1000
      
      Output:
      5
      1
      21
      

      Constraints

      1 <= T <= 10^3
      0 <= K <= 10^2
      0 <= N <= 10^9
      2 <= M <= 10^9
      

      You would perhaps have a look, after, at the hard edition with more difficult constraints.


      Added by:Francky
      Date:2012-08-19
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      12009. Fibonacci recursive sequences (hard)

      Problem code: FRSKH

      Leo searched for a new fib-like problem, and ...
      it's not a fib-like problem that he found !!! Here it is.

      Let FIB the Fibonacci function :
      FIB(0)=0 ; FIB(1)=1
      and
      for N>=2 FIB(N) = FIB(N-1) + FIB(N-2)

      Example : we have FIB(6)=8, and FIB(8)=21.

      Let F(K, N) a new function:
      F(0, N) = N for all integers N.
      F(K, N) = F(K-1, FIB(N) ) for K>0 and all integers N.

      Example : F(2, 6) = F(1, FIB(6) ) = F(0, FIB( FIB(6) ) ) = FIB( FIB(6) ) = FIB(8) = 21

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are three integers: K, N, M.

      Output

      For each test case, print F(K, N),
      as the answer could not fit in a 64bit container,
      give your answer modulo M.

      Example

      Input:
      3
      4 5 1000
      3 4 1000
      2 6 1000
      
      Output:
      5
      1
      21
      

      Constraints

      1 <= T <= 10^3
      0 <= K <= 10^18
      0 <= N <= 10^18
      2 <= M <= 10^18
      

      K, N, M are uniform randomly chosen.

      You would perhaps have a look, before, at the medium edition with easier constraints.


      Added by:Francky
      Date:2012-08-19
      Time limit:40s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      12012. grace marks

      Problem code: MTHUR

      In earlier days , grading  in  BITS  used to be absolute , instead of relative grading scheme .
      Once Professor Mathur decided to conduct a surprise quiz, and many students were caught unaware of it. 
      Their scores of the students came out to be much worse than the previous years scores.


      Professor Mathur really believed that true test of talent comes in difficult situations and continued such horrifying sequences of tests . But finally poor placements of his students turned the heat up for the professor and he decided to revise everyone's marks .
       
      Now being a qualified mathematician , professor mathur applied a simple strategy to this.
      He decided to award some constant grace marks to each and every student.
      He took every students last year marks and then added up the absolute difference with the
      revised current year marks  . And he decided to choose the grace marks with the least sum of absolute difference .
      ie. sum( abs (a[i] - (b[i]+grace) )  ) should be minimum .
      Also , prof. Mathur had a knack of choosing the grace value from his very set of favourite numbers .


      Now that our students are happily placed in  'Microsoft' , 'Adobe' for the good Cool, credit finally goes to professor "mathur" .
      Now , decide for each input ,what grace marks were given by mathur .
      (if there are many such grace marks , choose the lowest one) .

      Input

      First line , t for number of testcases. Next 5*t line for each testcase .
      First line of every testcase : integer n.
      Second line : n integers showing previous years marks of every student .
      Third line : n integers showing present years marks of every student .
      Fourth line : intger m
      Fifth line : m integers showing the possible values for grace marks

      Output

      Output the expected grace marks .

      Example

      Input:
      1
      5
      9 10 7 3 10
      4 1 4 1 3
      6
      0 1 2 3 4 5

      Output: 5

      contraints :
      number of testcases , t < 20
      maximum number of students : n < 10000
      1 <= m,marks[i] <= 50000

      Added by:Romal Thoppilan
      Date:2012-08-20
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PERL 6 PYTH 3.2.3 n
      Resource:own problem









      SPOJ Problem Set (classical)

      12030. Blackout

      Problem code: BLACKOUT

      Caracas, as any other city, never sleeps, however, this is about to change as the Chief Officer Marcos “the little one” is scheduling some blackouts to search an important criminal and bring it to justice (If you like to know the criminal is known as “El Pran Malandroso”), the criminal is known for fainting when he doesn't see any source of light, so this is a perfect plan for Marcos “the little one” to trap him and capture him.

      Marcos will give you the map where he is searching the criminal, the zone is given in a matrix and each value represents a block, surrounded by streets, where the number at the i-th row and j-th column denotes the number of people living in this block.

      As Marcos “the little one” is a good officer, he doesn't wants to bother more than a specific number of people, as when he darken the zone, the people will going to be mad. That's what he called you for, Marcos will give you the north-west corner and the south-east corner, he will search in this specific area, causing a blackout.

      Marcos will perform a series of blackouts in the city during the night, he will perform each blackout in a given zone, he will return the city all of its light and then he will perform another blackout, so on until he does Q blackouts, as the criminal is constantly moving in the city, the blackout will be independent and the area of searching will be always considered different.

      Knowing this, can you maximize the area searched without exceeding the limit that Marcos gives you? (Citizens will be going mad when a blackout occurs)

       

      INPUT:

      The first line will contain 4 integers N, M, Q and K, denoting, respectively the N and M matrix size denoting an aerial view of the city, Q blackouts that Marcos the little one will do and K people that he wants to bother as much.

      Then, N lines follow, each containing M integers, representing the people living in the block.

      After that, Q lines will follow, each one containing four integers denoting the (i,j) point of the north-west corner and the (i,j) point of the south-east corner.

       

      OUTPUT:

      The first and only line of output should contain a number, representing the maximum area that Marcos can look for the criminal.

       

      SAMPLE1:

      INPUT

      OUTPUT

      3 3 2 20

      1 2 3

      4 5 6

      7 8 9

      1 1 3 3

      1 1 2 2

      4

      Is important to note that each blackout is independent from the other, so, blackout affecting the zone (1,1) to (3,3) will lead to 45 people angry and 9 units of area, while a blackout from the zone (1,1) to (2,2) will get 12 people angry and 4 units of area. If the limit were 57, you could perform the two blackouts, giving a total result of 13.

      SAMPLE2:

      INPUT

      OUTPUT

      4 3 3 76

      1 4 9

      5 5 2

      2 1 9

      9 1 9

      2 1 4 3

      1 1 4 3

      2 1 3 2

      16

       

      CONSTRAINTS:

      1 <= N,M <= 2000

      1 <= Q <= 1000

      1 <= K <= 1000

      0 <= (Ni,Mj) <= 1000

      It is safe to say that there will be always an answer to this problem. (You will always find at least one blackout that doesn't bother more than K citizens)


      Added by:Venezuelan Programming League
      Date:2012-08-23
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12076. Longest Common Subsequence

      Problem code: LCS0

      No imagination at the moment.

      Input

      You will be given two lines. The first line will contain the string A, the second line will contain the string B. Both strings consist of no more than 50000 lowercase Latin letters.

      Output

      Output the length of the longest common subsequence of strings A and B.

      Example

      Input:

      abababab
      bcbb

      Output:

       3


      Added by:Tooru Ichii
      Date:2012-08-25
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Folklore









      SPOJ Problem Set (classical)

      12107. All Possible Barns

      Problem code: ALLBARN2



      Farmer John is going to build a new rectangular barn. But the 4 corners of  
      the barn mustn't be on soft soil. He examined the ground and found that  
      there are only N (4 <= N <= 1,000) appropriate points for the corners. He
      wants to know the number of possible ways to build the new barn.
       
      Given the points, help him find the answer.
       
      INPUT FORMAT:
       
      Input exactly contains 10 test cases each of them as follows:
       
      * Line 1: A single integer, N.
       
      * Lines 2..N+1: Each line has two space-separated integers x, y which
              are the coordinates  of a point. The magnitude of the
              coordinates is not more than 16,000. All points will be
              distinct.
       
      SAMPLE INPUT :
       
      8
      1 2
      1 -2
      2 1
      2 -1
      -1 2
      -1 -2
      -2 1
      -2 -1
       
      [and 9 more Test cases ....]
       
      OUTPUT FORMAT:
       
      For each Test case print one line contains:
       
      * The number of possible ways to build the new barn.
       
      SAMPLE OUTPUT :
       
      6
       
      [and 9 more Test cases ....]
       
      OUTPUT DETAILS:
       
      the answers are: {1,2,6,5}, {1,3,6,8}, {1,4,6,7}, {2,3,5,8}, {2,4,5,7},
      {3,4,8,7}


      Added by:Hussain Kara Fallah
      Date:2012-08-28
      Time limit:1s-7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Syrian Qualifications for IOI Round #5









      SPOJ Problem Set (classical)

      12108. Linear Garden

      Problem code: LINEGAR

       

      Ramesses II has just returned victorious from battle. To commemorate his
      victory, he has decided to build a majestic garden. The garden will contain
      a long line of plants that will run all the way from his palace at Luxor to
      the temple of Karnak. It will consist only of lotus plants and papyrus
      plants, since they symbolize Upper and Lower Egypt respectively.
      
      The garden must contain exactly N plants. Also, it must be balanced: in any
      contiguous section of the garden, the numbers of lotus and papyrus plants
      must not differ by more than 2.
      
      A garden can be represented as a string of letters ‘L’ (lotus) and ‘P’
      (papyrus). For example, for N=5 there are 14 possible balanced gardens. In
      alphabetical order, these are: LLPLP, LLPPL, LPLLP, LPLPL, LPLPP, LPPLL,
      LPPLP, PLLPL, PLLPP, PLPLL, PLPLP, PLPPL, PPLLP, and PPLPL.
      
      The possible balanced gardens of a certain length can be ordered
      alphabetically, and then numbered starting from 1. For example, for N=5,
      garden number 12 is the garden PLPPL.
      
      TASK
      
      Write a program that, given the number of plants N and a string that
      represents a balanced garden, calculates the number assigned to this garden
      modulo some given integer M. Note that for solving the task, the value of M
      has no importance other than simplifying computations.
      
      CONSTRAINTS
      
      1 <= N <= 1,000,000
      7 <= M <= 10,000,000
      
      INPUT FORMAT:
      
      * Line 1: N, the number of plants in the garden
      
      * Line 2: M
      
      * Line 3: A string of N characters ‘L’ (lotus) or ‘P’ (papyrus) that
              represents a balanced garden.
      
      SAMPLE INPUT :
      
      5
      7
      PLPPL
      
      OUTPUT FORMAT:
      
      * Line 1: Your program must write to the standard output a single line
              containing one integer between 0 and M-1 (inclusive), the
              number assigned to the garden described in the input, modulo
              M.
      
      SAMPLE OUTPUT :
      
      5
      
      OUTPUT DETAILS:
      
      The actual number assigned to PLPPL is 12. So, the output is 12 modulo 7,
      which is 5.

       


      Added by:Hussain Kara Fallah
      Date:2012-08-28
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IOI 2008









      SPOJ Problem Set (classical)

      12125. Fibonacci With a Square Root

      Problem code: FIBOSQRT

      FIBONACCI is the recursive sequence that is given by: F(n)=F(n-1)+F(n-2) with F(0)=0 and F(1)=1
      In this problem we define FIBOSQRT that is given by: Fs(n)=Fs(n-1)+Fs(n-2)+2*SQRT(3+Fs(n-1)*Fs(n-2)) with Fs(0) and Fs(1) are given in the input file.
      It's guaranteed that SQRT(3+Fs(n-1)*Fs(n-2)) is always an integer. Wink I've proved it by math theorem.

      Now your task is to find Fs(n)
      Since the number can be Big you have to find the result mod M.

      Input

      The first line is an integer T(1 ≤ T ≤ 111,111), denoting the number of test cases. Then, T test cases follow.

      For each test case, there are four integers Fs(0),Fs(1)(1 ≤ Fs(0) ≤ Fs(1) < 106), M(1 ≤ M < 109), and n(0 ≤ n < 1018) written in one line, separated by space.

      Output

      For each test case, output Fs(n) mod M.

      Example

      Input:
      2
      1 1 10 5
      2 3 100 6
      
      Output:
      4
      82

      Explanation:
      Case #1:
      • Fs(0)=1
      • Fs(1)=1
      • Fs(2)=1+1+2*SQRT(3+1*1)=6
      • Fs(3)=6+1+2*SQRT(3+6*1)=13
      • Fs(4)=13+6+2*SQRT(3+13*6)=37
      • Fs(5)=37+13+2*SQRT(3+37*13)=94

      The answer is: 94 mod 10 = 4.

      Case #2:
      • Fs(0)=2
      • Fs(1)=3
      • Fs(2)=3+2+2*SQRT(3+3*2)=11
      • Fs(3)=11+3+2*SQRT(3+11*3)=26
      • Fs(4)=26+11+2*SQRT(3+26*11)=71
      • Fs(5)=71+26+2*SQRT(3+71*26)=183
      • Fs(6)=183+71+2*SQRT(3+183*71)=482

        The answer is: 482 mod 100 = 82.

      Input File:
      File #1: More than 100,000 random test cases (test your program speed Laughing)
      File #2: Less than 10 test cases (tricky test cases that might give you WA Tongue out)

       

      Time Limit ≈ 8*(My Program Top Speed)

       

      Warning: large Input/Output data, be careful with certain languages


      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2012-08-30
      Time limit:5s-50s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12150. Just Next !!!

      Problem code: JNEXT


      JUST NEXT !!!
      DevG likes too much fun to do with numbers. Once his friend Arya came and gave him a challenge, he gave DevG an array of digits which is forming a number currently (will be called as given number). DevG was challanged to find the just next greater number which can be formed using digits of given number. Now DevG needs your help to find that just next greater number and win the challenge.
      Input: 
      The first line have t number of test cases (1<=t<=100). In next 2*t lines for each test case first there is number n (1<=n<=1000000) which denotes the number of digits in given number and next line contains n digits of given number separated by space.
      Output:
      Print the just next greater number if possible else print -1 in one line for each test case.
      Note : there will be no test case which contains zero in starting digits of any given number.
      Sample Test Cases :
      Input : 
      2
      5
      1 5 4 8 3
      10
      1 4 7 4 5 8 4 1 2 6
      Output :
      15834
      1474584162
      Time Limit : 2 sec


      DevG likes too much fun to do with numbers. Once his friend Arya came and gave him a challenge, he gave DevG an array of digits which is forming a number currently (will be called as given number). DevG was challanged to find the just next greater number which can be formed using digits of given number. Now DevG needs your help to find that just next greater number and win the challenge.


      Input: 


      The first line have t number of test cases (1<=t<=100). In next 2*t lines for each test case first there is number n (1<=n<=1000000) which denotes the number of digits in given number and next line contains n digits of given number separated by space.


      Output:


      Print the just next greater number if possible else print -1 in one line for each test case.


      Note : There will be no test case which contains zero in starting digits of any given number.


      Sample Test Cases :


      Input : 

      2

      5

      1 5 4 8 3

      10

      1 4 7 4 5 8 4 1 2 6


      Output :

      15834

      1474584162


       


      Added by:! include(L.ppt)
      Date:2012-08-31
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:MNNIT OPC 31-08-2012









      SPOJ Problem Set (classical)

      12151. Pizzamania

      Problem code: OPCPIZZA


      Singham and his friends are fond of pizza. But this time they short of money. So they decided to help each other.They all decided to bring pizza in pairs. Our task is to find the total number of pairs possible which can buy pizza, given the cost of pizza. As pizza boy dont have any cash for change, if the pair adds upto more money than required, than also they are unable to buy the pizza. Each friend is guaranteed to have distinct amount of money. As it is Singham's world, money can also be negative ;).
      Input:
      The first line consist of t(1<=t<=100) test cases.In the following 2*t lines, for each test case first there is n and m, where n(1<=n<=100000) is number of Singham's friend and m is the price of pizza.The next line consist of n integers, seperated by space, which is the money each friend have. 
      The value of m and money is within the limits of int in C,C++.
      Output: 
      A single integer representing the number of pairs which can eat pizza.
      Example
      Sample Input:
      2
      4 12
      9 -3 4 3
      5 -9
      -7 3 -2 8 7
      Sample Output:
      1
      1
      Time Limit: 3s


      Singham and his friends are fond of pizza. But this time they short of money. So they decided to help each other.They all decided to bring pizza in pairs. Our task is to find the total number of pairs possible which can buy pizza, given the cost of pizza. As pizza boy dont have any cash for change, if the pair adds upto more money than required, than also they are unable to buy the pizza. Each friend is guaranteed to have distinct amount of money. As it is Singham's world, money can also be negative ;).


      Input:

      The first line consist of t(1<=t<=100) test cases.In the following 2*t lines, for each test case first there is n and m, where n(1<=n<=100000) is number of Singham's friend and m is the price of pizza.The next line consist of n integers, seperated by space, which is the money each friend have. 


      The value of m and money is within the limits of int in C,C++.


      Output: 

      A single integer representing the number of pairs which can eat pizza.


      Example

      Sample Input:

      2

      4 12

      9 -3 4 3

      5 -9

      -7 3 -2 8 7


      Sample Output:

      1

      1


       


      Added by:! include(L.ppt)
      Date:2012-08-31
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:MNNIT OPC 31-08-2012









      SPOJ Problem Set (classical)

      12183. Help the Commander in Chief

      Problem code: KFSTB


      Help the Commander in Chief

      The Country of byteland is in a state of war with its neighboring nation bitland which is a small island. The king of byteland needs to send his soldiers across the sea to attack bitland. It is not easy for bytelandian soldiers to cross the sea between the two countries as there are soldiers of bitland who are constantly on patrol.

      But, The commander of byteland through his secret sources has gathered some information about the camping spots in between, It is as follows. There are C camping spots in the sea between the two countries. There are B one way bridges, each bridge is between two camps. Bytelandian army can use these bridges without any danger of being attacked. The commander also knows that if the army leaves a camping spot along a bridge safely it is not possible to return back safely to the same camping spot.

      The camping spot closest to the bytelandian shore is S and the camping spot closest to the bitlandian shore is T. The commander in chief of byteland wants to formulate a strategy for the army to safely move from the camping spot S to T. You have been assigned the task of finding the number of possible paths that a soldier could follow from camping spot S to T.

      Input

      The first line of input contains the number of test cases D. For each test case the first line contains C, B, S and T number of camping spots, number of one way bridges, camping spot close to byteland and camping spot close to bitland respectively. The next B lines contain description of bridges. Each bridge is described on a single line by two integers X and Y denoting the starting and ending point of a bridge.

      Output

      In each line print the number of possible paths modulo 1000000007

      Sample Input

      2
      4 4 1 4
      1 2
      1 3
      2 4
      3 4
      5 5 1 5
      1 2
      2 3
      2 4
      3 5
      4 5

      Sample Output

      2
      2

      Constraints

      1<= D <= 10
      1<= C <= 10000
      1<= B <= 10000
      1 <= X,Y <= C
      1 <= S,T <= C


      Added by:rizwan hudda
      Date:2012-09-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Kodefest 2012 IITK - Own problem









      SPOJ Problem Set (classical)

      12209. Morenas Candy Shop ( Easy )

      Problem code: MORENA

       

      Brunette's Candy Shop ( Easy )

      HARDER VERSION: http://www.spoj.pl/problems/HILO/

      Brunette's is a big candy shop from Little Campina in Paraibas/Brazil. This company is known for making the best candies in the world. Matheus Pheverso is the president of this company and he has a sister called Morena who loves and helps him in running the company. She uses to go the supermarket every day and buy a lot of stuffs to make all the candies. But she's insane and likes to take an alternate path to go to the supermarket.

      Given the streets heights, a path is alternate only if the differences between succesive numbers strictly alternate between positive and negative.

      Ex:

      - Street Heights: {1,3,4,5,2,9,8,10}

      - Alternate Paths: {1,3,2,9,8}, {1,4,2,8} {1,5,2,9,8}

      Matheus Pheverso is a friendly brother and he would like to know the longest alternate path between the first supermarket and the last supermarket, this means that his sister always starts at the supermarket number 1, and always ends at the last supermarket.

      Given the number of supermarkets, and their heights, your task is to print the longest alternate path between the first and the last city.

      Input

      There is a single positive integer N on the first line of input ( 1 <= N <= 10^6 ) representing the number of supermarkets. In the second line there're N integers Ai representing the heights of each supermarket ( -10^18 <= Ai <= 10^18 ).

      Ouput

      You have to print the longest alternate path between the first and the last supermarket. The supermarket number 1 is always the first, and the supermarket number N is always the last one.

      Example

      Input:

      5

      1 2 3 4 5

      Output

      2

      Input:

      8

      1 4 2 10 1 9 7 8

      Output

      8

       

       

       

       

       

       

       


      Added by:Mateus Dantas [ UFCG ]
      Date:2012-09-11
      Time limit:1s-2.400s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      12210. High and Low

      Problem code: HILO

      A student is always bored during his math classes. As the teacher won't let him sleep, he finds something else to do: try to find patterns in the numbers written on the board! Currently, he's spending his time trying to find Hi&Lo subsequences.

      Intuitively, a Hi&Lo sequence is any sequence that has consecutive differences with opposite signs, that is, if the first number is greater than the second, then the second is smaller than the third, the third is greater than the fourth, and so on.

      Formally, let x[1], x[2], ..., x[n] be the numbers written on the board. A Hi&Lo subsequence of length k that only uses elements from A to B is a sequence of indices a1, a2, ..., ak such that:

      1.  ak > ... > a2 > a1  A
      2. x[ai]- x[ai-1] != 0, for 1 < i <= k
      3. ( x[ai] - x[ai-1] )( x[ai+1] - x[ai] ) < 0, for 1 < i < k 

      Note that every sequence with only one element is a Hi&Lo sequence.

      However, as the amount of numbers increases, finding a big subsequence is getting harder and harder, so he asked you to create a program to help him and quickly find the largest Hi&Lo subsequence in a given interval. 

      Input

      The input contains several test cases. A test case begins with a line containing integers N (1 ≤ ≤ 100000)  and M (1  M  10000), separated by spaces. On the second line there are N positive integers, the initial state of the board. M lines follow, each with an instruction. Instructions can be of two kinds:

      1) q A B: Print the length of the longest high & low subsequence only using elements in positions from A to B, inclusive. You may assume that 1 ≤ A  B  N. 

      2) m A B: Modify the Ath element of the sequence to the positive integer B. You may assume that 1  A  N. 

      No number on the board will ever exceed 109. There is a blank line after each test case. The last test case is followed by a line containing two zeros.

      Output

      For each instruction of type 1, print a line containing an integer, the answer to the query. After each test, print a blank line. 

      Example

      Input:
      
      5 7
      5 7 1 2 3 4 5 q 2 4 m 3 1 q 2 4 m 3 2 q 2 4 m 4 2 q 2 4
      0 0
      Output:
      2
      3
      2
      1

      Added by:Fernando Fonseca [ITA]
      Date:2012-09-11
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Mateus Dantas









      SPOJ Problem Set (classical)

      12236. Cloud Computing

      Problem code: CLOUDMG

      The concept of cloud computing has become fairly popular lately. One of the main kinds of cloud computing is known as IaaS (Infrastructure as a Service), in which servers can be rented and managed via the Internet.

      Cloud, Inc. is an IaaS provider. The company is designing a new data center for its clients. Through some research, they found out that their clients, as a whole, need K servers, each of which needs to be able to withstand a certain level of demand. If we assume that the cost of a server always grows with the demand which that server can process, the best solution in terms of cost is to buy K servers explicitly designed to meet the exact requirements of the corresponding client.

      However, having K different hardware configurations in the data center is extremely problematic for the system administrators. To simplify, they demand that no more than L distinct server types be bought. A server that meets a demand c also meets any demand smaller than c.

      A possible solution is to buy only one server type that is able to meet the highest client demand, as it will also be able to meet all other demands. On the other hand, the cost of such a solution can be prohibitively high. Considering that you can buy up to L different kinds of servers, there's likely a better option. For instance, suppose that there are 3 clients, with demands 3, 7 and 16. Assume that the cost of a server meeting demands up to 3 is of R$ 1500 (1500 brazilian reais), the cost of a server that meets demand 7 is R$ 5500 and the cost of a server that meets demand 16 is R$ 19200. If you want to buy at most 2 kinds of servers to satisfy all clients, you have four possibilities:

      • Buying three servers with capacity 16, at a total cost of R$ 57600;
      • Buying two servers with capacity 16 and one with capacity 7, at a total cost of R$ 43900;
      • Buying two servers with capacity 16 and one with capacity 3, at a total cost of R$ 39900;
      • Buying one server with capacity 16 and two servers with capacity 7, at a total cost of R$ 30200.

      Among these options, the one with the least total cost is the last one.

      You will receive a list of K requested demands and the price of a server type that meets the corresponding demand. Determine the lowest total cost to buy K servers in a way such that all requested demands are met and at most L different types of servers are bought.

      Notes

       

    • Each server is used by one and only one client. A server with capacity 4 may not be used by two clients with demand 2 each.
    • Let Di and Dj be two demands, and Pi, Pj prices associated to the servers that meet those demands. If Di < Dj, then Pi ≤ Pj.
    •  

      Input

      There are several test cases.

      Each test case begins with a line containing integers K and L, respectively the number of servers to be bought and the maximum allowed number of distinct server types (1 ≤ L ≤ K ≤ 2000). K lines follow, each of which containing two integers D and P, respectively the demand of a client and the smallest price of a server which meets that demand (1 ≤ D ≤ 2000, 1 ≤ P ≤ 100000). If the same value of D is present on more than one line, then both lines will have the same value for P.

      The input ends when K = L = 0, and this case should not be processed.

      Output

      For each test case, print a line with an integer T, which is the lowest total cost obtainable.

      Example

      Input:
      10 3
      1 1
      2 4
      3 5
      4 7
      5 8
      6 12
      7 13
      8 18
      9 19
      10 21
      0 0
      
      Output:
      129
      

      The best option to buy servers of 3 kinds that meet the required demands is to buy:

      • 3 servers of capacity 10, which account for client demands 10, 9 and 8;
      • 2 servers of capacity 7, which account for client demands 7 and 6;
      • 5 servers of capacity 5, which account for all other demands.

      Total cost is 3*21 + 2*13 + 5*8 = 129.

       


      Added by:Fernando Fonseca [ITA]
      Date:2012-09-16
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Minas Gerais State Programming Competition 2012 (unofficial test data)









      SPOJ Problem Set (fifth)

      12240. Multinomial numbers

      Problem code: HS12MULT

      You may perhaps know how to find the last nonzero digit of n factorial. This time your task is harder, find the last nonzero decimal digit of the multinomial coefficient:
      (a1+a2+ … +an)!/(a1!*a2!* … *an!) . Note that this is an extension of the classical problem, since factorials (and binomial numbers) are also multinomial numbers!

      Input

      An integer T, denoting the number of testcases (T≤10000). In each line you are given one positive integer ( n≤20 ), followed by n integers: a1,a2,…,an, where 0 ≤ ai ≤ 1000000000. There are 4 input sets for 10 points.

      Output

      Output T lines, the case number followed by the last nonzero decimal digit. See the sample output for the correct format!

      Example

      Input:
      7
      1 0
      2 11 9
      4 5 7 2 9
      3 1000 3000 2000
      3 100000000 200000000 300000000
      2 4 9
      8 1 1 4 7 4 8 9 2
      
      Output:
      Case 1: 1
      Case 2: 6
      Case 3: 8
      Case 4: 6
      Case 5: 2
      Case 6: 5
      Case 7: 4
      

      Warning: A naive algorithm will probably solve only the first two input sets (4 pts).


      Added by:Robert Gerbicz
      Date:2012-09-18
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: CLOJ ICK NODEJS PERL 6 PYTH 3.2.3 n
      Resource:High School Programming League 2012/13









      SPOJ Problem Set (classical)

      12241. Classification from Erdõs and Selfridge

      Problem code: HS12PRIM


      Erdõs Pál and John Selfridge classified prime numbers in this way: for a prime p, if the largest prime factor of p-1 is 2 or 3, then p is in class one. Otherwise, p is in class c+1 where c is the largest of the classes of the prime factors of p-1. We put p=2 in class one. For example, p=89 is in class three, because p-1=2^3*11 and here 2 is in class one, but 11 is in class two (because 11-1=2*5 and here 2 and 5 are in class one). Your task is to count the number of primes in each class up to class thirteen for a given (closed) interval.

      Input

      The first line contains the number of test cases T, where T≤1000. Each of the following T lines contains two integers a,b where 0≤a≤b≤50000000. There are 4 input sets for 10 points.

      Output

      Output the case number, followed by the distribution of the primes in each class up to class 13 in the (closed) interval [a,b]. See the sample input/output for the correct format!

      Example

      Input:
      3
      2 100
      23 23
      0 50000000
      
      Output:
      Case 1:
      There are 10 primes in class 1.
      There are 9 primes in class 2.
      There are 5 primes in class 3.
      There are 1 primes in class 4.
      There are 0 primes in class 5.
      There are 0 primes in class 6.
      There are 0 primes in class 7.
      There are 0 primes in class 8.
      There are 0 primes in class 9.
      There are 0 primes in class 10.
      There are 0 primes in class 11.
      There are 0 primes in class 12.
      There are 0 primes in class 13.
      
      Case 2:
      There are 0 primes in class 1.
      There are 0 primes in class 2.
      There are 1 primes in class 3.
      There are 0 primes in class 4.
      There are 0 primes in class 5.
      There are 0 primes in class 6.
      There are 0 primes in class 7.
      There are 0 primes in class 8.
      There are 0 primes in class 9.
      There are 0 primes in class 10.
      There are 0 primes in class 11.
      There are 0 primes in class 12.
      There are 0 primes in class 13.
      
      Case 3:
      There are 54 primes in class 1.
      There are 14196 primes in class 2.
      There are 364182 primes in class 3.
      There are 1029984 primes in class 4.
      There are 939493 primes in class 5.
      There are 458831 primes in class 6.
      There are 150902 primes in class 7.
      There are 34878 primes in class 8.
      There are 7085 primes in class 9.
      There are 1310 primes in class 10.
      There are 203 primes in class 11.
      There are 15 primes in class 12.
      There are 1 primes in class 13.
      

      Warning: A naive algorithm will probably solve only the first input set.


      Added by:Robert Gerbicz
      Date:2012-09-18
      Time limit:1s-30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:High School Programming League 2012/13









      SPOJ Problem Set (classical)

      12243. Natalia Spins The Roulette

      Problem code: ROULETTD


      A La Vega Roulette is like a normal Roulette. It is a circular shape with numbers written down on the edge so that they fill up the whole circumference line. It differs from the well-known Roulette in two aspects. First, all numbers have the same color. Second, there is a marker right at the top of the center of the Roulette.

       

      Natalia and Luis are bored and decided to play "Battle of the Spins" with a La Vega Roulette. On her first turn, a player rotates the La Vega Roulette such that the first number is below the marker. Then, she spins the Roulette and writes down the number that landed on the marker. She also records the position of the Roulette. In subsequent turns, the player must first rotate the Roulette back to the position where it ended in her previous turn, spin, sum the new marked number to her current sum and record again the position.

      After both players take a turn then a decision must be made to whether continue playing or announce verdict. Let's say the sum of Player 1 and Player 2 are S1 and S2, respectively. If S1 - S2 > K, Player 1 wins and the game is over. If S2 - S1 > K, then Player 2 wins. However, if S1 - S2 = 0, the game is a draw and ends immediately. If none of the previous conditions apply, the game continues.

      You are given the amount of numbers by which the La Vega Roulette spinned after each player's turn. Please output the result of the battle.

      Input

      The first input line contains two space-separated integers N (2 ≤ N ≤ 103), the size of the list of numbers along the La Vega Roulette's circumference and K (100 ≤ K ≤105), the threshold. Then there's a second line with N space-separated 32-bit integers. Each of these integers represent the ith number written down on the circumference.  Then there are many lines. Each of these lines contain two space-separated integers Spin1 and Spin2 (1 ≤ Spin1, Spin2 ≤ 105). Each represent the amount of numbers by which the La Vega Roulette rotated in Player 1's and Player 2's turns, respectively. It is guaranteed that there are sufficient lines to reach a verdict.

      Output

      Please output the answer to this problem. If Player 1 wins, write "P1". If Player 2 wins, write "P2". If there's a draw, write "BAD LUCK".

      Example

      Input:
      6 120
      6 5 1 80 10 50
      3 2
      2 5
      
      Output:
      P1
      Note: In this test case, both players start at the first position. After the first round, Player 1 writes down 80 and Player 2
      writes down 1. Because S1 - S2 and S2 - S1 are not zero and neither greater than K = 120, the game takes another round. 
      After the second round, Player 1 writes down 50 and Player 2 writes down 5. Now S1 = 80 + 50 = 130 and S2 = 1 + 5 = 6.
      Because S1 - S2 = 124 > 120, Player 1 wins and the game is over.

      Added by:kojak_
      Date:2012-09-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Roberto Abreu's Repository









      SPOJ Problem Set (classical)

      12244. Natalia Has Another Problem

      Problem code: NATALIAS

      Natalia has another problem she needs your help with. Do you still have some energies left?

      A Logical String is a string that represents a valid boolean expression. It is composed of operators AND, OR and NOT and truth values operands. The boolean expressions are recursive in the sense that operators can have other operators as operands. For example, the following is a list of valid Logical Strings:

      T
                    T
      F
        F
      AND(T, T)
      OR(T, F)
      NOT(T)
      AND(OR(T, F), AND(F, F))
      AND(AND(AND(OR(T, F), F), F), T)
      AND ( AND ( OR ( T,F),OR(F,F)),T)

       

      Please note that there can be several spaces in between objects. However, no space will be in between letters of the names. Therefore, "AND(T,T)" is a valid Logical String but "A     N       D(T,T)" is not.

      Given a Logical String, please evaluate it and output its truth value.

      Input

      The first line contains T(1≤ T ≤ 100), the number of test cases. Then there are T lines. Each line contains a string s0s1s2...sn-1(1 ≤ N ≤ 100). It is guaranteed that the ith Logical String is valid.

      Output

      For each Logical String given, output its truth value. If it is true, output T, otherwise output F.

      Example

      Input:
      

      7
      T
      F
      AND(T, T)
      OR(T, F)
      NOT(T)
      AND(OR(T, F), AND(F, F))
      AND(AND(AND(OR(T, F), F), F), T)

      Output:
      

      T
      F
      T
      T
      F
      F
      F


      Added by:kojak_
      Date:2012-09-18
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Roberto Abreu's Repository









      SPOJ Problem Set (classical)

      12245. Natalia Plays a Game

      Problem code: NATALIAG

      When Natalia is not having fun studying Computing Science in Santiago de los Caballeros, she opens up her bag and pulls out an iPad she won at a Programming Olympiad to play a classical maze game.

      The maze is a rectangular figure of M rows and N columns. Open areas are represented by a 'O' while closed areas are represented by a '*'. An area is just a 1x1 block inside the maze. There's an entrance area marked by a '$' and a destination area marked by a '#'. Please note that both the entrance and destination are also open areas. 

      Once Natalia is located inside an open area, she can decide to move to either cardinal direction (north, south, east or west). In other words, if Natalia is located at (x,y), she can move to either (x + 1, y), (x - 1, y),  (x, y + 1) or (x, y - 1). Of course, she can't move inside a closed area.

      Given a rectangular maze as described above, output the minimum number of steps necessary to reach the final position from the starting area, if it is possible. If not, output '-1'.

      Input

      The input contains many lines. The first line contains an integer T (1 ≤ T ≤ 100), the number of test cases. For each test case there's a first line that contains two space separated integers M and N (1 ≤ M ≤ 100), (2 ≤ N ≤ 100), the dimensions of the maze. The line is followed by M lines. Each of these lines contain a string of N characters. The position at index j of the ith string represents the marker of the i,j area. It can be either an open marker ('O'), a closed marker ('*'), the unique entrance marker ('$') or the unique destination marker ('#'). 

      Output

      For each test case output the minimum number of steps necessary to reach the final position from the entrance position. If it is impossible to reach the final position, output -1.

      Example

      Input:
      
      2
      $OO
      2 3 3 $OO *** OO# 3 3 $*# O*O OOO
      ***
      O#
      3 3
      $*#
      O*O
      OOO2 3 3 $OO *** OO# 3 3 $*# O*O
      Output:
      

      -1
      6


      Added by:kojak_
      Date:2012-09-18
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Roberto Abreu's Repository









      SPOJ Problem Set (classical)

      12249. Spiderman vs Sandman

      Problem code: SPIDY

       

      There is a faceoff between Spiderman & Sandman. 

      There are two glass buildings each of height H. Each building has H equal sized windows on the outside covering entire space from bottom to top. Some windows are open and spiderman cannot land on these window.

      In one step, Spiderman can:

      1) Rise up to just above window of the same building he is on.

      2) Slide down to just below window of the same building he is on.

      3) Use his web to jump to Kth window above from current height on the other building.

       

      Sandman on the other rises steadily a rate of 1 per step.

      For the purpose of this problem, assume Spiderman and Sandman take turns ie: Spiderman takes one step, then Sandman takes one step.

      Your goal is to assist Spiderman to always remain above or at same height as Sandman at the end of Sandman's turn. Spiderman gets the first turn and both start at height 0 (ie: Sandman is on the ground and Spiderman is on the window of lowermost floor of left building. It is guarenteed that window of lowermost floor of left building is not open.

      Note : If Spiderman gets to area with height >= H assume he has got out.

       

      You are Spiderman's best friend, your duty is to guide Spiderman to escape from Sandman if possible in shortest number of steps to get out.

       

      Input

      First line contains integer T. 

      T Testcases follow. Each testcase contains 3 lines. 

      First line of input contains two space seperated integers H & K

      Next two lines contain description of two buildings.

      2nd line represents the left building - a string of length H. The ith character represents the state of window between (i-1) and i heights : character '-' represents closed window(safe to land on) , character 'X' represents open window. 

      Similarly 3rd line represents the right building.

       

      Output

      For every testcase output single integer x where x is the number of steps taken to get out of building. Output "NO" if Spiderman cannot escape the area and has to fight in the enclosure.

       

      Constraints

      1<=T<=10

      1 <= H,K <= 10^5

       

      Example

      Input: 

      2

      7 3

      ---X--X

      -X--XX-

      6 2

      --X-X-

      X--XX-

       

      Output: 

      4

      NO

       

      EXPLANATION

      In first case Spiderman jumps to right building, goes one height down, jumps to left building and jumps to right buidling (he got to the top).

      In second case, no matter how he moves, Spiderman cannot escape above the buildings.

       


      Added by:Anil Shanbhag
      Date:2012-09-20
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:codeforces









      SPOJ Problem Set (classical)

      12250. Buzz Trouble

      Problem code: BUZZOFF


       

      BUZZ OFF
      Commander Nebula decided to take interns into Star Command to join the Little Green Men (LGMs). And the job of physical training of these LGMs went to Buzz Lightyear. Assume N interns are taken, each with a distinct LGM ID.
      Being buzy with XR, Buzz sent Mira Nova to select a few of the interns and line them in the training center. XR noticed that he neither told Mira how many LGMs to select, nor in which order to arrange them; so Mira can select any number M of students (1<=M<=N) and line them up randomly (Assume that if Mira is to select M LGMs, then she selects the M smallest LGM IDs, eg, if N=5 and IDs be 12,3,4,11,2 and she decided to select 3 LGMs, then she picks up 3,4 and 2).
      XR wonders, how many different arrangements might Buzz find on arriving in the training centre for which no LGM is more than unit distance away from its correct position, and Buzz has to do less work in ordering them correctly (in increasing order of LGM ID).
      As result might be large, output result modulo 10^9+7 (1000000007)
      INPUT:
      first line contains T, number of test cases
      Next T lines contain single number N, indicating number of LGM interns.
      OUTPUT:
      T lines, each with the answer for corresponding case.
      CONSTRAINTS:
      1<=T<=10^5
      1<=N<=10^18
      EXAMPLE:
      Input:
      5
      1
      2
      5
      8
      10
      Output:
      1
      3
      19
      87
      231
      Explaination:
      for N=1, only case is to pick the only LGM
      for N=2, and LGM IDs are say 1 and 2, then Buzz might find [1], [1,2], or [2,1] Therefore 3

       

       

      BUZZ OFF

      Commander Nebula decided to take interns into Star Command to join the Little Green Men (LGMs). And the job of physical training of these LGMs went to Buzz Lightyear. Assume N interns are taken, each with a distinct LGM ID.

      Being busy with XR, Buzz sent Mira Nova to select a few of the interns and line them in the training center. XR noticed that he neither told Mira how many LGMs to select, nor in which order to arrange them; so Mira can select any number M of students (1<=M<=N) and line them up randomly (Assume that if Mira is to select M LGMs, then she selects the M smallest LGM IDs, eg, if N=5 and IDs be 12,3,4,11,2 and she decided to select 3 LGMs, then she picks up 3,4 and 2).

      XR wonders, how many different arrangements might Buzz find on arriving in the training centre for which no LGM is more than unit distance away from its correct position, and Buzz has to do less work in ordering them correctly (in increasing order of LGM ID).

      As result might be large, output result modulo 10^9+7 (1000000007)

       

      INPUT:

      first line contains T, number of test cases

      Next T lines contain single number N, indicating number of LGM interns.

       

      OUTPUT:

      T lines, each with the answer for corresponding case.

       

      CONSTRAINTS:

      1<=T<=10^4

      1<=N<=10^18

       

      EXAMPLE:

      Input:

      5

      1

      2

      5

      8

      10

       

      Output:

      1

      3

      19

      87

      231

       

      Explaination:

      for N=1, only case is to pick the only LGM

      for N=2, and LGM IDs are say 1 and 2, then Buzz might find [1], [1,2], or [2,1] Therefore 3

       


      Added by:Piyush Kumar
      Date:2012-09-20
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      12251. Mad Hulk

      Problem code: MADHULK


       

      Evil Doctor D has captured Hulk and put him into an underground tunnel system. The tunnel system is closed but sadly Hulk is not aware of this fact. 
      Tunnel structure is of the form of a asterix. There are many tunnels coming out of single center point. Hulk is left unconscious at the outer end of tunnel. Once Hulk gets up he just wants to get out of this underground system. Since its completely dark down there, Hulk adopts the following strategy : He runs to get to the center and once he gets there he randomly enters another tunnel other than the one he came from. He will run to outer end of this tunnel, come back to center and again choose a random tunnel other than presently exited one ( may as well be the first chosen one). 
      You have to find out the the expected length of Hulk's path in which he would have visited the ends of all tunnels atleast once.
      Input : 
      First line contains integer n giving number of testcases. 
      n testcases follow. 
      For each testcase contains k followed k space seperated integers representing the lengths of the k tunnels.
      Output:
      One line per testcase containing one integer E which is the expected length of Hulk's path
      Constraints:
      2 <= k <= 50
      Each integer a[i] : 1 <= a[i] <= 10^5
      Example :
      Input:
      2
      2 40 40
      3 50 50 50
      Output:
      80.0
      300.0
      In testcase 1 there are two tunnels of length 40 each meeting at the center. Hulk runs from end of first to center. He will take the second on to reach the end of second. Hence 40 + 40 = 80.
      In testcase 2 there are three tunnels of length 50 each meeting at the center. Hulk would run from end of 0th tunnel to center (Total: 50). Run to end of one of the other two tunnels and back to center (Total: 50 + 50*2).  Now to cover last tunnel remaining, he either choose the third tunnel immediately with probablity 1/2 or chooses the first, goes to end, comes back to center and chooses third with probablity 1/2 * 1/2 and so on. Total expected path length = 150 + 50 * 1/2 + 150 * 1/2 * 1/2 + 250 * (1/2)^3 ..... = 300.0

       

      Evil Doctor D has captured Hulk and put him into an underground tunnel system. The tunnel system is closed but sadly Hulk is not aware of this fact. 

       

      Tunnel structure is of the form of a asterix. There are many tunnels coming out of single center point. Hulk is left unconscious at the outer end of tunnel. Once Hulk gets up he just wants to get out of this underground system. Since its completely dark down there, Hulk adopts the following strategy : He runs to get to the center and once he gets there he randomly enters another tunnel other than the one he came from. He will run to outer end of this tunnel, come back to center and again choose a random tunnel other than presently exited one ( may as well be the first chosen one). 

      Note: The statring point of Hulk is at the end of the tunnel whose length is mentioned first in the array

      You have to find out the the expected length of Hulk's path in which he would have visited the ends of all tunnels atleast once.

       

      Input : 

      First line contains integer n giving number of testcases. 

      n testcases follow. 

      For each testcase contains k followed k space seperated integers representing the lengths of the k tunnels.

       

      Output:

      One line per testcase containing one number E which is the expected length of Hulk's path

       

      Constraints:

      2 <= k <= 50

      Each integer a[i] : 1 <= a[i] <= 10^5

       

      Example :

       

      Input:

      2

      2 40 40

      3 50 50 50

       

      Output:

      80.0

      300.0

       

      In testcase 1 there are two tunnels of length 40 each meeting at the center. Hulk runs from end of first to center. He will take the second on to reach the end of second. Hence 40 + 40 = 80.

      In testcase 2 there are three tunnels of length 50 each meeting at the center. Hulk would run from end of 0th tunnel to center (Total: 50). Run to end of one of the other two tunnels and back to center (Total: 50 + 50*2).  Now to cover last tunnel remaining, he either choose the third tunnel immediately with probablity 1/2 or chooses the first, goes to end, comes back to center and chooses third with probablity 1/2 * 1/2 and so on. Total expected path length = 150 + 50 * 1/2 + 150 * 1/2 * 1/2 + 250 * (1/2)^3 ..... = 300.0

       

       


      Added by:Piyush Kumar
      Date:2012-09-20
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:topcoder









      SPOJ Problem Set (classical)

      12260. Devlali Numbers

      Problem code: HARSHAD

      Harshad numbers were an important coinage by Indian recreational mathemtician D. R. Kaprekar.
      For any positive integer n, define d(n) as the sum of n and the digits of n. Eg, d(199)=199+1+9+9=218.
      For a positive number m, if there exists no positive number r such that r+d(r)=m, then m is a Harshad number. First few Harshad numbers are 1,3,5,7.. so on.
      A prime number falling in this family is called a Harshad Prime. First few Harshad Primes are 3,5,7,.. so on.
      INPUT
      first line contains integer Q
      Next Q lines contain two integers A and B
      OUTPUT
      print Q lines, each listing number of Harshad Primes in range [A,B] (both inclusive)
      EXAMPLE
      Input
      3
      1 3
      0 10
      5 8
      Output
      1
      3
      2

       

      Devlali numbers were an important coinage by Indian recreational mathemtician D. R. Kaprekar.

       

      For any positive integer n, define d(n) as the sum of n and the digits of n. Eg, d(199)=199+1+9+9=218.

      For a positive number m, if there exists no positive number r such that d(r)=m, then m is a Devlali number. First few Devlali numbers are 1,3,5,7.. so on.

       

      A prime number falling in this family is called a Devlali Prime. First few Devlali Primes are 3,5,7,.. so on.

       

      INPUT

      first line contains integer Q

      Next Q lines contain two integers A and B

       

      OUTPUT

      print Q lines, each listing number of Devlali Primes in range [A,B] (both inclusive)

       

      LIMITS

      1<=Q<=100000

      0<=A<=B<=1000000

       

      EXAMPLE

      Input

      3

      1 3

      0 10

      5 8

      Output

      1

      3

      2

       


      Added by:Piyush Kumar
      Date:2012-09-21
      Time limit:4s-10s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      12262. Mirror Strings !!!

      Problem code: MSUBSTR

       

      Mirror Strings
      As we all know Utkarsh is very good at solving number based problems, this time Arpit thinks smartly and gives Utkarsh to solve a problem on Strings. Arpit gives Utkarsh a string and challenges him to find the length of largest substring that have its mirror string same as its original one and number of such substrings. Now Utkarsh is buzy at preparing Avishkar papers so he asks you to help him in doing this task.
      Eg.Consider string "lalit" then its mirror string will be "tilal".
      Input :
      There are t numbers of test cases (t<=100) followed t lines where each line contains a character string of lower case characters (a-z) of length l (1>=l<=3000).
      Output :
      There will be two integers per line separated by space indicating the length of largest substring which have its mirror string same and number of such substrings.
      Sample test cases :
      Input :
      3
      lalit
      abedcdetr
      abcde
      Output :
      3 1
      5 1
      1 5
      Time Limit : 1 sec

           As we all know Utkarsh is very good at solving number based problems, this time Arpit thinks smartly and gives Utkarsh to solve a problem on Strings. Arpit gives Utkarsh a string and challenges him to find the length of largest substring that have its mirror string same as its original one and number of such substrings. Now Utkarsh is buzy at preparing Avishkar papers so he asks you to help him in doing this task.

      Eg. for mirror string : Consider string "lalit" then its mirror string will be "tilal".

       

      Input :

      There are t numbers of test cases (t<=200) followed t lines where each line contains a character string of lower case characters (a-z) of length l (1>=l<=3000).

       

      Output :

      There will be two integers per line separated by space indicating the length of largest substring which have its mirror string same and number of such substrings.

       

      Sample test cases :

      Input :

      3

      lalit

      abedcdetr

      abcde

       

      Output :

      3 1

      5 1

      1 5

       

       

       

       


      Added by:! include(L.ppt)
      Date:2012-09-21
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:MNNIT OPC 21-09-2012









      SPOJ Problem Set (classical)

      12277. The Trip

      Problem code: OPCTRIP


      Akshat aka Singham, watches a lot of TV Series. Today he finished Castle, he is bored now and is planning for a trip with friends.He has N friends. As you all know singham is very cautious and wants to save every penny he can. He has identified few reigons that they will visit. He will start from MNNIT and visit all the reigons one by one in buses.
      Assume that all reigons are connect by a single road running through these reigons. Each reigon has a tempreture ti units, if a bus is travelling through ith reigon and has k people in it then the tempreture of the bus ti+k units.
      If the tempreture of the bus exceeds Ti units, then each of the member on the bus ask for refreshment in the form of ice -cream, drinks due to uncomfortable cnditions. As the cost of products varies from reigon to reigon, the refreshment cost on avg. per member on bus in reigon i is Rs. xi. 
      As Akshat wants to save money, he thinks of adding/removing buses in the begining of the trip and between reigons (they need at least one bus to pass any reigon). Assume that buses have infinite capacity and Friends can be randomly distributed on buses. Each of the bus in reigon i cost Rs. Ci.
      You have to help akshat find the minimum cost needed to organize the trip.
      Input
      First Line contains one integer tc, representing the number of test cases, then tc test cases follow.
      Each test cases starts with two integer on first line n and m (1<=n<=10^5; 1<=m<=10^6) -- the number of reigons in the trip and number of friends.
      Next n lines contains four integers : the ith line contains ti (temp. of reigon), Ti(max. tolerable temp.), xi(Avg. refreshment cost), Ci (cost per bus).(1<=ti,Ti,xi,Ci<=10^6).
      Output
      Print one integer, minimum cost nedded to organize to trip. (Warning : Output may not be in the range of integer)
      Sample Test Case: 
      Input
      2
      2 10
      30 35 1 100
      20 35 10 10
      3 100
      10 30 1000 1
      5 10 1000 3
      10 40 1000 100000
      Output
      120
      200065

      Akshat aka Singham, watches a lot of TV Series. Today he finished Castle, he is bored now and is planning for a trip with friends.He has N friends. As you all know singham is very cautious and wants to save every penny he can. He has identified few reigons that they will visit. He will start from MNNIT and visit all the reigons one by one in buses. 

      Assume that all reigons are connect by a single road running through these reigons. Each reigon has a tempreture ti units, if a bus is travelling through ith reigon and has k people in it then the tempreture of the bus ti+k units.

      If the tempreture of the bus exceeds Ti units, then each of the member on the bus ask for refreshment in the form of ice -cream, drinks due to uncomfortable cnditions. As the cost of products varies from reigon to reigon, the refreshment cost on avg. per member on bus in reigon i is Rs. xi. 

      As Akshat wants to save money, he thinks of adding/removing buses in the begining of the trip and between reigons (they need at least one bus to pass any reigon). Assume that buses have infinite capacity and Friends can be randomly distributed on buses. Each of the bus in reigon i cost Rs. Ci.

      You have to help akshat find the minimum cost needed to organize the trip.

       

      Input

      First Line contains one integer tc, representing the number of test cases, then tc test cases follow.

      Each test cases starts with two integer on first line n and m (1<=n<=10^5; 1<=m<=10^6) -- the number of reigons in the trip and number of friends.

      Next n lines contains four integers : the ith line contains ti (temp. of reigon), Ti(max. tolerable temp.), xi(Avg. refreshment cost), Ci (cost per bus).(1<=ti,Ti,xi,Ci<=10^6).

       

      Output

      Print one integer, minimum cost nedded to organize to trip. (Warning : Output may not be in the range of integer)

       

      Sample Test Case: 

      Input

      2

      2 10

      30 35 1 100

      20 35 10 10

      3 100

      10 30 1000 1

      5 10 1000 3

      10 40 1000 100000

       

      Output

      120

      200065

       

       


      Added by:! include(L.ppt)
      Date:2012-09-23
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:MNNIT OPC 21-09-2012









      SPOJ Problem Set (classical)

      12295. Smallest Inverse Euler Totient Function

      Problem code: INVPHI


      This task is the inverse of ETF problem, given an integer n find smallest integer i such that φ(i)=n, where φ denotes Euler's totient function.

      Input

      The first line is an integer T(1 ≤ T ≤ 100,000), denoting the number of test cases. Then, T test cases follow.

      For each test case, there is an integer n(1 ≤ n ≤ 100,000,000) written in one line. (one ineger per line)

      Output

      For each test case, output Smallest Inverse Euler's Totient Function of n. if n doesn't have inverse, output -1.

      Example

      Input:
      5
      10
      20
      30
      40
      50
      
      Output:
      11
      25
      31
      41
      -1

       

      Time Limit ≈ 3*(My Program Top Speed)

       

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2012-09-28
      Time limit:20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12304. Smallest Inverse Sum of Divisors

      Problem code: INVDIV

      First, we define σ(i) = Sum of all positive divisors of i.

      example: all positive divisors of 60 = {1,2,3,4,5,6,10,12,15,20,30,60}

      so σ(60)=1+2+3+4+5+6+10+12+15+20+30+60=168

      Now for the task: given an integer n find smallest integer i such that σ(i)=n.

      Input

      The first line is an integer T(1 ≤ T ≤ 100,000), denoting the number of test cases. Then, T test cases follow.

      For each test case, there is an integer n(1 ≤ n ≤ 100,000,000) written in one line. (one ineger per line)

      Output

      For each test case, output Smallest Inverse Sum of Divisors of n. if n doesn't have inverse, output -1.

      Example

      Input:
      5
      1
      16
      40
      60
      168
      Output:
      1
      -1
      27
      24
      60

       

      Time Limit ≈ 2.5*(My Program Top Speed)

       

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2012-09-29
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12318. My Reaction when there is no internet connection

      Problem code: NITT1


      There is college whose name will not be disclosed. To raise the level the college management installed wifi connections. There was poor hostel where there was a poor floor. The floor had n rooms. Three routers were setup just for that floor to increase the signal strength. Still there they weren't able to operate the internet. Also no router can hold more than the current connections from that wing. They finally found that if three adjacent room connects to a same router then there won't be an internet connection established. You know which room is connected to which router. Since they are very lazy (as it is the typical character of their college) they want to swap the router connection between certain room so that the number of unswapped rooms are maximum and also no three continuous rooms are connected to the same wifii router.

      Input

       

      First line T denoting the number of cases
      For each line a string x is given which determines which denotes which room is connected to which router

       

      First line T denoting the number of cases (T<=40)

      For each line a string x is given which determines which denotes which room is connected to which router (size of x<=50)

       

       

      Output

      Output the maximum unswapped rooms which follows the above mentioned condition or output -1 if it is not possible to make a valid arrangement

      Example

      Input:
      2
      111222333
      11111111322
      
      Output:
      6
      7

      Added by:jack(chakradarraju)
      Date:2012-09-29
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      12319. hai jolly jolly jolly

      Problem code: NITT2

      Alp and gaut are like always opposite to each other. Once alp told that he can identify a number which is divisble by 252 (He knows because that is his girlfriends birthday - 25/2). Now to come up against alp, gaut said he can identify whether the number is divisble by 525 (poor gaut don't have a girl friend though). The truth is they don't know to do it for big numbers.  So you are here to help them with a method. Given a number you have to tell whether the number is divisble by 252 and 525

      Input

      Number of testcases in first line, T. T <= 100.

      Each line contains one number N, whose divisibility is to be tested. 1 <= N <= 10^50000

      Output

      each line containing two Yes/No. one for 252 and one for 525.

      Example

      Input:
      4
      252
      525
      1179630648
      1234623983
      16884
      21347
      
      Output:
      Yes No
      No Yes
      Yes No
      No No

      Added by:jack(chakradarraju)
      Date:2012-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      12321. NSquare Sum ( Easy )

      Problem code: NSQUARE

      Given two integers N ( N <= 10^18 ) and a prime number P ( 1 < P < 10^18 ), find the lowest number x such that there're not N integers greater or equal to 0 whose sum of squares is equal to x.

       

       

      N = 2, P = 2

      x = 3mod2 = 1

       

      0 = 0² + 0²

      1 = 1² + 0²

      2 = 1² + 1²

      4 = 2² + 0²

      Input

      There're two integers N ( 1 <= N <= 10^18 ) and a prime number P ( 1 < P < 10^18 ). You have to print the answer modulo P.

      Output

      You have to print an integer x mod P ( -1 < x < 10^18 + 1 ) that satisfies the problem. If there's no number x, print "Impossible".

      Example

       

       

      Input:

      1 3

      Output:

      2

       

      Input:

      13 7

      Output:

      Impossible

       


      Added by:Mateus Dantas [ UFCG ]
      Date:2012-09-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: NODEJS PYTH 3.2.3 n
      Resource:Rafael Perrela









      SPOJ Problem Set (classical)

      12322. NSquare Sum ( Medium )

      Problem code: NSQUARE2

      N-square Sum! Problem? ( Medium ) 

      Given Q pairs of integers Ni, Ai ( 1 <= Ai, Q <= 10^5 , 4 <= N <= 10^2 ) a, find Ni numbers whose square sums is equal to Ai. If there're more than one solution, print the one lexicographically smallest . If there's no solution, print "Impossible".



      Q = 1

      Ni = 4

      A1 = 16


      { 4² + 0² + 0² + 0² = 16}


      Input

       There's an integer Q ( 1 <= Q <= 10^5 ) in the first line; it stands for the number of queries. The next Q lines describe each query with two integers Ni, Ai ( 1 <= Ai <= 10^5, 4 <= Ni <= 10^2 ). Ni is the number of integers that you need to find whose sum of squares is equal to Ai.

       Output

       You have to print Q lines, each one with Ni numbers such that the sum of squares is equal to Ai. If there's no solution, you've to print "Impossible".

       Example



      Input:

      1

      4 16

      Output:

      0 0 0 4


      Input:

      1

      4 15

      Output:

      1 1 2 3



      Added by:Mateus Dantas [ UFCG ]
      Date:2012-09-30
      Time limit:0.600s-1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Manoel Lucas









      SPOJ Problem Set (classical)

      12323. Minimum Knight moves !!!

      Problem code: NAKANJ

       

      Anjali and Nakul are good friends. They both had a quarrel recently while playing chess. Nakul wants to know the minimum number of moves a knight takes to reach from one square to another square of a chess board (8X8). Nakul is brilliant and he had already written a program to solve the problem. Nakul wants to know whether Anjali can do it. Anjali is very weak in programming. Help her to solve the problem.

       

      A knight can move in the shape of an "L" in a chessboard - two squares either forward, backward, left, or right and then one square to its left or right. A knight move is valid if it moves as mentioned above and it is within the boundary of the chessboard (8 X 8).

       

      http://0.tqn.com/d/chess/1/0/6/-/-/-/KnightMoves.gif

       

      Input

       

      There are T test cases in total. The next T lines contain two strings (start and destination) separated by a space.

      The strings start and destination will only contain two characters - First character is an alphabet between 'a' and 'h' (inclusive), Second character is a digit between '1' and '8' (inclusive) - (Quotes just for clarity).

       

      To know the knight moves more clearly refer to the above figure.

      Output

       

      Print the minimum number of moves a knight takes to reach from start to destination in a separate line.


      Constarints

      1<=T<=4096

       

      Example

      Input:
      
      3
      a1 h8
      a1 c2
      h8 c3

      Output:

      6
      1
      4

      Added by:Nakul Krishna
      Date:2012-09-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Used for Code it - Vidyut 2012 - Amrita University









      SPOJ Problem Set (classical)

      12324. Tiles

      Problem code: NITT4

      Given a N x M floor with few blocks already filled, check if it is possible to fill the remaining space with only 2 x 1 blocks, if it is not possible, print the minimum number of 1 x 1 blocks required to fill the floor completely.

      Input

      First line contains N (number of rows), M (number of columns), B (number of already blocked cells), followed by B lines each containing 2 integers x, y coordinates of the blocked cell

      1 <= N <= 100, 1 <= M <= 100, 0 <= B <= N*M

      Output

      If it is possible to fill the floor with only 2 x 1 tiles, print Yes, else print No and the minimum number of 1 x 1 tiles required.

      Example

      Input:
      1 1 0
      Output:
      No 1
      Input:
      2 2 0
      Output:
      Yes
      Input:
      2 2 2
      0 1
      1 0
      Output:
      No 2

      Added by:jack(chakradarraju)
      Date:2012-09-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: NODEJS PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      12326. Dating Rishi

      Problem code: NITT8

                                                                            Dating Rishi

                      Its been Monday and Rishi   Dude is planning to select a girl to date for this week. So all N girls are standing in a line  from 1 to N so that Rishi will select one of them.  The girls are standing in a straight line but randomly. They know they cannot predict what Rishi The Great likes, He may like hot,smart,tall,short,witty,white,black or anything . But wait , Rishi ,the Coolest Dude  plans to date two girls this week !!!  How lucky they are ????  . But he wants to select two girls whose friendship quotient is maximum so that they wont fight too much over  Rishi during the date. He is shy too ! .Friendship quotient is defined as the product of absolute difference between the position of the two girls and the minimum height of the two girls.

                      Can you help Rishi to find the maximum friendship quotient ?

      Input Specification:

       

       The first line of input file contains T which denotes number of testcases.2*T lines follows.

      First line of each test case contains an integer N .

      Second line of each test case contains N space seperated integers denoting the height of each girl.

       

      Output Specification:

       

      The output must contain T lines each line corresponding to a testcase.

      Constraints:

      T<=20

      N<=100000

      Height[i]<=10^9

      Sample Input:

      2

      4

      3 2 1 3

      5

      4 2 3 1 4

      Sample Output:

      9

      16


      Added by:jack(chakradarraju)
      Date:2012-09-30
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Radhakrishnan









      SPOJ Problem Set (classical)

      12352. HNumbers

      Problem code: HNUMBERS


      H-Numbers 

      Note: Some tricky testcases were added on Feb. 26th, 2013 and time limit has been changed. All the solutions have been rejudge and some "Accepted" ones got Wron Answer/Time Limit Exceeded. However, this problem can still be solved by a simple and beautiful solution :)

      Ualter is a smart guy, and he loves mathematics and everything related with numbers. Recently his friend Matheus Pheverso showed him a group of H-numbers. Also, his friend told him that, in the Ancient Greek, there h-numbers would be used to create music. This group of numbers can be described in this way:

      • For each integer N, a positive integer A is H-Number with N only if:
        - LCM(N,A) = N*A

      • LCM is the Lowest Common Multiple between two numbers.

      • Ex1: N = 20, H-Numbers = {1,3,7,9,11,13,17,19}

      • Ex2: N = 10, H-Numbers = {1,3,7,9}

       

      Ualter loves classical music mainly Pachelbel's compositions. In order to achieve his old dream, he's willing to make a version of Canon in D using only h-numbers to create notes. To solve that problem, he needs, for each number N, the number of h-numbers of N that are between 1 and M, inclusive.

      Task

      You're given an integer Q - the number of queries - , and two numbers N,M in each query, your task is to find the number of h-numbers of N between 1 and an integer M.

      Input

      In the first line there's an integer Q ( 1 <= Q <= 10^5 ) representing the number of queries. In the next Q lines there're two numbers N,M ( 1 <= N, M <= 10^5 , M < N ). 

      Output

      You have to print for each query an integer xi representing the number of H-numbers of N less or equal to M.

      Examples

       

      Input:

      3

      20 15

      7 3

      10 8

       

      Output:

      6

      3

      3

       


      Added by:Mateus Dantas [ UFCG ]
      Date:2012-10-03
      Time limit:0.400s-1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Mateus Dantas









      SPOJ Problem Set (main)

      12357. Subset and upset (HARD)

      Problem code: SUBSHARD

      The whole world is crazy about subset sum. We define subset sum as sum of all subparts. A subpart is a number which is obtained by erasing certain digits and arranging the remaining numbers in the same order. You have to calculate the subset sum of the given number. Since the number can be very large return the subset sum modulo m.

      For example if the number is 1357, then the various subparts are 1, 3, 5, 7, 13, 15, 17, 35, 37, 57, 137, 135, 157, 357, 1357 .

      Input

      First line contains T(1 ≤ T ≤ 50) denoting the number of test cases.

      Next T lines containing two numbers n(0 < n < 101000) and m(1 < m < 109).

      Output

      Print the subset sum modulo m.

      Example

      Input:
      6
      111 9
      111 200
      456 9
      456 1000
      1357 1000
      1357 5000
      Output:
      3
      147
      6
      618
      333
      2333

       

      Time Limit ≈ 2*(My Python 3 Program Top Speed)

       

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2012-10-03
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Hard version of NITT5 problem.









      SPOJ Problem Set (classical)

      12363. Red And Green

      Problem code: RANDG

      Red & Green 

       

      You have several squares arranged in a single row. Each square is currently painted red or green. You can choose any of the squares and paint it over with either color. The goal is that, after painting, every red square is further to the left than any of the green squares. We want you to do it repainting the minimum possible number of squares.

      Squares are numbered from left to right. You will be given the initial arrangement as a String, such that character i is 'R' if square i is red or 'G' if square i is green. Print the minimum number of repaints needed to achieve the goal.

       

      Input

      There will be several test cases. Each test case will contain a string of not more than 50 characters on a separate line. Input is terminated by EOF.

      Output

      For each test case, print the output on a separate line.

       

      Constraints

      -Input will contain between 1 and 50 characters, inclusive.

      -Each character of input will be either 'R' or 'G'.

       

      Sample Input

      RGRGR

      RRRGGGGG

      GGGGRRR

      RGRGRGRGRGRGRGRGR

      Sample Output

      2

      0

      3

      8


      Solution & Dataset : Bidhan Roy 


      Added by:Bidhan Roy ( বিধান )
      Date:2012-10-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Topcoder









      SPOJ Problem Set (classical)

      12364. Awari 2

      Problem code: TAP2012A

      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/taip2012-problems.pdf]


      Awari is a one-player game from the Antilles, which is played with boxes and stones instead of cards. A particular variant of Awari is played with N boxes numbered from 1 to N, each containing at the beginning of the game zero or more stones. The rules of this game are very simple, because there is only one type of valid move, consisting of choosing a box numbered i containing exactly i stones, and then taking those stones from the box in order to use them to add a single stone to every box numbered 1 through i-1; the remaining stone is then kept by the player. These moves are applied in succession as long as there exists a box i containing exactly i stones. When this is no longer true, the game ends. The player wins if at this stage every box is empty, and looses otherwise.

      In the following figure, on the left hand side there is a possible initial state of a game with N = 5 boxes (the circles) containing P1 = 0, P2 = 1, P3 = 3, P4 = 0 and P5 = 2 stones (the black dots). If box number 3, containing P3 = 3 stones, was chosen to make the next move, then the resulting configuration would be the one shown on the right hand side of the figure. Additionally, the player would now have one stone in his power.

      Given the initial state of the boxes, you should determine if it is possible to win the game, that is, if there is a sequence of valid moves after which all the boxes are left empty.

       

      Input

      Each test case is described using two lines. The first line contains an integer N, indicating the number of boxes (1 ≤ N ≤ 500). The second line contains N integer numbers Pi, representing the number of stones in the boxes at the beginning of the game, from box 1 to box N in that order ( P_i  500 for i = 1, ..., N). In every test case there is at least one non-empty box, that is there exists i from 1 to N such that P≠ 0. The end of the input is signalled by a line containing the number -1.

       

      Output

      For each test case, you should print a single line containing a single character. This character should be the uppercase letter 'S' if it is possible to win the game; otherwise, it should be the uppercase letter 'N'.

       

      Awari is played with N boxes numbered from 1 to N, each
      containing at the beginning of the game zero or more stones.
      The rules of this game are very simple, because there is only
      one type of valid move, consisting of choosing a box numbered i
      containing exactly i stones, and then taking those stones from
      the box in order to use them to add a single stone to every box
      numbered 1 through i-1; the remaining stone is then kept by the
      player. These moves are applied in succession as long as there
      exists a box i containing exactly i stones. When this is no
      longer true, the game ends. The player wins if at this stage
      every box is empty, and looses otherwise.
      In the following figure, on the left hand side there is a
      possible initial state of a game with N = 5 boxes (the circles)
      containing P_1 = 0, P_2 = 1, P_3 = 3, P4 = 0 and P_5 = 2 stones
      (the black dots). If box number 3, containing P_3 = 3 stones,
      was chosen to make the next move, then the resulting
      configuration would be the one shown on the right hand side of
      the figure. Additionally, the player would now have one stone
      in his power.
      [IMAGE GOES HERE]
      Given the initial state of the boxes, you should determine if
      it is possible to win the game, that is, if there is a sequence
      of valid moves after which all the boxes are left empty.

      Example

      Input:
      5
      0 1 3 0 2
      4
      1 1 3 0
      3
      1 2 3
      -1
      
      Output:
      N
      S
      N
      

      Added by:Fidel Schaposnik
      Date:2012-10-04
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2012









      SPOJ Problem Set (classical)

      12365. Ball of Reconciliation

      Problem code: TAP2012B

      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/taip2012-problems.pdf]

       

      Every year the kingdoms of Cubiconia, Quadradonia and Nlogonia organize a ball to commemorate the end of the war that ravaged the region for many years. A certain number of noblemen of each kingdom is invited to participate in this event, and it is expected that every pair of guests coming from different kingdoms will dance together exactly once. That is, each of the guests from Cubiconia shall dance once with every guest from Quadradonia and Nlogonia; in turn, each of the guests from Quadradonia shall also dance once with every guest from Nlogonia. However, guests coming from the same kingdom are not allowed to dance with one another.

      To help organize the ball, the total number of dances that will take place is determined beforehand, so that care must be taken when choosing the number of noblemen that shall be invited from each kingdom. For example, if it is decided that the ball must have N = 20 dances, one possibility is to invite 6 noblemen from Cubiconia, 2 from Quadradonia and 1 from Nlogonia, which can be represented by the expression (6, 2, 1). This is a valid option because the total number of dances would then be 6*2 + 6*1 + 2*1 = 20.

      Traditions whose origins nobody can now remember indicate that the number of invited noblemen from Cubiconia must be greater or equal to the number of those coming from Quadradonia, and at the same time the number of invited noblemen from Quadradonia must be greater or equal to those coming from Nlogonia. Thus, for N = 20 dances there are exactly 5 possible ways to choose the number of guests from each kingdom, namely (5, 4, 0), (4, 2, 2), (10, 2, 0) and (20, 1, 0) as well as the aforementioned (6, 2, 1).

      With so many restrictions, the organizing committee has problems finding the ideal way to choose the number of guests from each kingdom. Your task is to help this committee by counting the different ways in which the number of guests can be chosen for a ball with N dances. Two of these ways are considered different if they differ in the number of invited noblemen from at least on of the three kingdoms.

       

      Input

      Each test case is described using a single line, containing an integer N representing the total number of dances that the ball must have (1 ≤ N ≤ 104). The end of the input is signalled by a line containing the number -1.

       

      Output

      For each test case, print a single line containing the number of different ways in which the number of guests from each kingdom can be chosen in order to have a ball where there are exactly N dances, with all the restrictions mentioned in the problem statement.

       

      Example

      Input:
      20
      1
      9747
      -1
      
      Output:
      5
      1
      57

      Added by:Fidel Schaposnik
      Date:2012-10-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2012









      SPOJ Problem Set (classical)

      12366. Cantor

      Problem code: TAP2012C

      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/taip2012-problems.pdf]

       

      The mathematician Georg Cantor was a lover of both sets and
      infinity, but he didn't get along too well with his colleagues.
      One morning he woke up with the idea of defining a set so
      strange that, when made public, would make the rest of the
      mathematicians lose their sleep for several days. And he was
      successful.
      The set he defined is called the Cantor set, and it is formed
      by all the real numbers in the interval [0, 1] whose decimal
      expression in base 3 uses exclusively the digits 0 and 2. This
      set has amazing properties, which we will not mention here so
      that you can sleep tonight. Moreover, and luckily for everyone
      involved, in this problem we will not be working with the
      Cantor set, but with a generalization of this set to the
      integer numbers.
      We will say that an integer number is of Cantor type, or a
      "cantiger" for short, if its expression in a given base B uses
      solely the digits in a given set C contained in {0, 1, ...,
      B-1}. Thus, the fact that a given number is a cantiger depends
      on how we choose B and C.
      Your task is to count cantiger numbers, in order to prevent the
      mathematicians of the entire world from loosing their sleep.
      More precisely, given two integers D and H, along with B and C,
      you have to count the number of cantigers with respect to B and
      C from D to H inclusive.

      The mathematician Georg Cantor was a lover of both sets and infinity, but he didn't get along too well with his colleagues. One morning he woke up with the idea of defining a set so strange that, when made public, would make the rest of the mathematicians lose their sleep for several days. And he was successful.

      The set he defined is called the Cantor set, and it is formed by all the real numbers in the interval [0, 1] whose decimal expression in base 3 uses exclusively the digits 0 and 2. This set has amazing properties, which we will not mention here so that you can sleep tonight. Moreover, and luckily for everyone involved, in this problem we will not be working with the Cantor set, but with a generalization of this set to the integer numbers.

      We will say that an integer number is of Cantor type, or a cantiger for short, if its expression in a given base B uses solely the digits in a given set C contained in {0, 1, ..., B-1}. Thus, the fact that a given number is a cantiger depends on how we choose B and C.

      Your task is to count cantiger numbers, in order to prevent the mathematicians of the entire world from loosing their sleep. More precisely, given two integers D and H, along with B and C, you have to count the number of cantigers with respect to B and C from D to H inclusive.

       

       

      Input

      Each test case is described using a single line. This line contains three integers, D, H and B, and a string L. The values of D and H indicate the endpoints of the closed interval [D, H] we are interested in (1 ≤ D  H  1016). The value of B is the base mentioned in the problem statement ( B  10). The string L = L0 L1 ... LB-1 has exactly B characters, and describes the set C also mentioned in the problem statement. The character Li is the uppercase letter 'S' if i is in C, and the uppercase letter 'N' otherwise (i = 0, 1, ..., B-1). The set C is non-empty, so that there is at least one 'S' character in L. The end of the input is signalled by a line containing three times the number -1 and a single '*' character.

       

       

      Output

      For each test case, you should print a single line containing an integer number, representing the number of cantigers (with respect to B and C) that are greater or equal to D and lower or equal to H.

       

       

      Example

      Input:
      1 10 3 SNS
      99 999 5 NSSNS
      1110 1111 10 NSNNNNNNNN
      1 10000000000000000 10 NNNNNSNNNN
      1 10000000000000000 7 SSSSSSS
      -1 -1 -1 *
      
      Output:
      3
      144
      1
      16
      10000000000000000
      

      Added by:Fidel Schaposnik
      Date:2012-10-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2012









      SPOJ Problem Set (classical)

      12367. Designing T-Shirts

      Problem code: TAP2012D

      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/taip2012-problems.pdf]

       

      Argentina's rugby is currently in one of its best moments of
      all time. Recently the under-18 and under-21 national teams
      qualified for their corresponding world cups, so the coaches of
      both teams have asked the Incredible Commission for the
      Production of Clothing (ICPC) to provide the t-shirts for these
      events. Each team is formed by N players, but because the two
      world cups do not take place simultaneously it was agreed that
      the ICPC would provide only N t-shirts, to be used by both
      teams.
      For this reason, the t-shirts must be a valid set of clothing
      for both teams. The rules if the rugby world cups state that
      each player must go in the field with a t-shirt imprinted with
      a unique number, along with a prefix of the player's surname,
      not necessarily unique. This includes boundary cases such as a
      t-shirt with no surname prefix (that is, a prefix of length 0)
      and a t-shirt with a complete surname.
      The experts of ICPC immediately realized that they could simply
      provide N t-shirts with only numbers and no surnames on them,
      and each of them would be a valid t-shirt to be used by any
      player. However, the coaches would rather have the t-shirts
      with the longest possible prefixes, of course without violating
      world cup rules, because this way it's easier for them to
      identify the players while the matches are taking place.
      Your task is to help the ICPC finding the maximum amount of
      letters that can be imprinted on a set of N t-shirts, so that
      this set is a valid clothing set for both teams. For example,
      if we have N=3 players, the under-18 team is composed of
      "PEREZ", "GONZALEZ" and "LOPEZ", whereas the under-21 team is
      composed of "GARCIA", "PERALTA" and "RODRIGUEZ", the optimal
      choice consists in having one t-shirt with the 1-letter prefix
      "G" (to be used by "GONZALEZ" and "GARCIA"), another one with
      the 3-letter prefix "PER" (to be used by "PEREZ" and
      "PERALTA"), and the third t-shirt with a 0-letter prefix (to be
      used by "LOPEZ" and "RODRIGUEZ"). This way, the answer in this
      case would be 1+3+0=4.

      Argentina's rugby is currently in one of its best moments of all time. Recently the under-18 and under-21 national teams qualified for their corresponding world cups, so the coaches of both teams have asked the Incredible Commission for the Production of Clothing (ICPC) to provide the t-shirts for these events. Each team is formed by N players, but because the two world cups do not take place simultaneously it was agreed that the ICPC would provide only N t-shirts, to be used by both teams.

      For this reason, the t-shirts must be a valid set of clothing for both teams. The rules of the rugby world cups state that each player must go in the field with a t-shirt imprinted with a unique number, along with a prefix of the player's surname, not necessarily unique. This includes boundary cases such as a t-shirt with no surname prefix (that is, a prefix of length 0) and a t-shirt with a complete surname.

      The experts of ICPC immediately realized that they could simply provide N t-shirts with only numbers and no surnames on them, and each of them would be a valid t-shirt to be used by any player of any of the two teams. However, the coaches would rather have the t-shirts with the longest possible prefixes, of course without violating world cup rules, because this way it's easier for them to identify the players while the matches are taking place.

      Your task is to help the ICPC finding the maximum amount of letters that can be imprinted on a set of N t-shirts, so that this set is a valid clothing set for both teams. For example, if we have N = 3 players, the under-18 team is composed of "PEREZ", "GONZALEZ" and "LOPEZ", whereas the under-21 team is composed of "GARCIA", "PERALTA" and "RODRIGUEZ", the optimal choice consists in having one t-shirt with the 1-letter prefix "G" (to be used by "GONZALEZ" and "GARCIA"), anotherone with the 3-letter prefix "PER" (to be used by "PEREZ" and "PERALTA"), and the third t-shirt with a 0-letter prefix (to be used by "LOPEZ" and "RODRIGUEZ"). This way, the answer in this case would be 1+3+0=4.

       

      Input

      Each test case is described using three lines. The first line contains a single integer number N, indicating the number of players in each of the two teams (1 ≤ N ≤ 104). The second line contains the surnames of the N players in the under-18 team, whereas the third line contains the surnames of the N players in the under-21 team. Each surname is a non-empty string of at most 100 uppercase letters. In each test case the total number of characters in the 2N surnames is at most 105, and two or more players of the same or different teams may have the same surname.

      The end of the input is indicated by a line containing the number -1.

       

      Output

      For each test case, you should print a single line containing an integer number, representing the maximum number of letters that can be imprinted on a set of N valid t-shirts to be used by both teams as explained in the problem statement.

       

      Example

      Input:
      3
      PEREZ GONZALEZ LOPEZ
      GARCIA PERALTA RODRIGUEZ
      2
      RODRIGO GONZALEZ
      GONZALO RODRIGUEZ
      3
      LOPEZ PEREZ LOPEZ
      PEREZ LOPEZ LOPEZ
      1
      GIMENEZ
      JIMENEZ
      6
      HEIDEGGER GAUSS GROTHENDIECK ERDOS CHURCH TURING
      HEISENBERG GALOIS EULER ALLEN GODEL CHURCHILL
      -1
      
      Output:
      4
      12
      15
      0
      13
      

      Added by:Fidel Schaposnik
      Date:2012-10-04
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2012









      SPOJ Problem Set (classical)

      12368. Emma s Domino

      Problem code: TAP2012E

      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/taip2012-problems.pdf]

       

      The domino effect is a phenomenon that occurs when in a line of
      domino pieces, each standing on its smallest face, the first
      piece from one of the line's ends falls in the direction of the
      next piece. In turn, this second piece falls over the third one
      in the line, and so on until the other end of the line is
      reached, at which point every piece has fallen. Note that in
      order to produce this effect, the distance between consecutive
      pieces in the line must be lower or equal to their height.
      Emma has very recently found out about the domino effect, and
      she was immediately amazed by it. She spent all morning forming
      a line with the N domino pieces that her brother Ezequiel gave
      her, but just before she was going to make the first piece
      fall, her grandma came to her home and took her to play in the
      park. Ezequiel knows Emma has not taken into account the
      distance between consecutive pieces when she formed her domino
      line, and doesn't want to see her frustrated if all the pieces
      do not fall after she pushes the first one. Thus, Ezequiel
      wants to move some pieces from inside the line so that the
      distance between consecutive pieces is always lower or equal to
      their height H. Because he doesn't want Emma to find out that
      he has moved some of the pieces, que will leave the first and
      last pieces where they are, and he would also like to move as
      few pieces as possible from inside the line. What is the
      minimum number of pieces he must move?

      The domino effect is a phenomenon that occurs when in a line of domino pieces, each standing on its smallest face, the first piece from one of the line's ends falls in the direction of the next piece. In turn, this second piece falls over the third one in the line, and so on until the other end of the line is reached, at which point every piece has fallen. Note that in order to produce this effect, the distance between consecutive pieces in the line must be lower or equal to their height.

      Emma has very recently found out about the domino effect, and she was immediately amazed by it. She spent all morning forming a line with the N domino pieces that her brother Ezequiel gave her, but just before she was going to make the first piece fall, her grandma came to her home and took her to play in the park. Ezequiel knows Emma has not taken into account the distance between consecutive pieces when she formed her domino line, and doesn't want to see her frustrated if all the pieces do not fall after she pushes the first one. Thus, Ezequiel wants to move some pieces from inside the line so that the distance between consecutive pieces is always lower or equal to their height H. Because he doesn't want Emma to find out that he has moved some of the pieces, he will leave the first and last pieces where they are, and he would also like to move as few pieces as possible from inside the line. What is the minimum number of pieces he must move?

       

      Input

      Each test case is described using two lines. The first line contains two integer numbers N and H, indicating respectively the number of pieces in the line (3 ≤ N  1000) and their height ( H  50). The second line contains N-1 integers Di, representing the distances between pairs of consecutive domino pieces, in the order given by the line ( Di ≤ 100 for i = 1, 2, ..., N-1). The end of the input is signalled by a line containing two times the number -1.

       

      Output

      For each test case, you should print a line containing a single integer number, representing the minimum number of pieces that must be moved in order to have the distance between consecutive pieces always lower or equal to H. Note that the first and last pieces cannot be moved, and that the relative order between the the pieces cannot be changed. If it is impossible to achieve the desired result, print the number -1.

       

      Example

      Input:
      8 3
      2 4 4 1 4 3 2
      10 2
      1 2 2 2 2 2 2 2 3
      5 2
      2 2 2 2
      5 3
      1 6 2 4
      -1 -1
      
      Output:
      3
      8
      0
      -1
      

      Added by:Fidel Schaposnik
      Date:2012-10-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2012









      SPOJ Problem Set (classical)

      12369. Fixture

      Problem code: TAP2012F

      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/taip2012-problems.pdf]

      The International Committee for Professional Chess (ICPC) organizes a Tournament for Advanced Players (TAP) with a very strange methodology. As expected, in each game exactly two players face each other, but in this case only one game takes place at a time, because there is only one chess board available. After receiving the inscriptions for the competitors and assigning them a number, the organization decides arbitrarily what matches are going to take place, and in which order. Each competitor can face any other competitor any number of times, and it is even possible that some competitors never play against others. Once built the general fixture of all the matches to be played, the organization hands each competitor a non-empty list of their rivals, in chronological order (that is, the order in which the matches will take place).

      Florencia signed up in first place, so that she was assigned the number 1. After chatting a bit with the other competitors, she realized that she had lost her list of rivals. Because she does not want to bother the TAP's organizers, she has asked all the other competitors for a copy of their own lists of rivals, hoping that with this information she would be able to reconstruct her lost list. Florencia is not sure if there exists a unique general fixture that is compatible with all the copied lists that she was given by the other competitors. However, she knows that the list that she was given by TAP's organizers is in fact unique. Your task is to help her reconstruct this list.

       

      Input

      Each test case is described using two lines. The first line contains a single integer number N, representing the number of competitors ( N ≤ 9). Each competitor is identified by a different integer from 1 to N, and competitor number 1 is always Florencia. The second line contains N-1 non-empty strings Li of at most 100 characters each (for i = 2, 3, ..., N). The string Li is composed solely of digits between 1 and N, excluding digit i, and represents the list of rivals of competitor number i in chronological order. Note that competitor number 1 appears at least once in one of the given lists. In each test case, there exists a unique list of rivals for competitor number 1 that is compatible with the other lists of rivals. The end of the input is signalled by a line containing the number -1.

       

      Output

      For each test case, you should print a single line containing a string, representing the unique list of rivals of competitor number 1 (Florencia) that is compatible with the lists of rivals of the other competitors. The rivals indicated in this list must appear in chronological order.

       

      Example

      Input:
      4
      314 142 321
      9
      31 412 513 614 715 816 917 18
      4
      11111111111111111111111111111 4 3
      -1
      
      Output:
      324
      98765432
      22222222222222222222222222222
      

      Added by:Fidel Schaposnik
      Date:2012-10-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2012









      SPOJ Problem Set (classical)

      12370. Generating Alien DNA

      Problem code: TAP2012G

      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/taip2012-problems.pdf]

      GigaFarma is one of the largest pharmaceutical companies in the world, and it is currently conducting experiments using alien DNA. Its goal is to produce a chain of alien DNA that will report the maximum possible benefit when commercialized.

      A chain of alien DNA can be understood as a non-empty sequence of genes connected by links, and in turn each gene is a non-empty sequence of bases. Because not every possible sequence of bases corresponds to a valid gene, GigaFarma has created a catalogue of genes that appear in alien DNA, which are the only ones considered valid sequences of bases. Each of these genes has a value according to its functionality, and a given chain of alien DNA has a market value that is the sum of the values of the genes that compose it.

      We will represent the different bases with lowercase letters, 'a'-'z', and links using a hyphen '-'. In the following example we can see on the left a possible list of genes and their corresponding values; on the right there are some chains of alien DNA that can be formed with these genes, along with their corresponding market values.

      TAP2012G1

      GigaFarma can only produce very specific DNA chains, which we call producible. These chains are a non-empty sequence of DNA portions that the company can synthesize, joined without any additional links between them. Each portion is a sequence of bases and links containing at least one link, but without any consecutive, initial or final links. Each portion has a given cost, determined by the difficulty associated to its production, so each producible chain of DNA has a production cost that is the sum of the costs of each of the portions that form it. In the following example, we can see on the left a list of DNA portions and their costs; on the right we have some producible chains of DNA that can be formed with these portions, along with their associated production cost.

      TAP2012G2

      Note that there might be multiple ways of forming the same producible chain using different portions. This is the case of "como-como-les" in the example, which can be obtained using portions "como-co" and "mo-les" with a production cost of 7, or just using "como-como-les" with a production cost of 12. Of course, when there is more than one way to synthesize a given producible chain of DNA, GigaFarma will always do so using the cheapest possible process.

       

      Clearly, the set of alien DNA chains is infinite, just like the set of producible DNA chains. However, GigaFarma is not directly interested in any of these sets, but in their intersection. If we check the previous examples, we can see that "como-les" is a valid alien DNA chain, but is not producible; "mo-les" is producible, but is not an alien DNA chain; and "como-como-les" is both. For each alien and producible DNA chain, the company can commercialize this chain to get a net benefit that equals the market value of this chain minus its production cost. Of course, if this net benefit is not positive, the corresponding chain will never be produced.

      Because there is so much genetic material all over the place, GigaFarma would pay anything in order to know what is the maximum net benefit it can obtain for some producible and alien DNA chain.

       

      Input

      Each test case is described using several lines. The first line
      contains two integer numbers G and P, representing the number
      of genes in the catalogue and the number of portions GigaFarma
      can produce (1 <= G, P <= 100).
      Each of the following G lines describes a different gene using
      a string S and an integer V. The string S has between 1 and 10
      characters, and is formed solely by lowercase letters
      representing the bases that form this gene; the integer V
      represents the value of this gene (1 <= V <= 1000).
      Each of the following P lines describe a different DNA portion,
      using a string T and an integer C. The string T has between 1
      and 30 characters, and is composed of lowercase letters and
      hyphens only, respectively representing the bases and links in
      this portion. T contains at least one link, but will never have
      initial, final or consecutive links. The integer C represents
      the production cost for the corresponding portion (1 <= C <=
      1000).
      Note that in every test case, all the genes are different from
      one another, and all the portions are different from one
      another. The end of the input is signalled by a line containing
      two times the number -1

      Each test case is described using several lines. The first line contains two integer numbers G and P, representing the number of genes in the catalogue and the number of portions GigaFarma can produce (1 ≤ G, P  100).

      Each of the following G lines describes a different gene using a string S and an integer V. The string S has between 1 and 10 characters, and is formed solely by lowercase letters representing the bases that form this gene; the integer V represents the value of this gene ( V  1000).

      Each of the following P lines describe a different DNA portion, using a string T and an integer C. The string T has between 1 and 30 characters, and is composed of lowercase letters and hyphens only, respectively representing the bases and links in this portion. T contains at least one link, but will never have initial, final or consecutive links. The integer C represents the production cost for the corresponding portion ( C  1000).

      Note that in every test case, all of the genes are different from one another, and all of the portions are also different from one another. The end of the input is signalled by a line containing two times the number -1.

       

      Output

      For each test case, you should print a single line containing an integer number, representing the maximum net benefit that GigaFarma can obtain from a producible and alien DNA chain. If no net benefit is positive, you should print the value 0. If the net benefit can be arbitrarily large, you should print an asteris '*'.

       

      Example

      Input:
      4 6
      hola 5
      como 5
      les 3
      va 2
      como-co 3
      mo-co 8
      mo-les 4
      como-como-les 12
      ta-no-sirven 100
      hasta-es 200
      2 3
      xyz 1000
      zyxxyz 1000
      xyz-zyx 1
      zyx-xyz 1
      xyz-xyz-zyx-xyz 1
      2 1
      abc 1
      abcabc 1000
      abc-abc 999
      1 1
      ser 10
      no-ser 5
      -1 -1
      
      Output:
      6
      0
      *
      0
      

      Added by:Fidel Schaposnik
      Date:2012-10-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2012









      SPOJ Problem Set (classical)

      12371. High Mountains

      Problem code: TAP2012H

      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/taip2012-problems.pdf]

      To go on holidays, Horacio and Hernan have sacrificed their participation in an important programming contest. While you are in this contest, they are close to the Andes driving along Highway 40, in Argentina, enjoying a pleasant view of the mountains in the horizon. Right now the sky over the highway is a clear, uniform blue, while the visible part of the mountains is a profile presenting rich and attractive textures. This worries Horacio and Hernan, because they fear that the pictures they are taking will be very expensive to print correctly. For this reason, in the next stop they will take out their laptops and write a program to estimate the area of the mountain profile that has to be printed in each picture. Can you finish this program before them?
      Horacio and Hernan will be modeling the mountain profile in the following way. Each mountain is represented by an isosceles triangle whose base rests on the X axis of the XY plane. Two equal-length sides connect the endpoints of the base to the opposite vertex of the triangle, which is the tip of the corresponding mountain. To describe the position and shape of the triangle, we use the coordinates along the X axis of the base endpoints, along with the height of the mountain.

      The figure below is the model of a mountain profile formed by 4 mountains that are overlapping with one another. The area of the surface of the mountain profile that you have to calculate is marked with stripes. The lowest mountain of the figure is described by the values I = 4 (the left endpoint of the mountain base), D = 5 (the right endpoint of the mountain base)  and H = 1 (the height of the

       

       

      mountain)

      To go on holidays, Horacio and Hernan have sacrificed their participation in an important programming contest. While you are in this contest, they are close to the Andes driving along Highway 40, in Argentina, enjoying a pleasant view of the mountains in the horizon. Right now the sky over the highway is a clear, uniform blue, while the visible part of the mountains is a profile presenting rich and attractive textures. This worries Horacio and Hernan, because they fear that the pictures they are taking will be very expensive to print correctly. For this reason, in the next stop they will take out their laptops and write a program to estimate the area of the mountain profile that has to be printed in each picture. Can you finish this program before them?

      Horacio and Hernan will be modeling the mountain profile in the following way. Each mountain is represented by an isosceles triangle whose base rests on the X axis of the XY plane. Two equal-length sides connect the endpoints of the base to the opposite vertex of the triangle, which is the tip of the corresponding mountain. To describe the position and shape of the triangle, we use the coordinates along the X axis of the base's endpoints, along with the height of the mountain.

      The figure below is the model of a mountain profile formed by 4 mountains that are overlapping with one another. The area of the mountain profile that you have to calculate is marked with stripes. The lowest mountain of the figure is described by the values I = 4 (the left endpoint of the mountain base), D = 5 (the right endpoint of the mountain base)  and H = 1 (the height of the mountain).

      TAP2012H

      In this problem, you are given the representation of the mountain profile, and you have to find the area of the union of all the corresponding triangles, in such a way that the overlapping parts are counted only once.

       

      Input

      Each test case is described using several lines. The first line contains a single integer number N, indicating the number of mountains (1 ≤ N  1000). Each of the N following lines describes a mountain using three integer numbers I, D and H, representing respectively the X coordinate of the left endpoint of the base, the same for the right endpoint of the base, and the height of the mountain ( I, D, H  105 with I < D). In each test case there are no two mountains that are exactly the same (that is, with equal values for the three parameters I, D and H). The end of the input is signalled by a line containing the number -1.

       

      Output

      For each test case, you should print a single line containing a rational number, representing the area of the corresponding mountain profile. Round the result to the closest rational with two decimal digits. In case of ties, round up. Note that you should always use exactly two digits after the decimal dot, even if this means ending with a zero.

       

      Example

      Input:
      4
      4 5 1
      2 4 2
      3 5 3
      3 7 2
      1
      1 2 1
      2
      10 20 20
      20 40 10
      2
      15 25 20
      20 40 10
      7
      99998 99999 25000
      99998 100000 50000
      99996 100000 100000
      1 3 100000
      2 5 100000
      1 5 60000
      1 99999 100000
      5
      2 3 10
      4 5 6
      6 8 11
      12 14 3
      1 13 2
      -1
      
      Output:
      6.90
      0.50
      200.00
      190.00
      5000331093.88
      28.91
      

      Added by:Fidel Schaposnik
      Date:2012-10-04
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2012









      SPOJ Problem Set (classical)

      12397. Johnny plays with connect 4

      Problem code: LCPC12B

      Description

      "Connect Four is a two-player game in which the players first choose a color and then take turns dropping colored discs from the top into a seven-column, six-row grid. The pieces fall straight down, occupying the next available space within the column. The objective of the game is to connect four of one's own discs of the same color next to each other vertically, horizontally, or diagonally before his opponent." – Wikipedia.

      Johnny plays with the connect-four board, Johnny has N discs and each disc has a number on it. Johnny drops these discs in the board columns. as Johnny was nervous he closed the top of the board and rotated it with different angles, when he rotate the board 90 degree, all pieces slide over their rows till they hit the board boundary or touch another piece. You will be given the board configuration and those rotation angles. And you should write a program that calculates the new discs’ positions.

      Input Format

      Input will start with T number of test cases. Followed by T test cases each test case starts with board dimensions R and C where R (1 < R < 100) is number of rows and C (1 < C < 100) is number of columns, and number of discs N (0 <= N <= R*C). Then N lines follow, each contains two integers: P specifying the column number (0 <= P < C) and Q specifying the disc number (0 <= Q <= 9). Then you will be given number of rotations L followed by L positive integers representing the rotation angles, all angles will be anti-clockwise in the main directions (90, 180, and 270) only.

      Output Format

      For each test case, output the result using the following format:

      k (the test case number starting at 1) followed by a period (on a line by itself), then the final configuration of the board. Each row on a line by itself, and each cell is either a "." (without quotes) if the cell is an empty or a number representing a piece.

       

      Sample Input

      Sample Output

      4

      2 3

      2

      0 5

      2 9

      0

      2 3

      2

      0 5

      2 9

      1 90

      2 3

      2

      0 5

      2 9

      1 180

      2 3

      2

      0 5

      2 9

      2 90 90

       

       

       

      1.

      ...

      5.9

      2.

      ..

      .9

      .5

      3.

      ...

      9.5

      4.

      ...

      .95

       


      Added by:Gareev
      Date:2012-10-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LCPC 2012









      SPOJ Problem Set (classical)

      12398. Johnny Listens to Music

      Problem code: LCPC12C

      Description

      Johnny loves to listen to music so much. Each day he decides to add, delete or listen to a music track on his laptop by doing one of the following operations:

      1. Download a new track.
      2. Delete the last downloaded track that is not deleted already.
      3. Listen to the shortest track that is already on his laptop.

      Each test case Johnny starts with an empty collection of tracks, at day  Johnny decides which action to be taken depending on the value of R[i] % 3. if R[i] % 3 = 0 he listens to the shortest track on his laptop, if R[i] % 3 = 1 he deletes the last downloaded track that is not deleted already, if R[i] %3 = 2 he downloads a new track whose length is R[i] minutes. Your task is to compute the total number of minutes Johnny spends listening to music.

      To keep the input small, it will be codified in the following way. You will be given an array h. Use the following pseudo-code on h to generate an array R.

      • input array: h
      • output array: R (of size n)
      • j := 0
      • m := size of h
      • for i := 0 to n-1
        • R[i] := h[j]
        • s := (j+1)%m
        • h[j] := ( ( h[j] ^ h[s] ) + 13 ) % 835454957
        • j := s

      This code, along with the constraints, ensures that the length of each track is between 0 and 835454956, inclusive. In the above code, % is the modulus operator and ^ is the bitwise XOR binary operator. If x and y are integers, (x ^ y) represents the bitwise XOR operation on them in C/C++ and Java.

      Input Format

      Input will start with T number of test cases. Each test case will consist of 2 lines the first line starts with 0 < n <= 10,000,000 (size of array R), 0 < m <= 50 (size of array h). The second line will contain M numbers 0 <= h[i] <= 835454956 which are the elements of array h.

      Output Format

      For each test case, output the result using the following format:

      k. S                                                                  

      Where k is the test case number (starting at 1), a single period, a single space, and S is the total time in minutes spent by Johnny listening to music.

      Sample Input

      Sample Output

      2

      6 6

      8 5 2 4 8 9

      10 4

      9 4 3 10

      1. 5

      2. 52

       


      Added by:Gareev
      Date:2012-10-05
      Time limit:40s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LCPC 2012









      SPOJ Problem Set (classical)

      12399. Johnny Hates Climbing

      Problem code: LCPC12D

      Description

      Johnny has a map of the gang block which shows the heights of all buildings within the block. The plan is that a helicopter will drop Johnny on the roof of one of the buildings on the boundaries of the block during night. Then Johnny will get to the boss's building by moving to adjacent buildings, vertically or horizontally. Going up severely affects Johnny’s heart, so he can only go to a building which has the same or smaller height as the current building.

      Given the gang building block map which shows the heights of all buildings in the block along with the boss building, write a program to help Johnny determine the safest path from any building on the boundary of the block to reach the boss’s building without going up. A path safety is measured by the maximum jump value between any two buildings along the path, where the jump value is the difference between the heights of the two buildings (the building he jumps from and the building he jumps to).  The safest path is the path with minimum safety value.

      Input Format

      The first line of input contains an integer T, the number of test cases. T test cases follow, the first line of each test case contains two integers (1 <= R,C <= 10) the height and the width of the building block. The second line contains two integers (1 <= BR <= R), and (1 <= BC <= C), the coordinates of the boss’s building on the map. R lines follows; each line consists of C space separated integers representing the heights of all buildings. A height H of a building satisfies (1 <= H <= 1000).

      Output Format

      For each test case, output the result using the following format:

      k. S

      Where k is the test case number (starting at 1), a single period (.), a single space, and S (the safety value of the safest path) or "IMPOSSIBLE" (quotes for clarity) if there is no path to the boss's building.

      Sample Input

      Sample Output

      2

      3 3

      2 2

      1 7 3

      2 6 3

      3 5 4

      2 2

      2 1

      2 7

      2 6

      1. 1

      2. 0

       

       

       

       


      Added by:Gareev
      Date:2012-10-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LCPC 2012









      SPOJ Problem Set (classical)

      12400. Johnnys Empire

      Problem code: LCPC12E


      Description

      Hundreds of years ago Johnny's father had a great kingdom. Before his death he divided his kingdom between his sons (Johnny and Johnny's brother). Johnny's brother took part of the kingdom with a circular shape with radius R.  Jonny took part of kingdom of squared shape with side length L. As Johnny was jealous from his brother after his father's death, he decided to extend his kingdom to be a circle such that the corners of the square lies exactly on the border of the circle. A problem might occur that Johnny could steal some land from his brother, and that could wage a huge war between the two brothers. So Johnny decided to convince his brother to build a wall separating between the two kingdoms. The wall should be connecting the two intersection points between the two circles. You are to estimate the length of this wall.

       

      Input Format         

      The first line of input contains an integer T, the number of test cases. T test cases follow, the first line of each test case contains 6 floating point numbers; 2 numbers denoting the center of Johnny's brother kingdom, another 2 for the center of Johnny's kingdom, R the radius of Johnny's brother kingdom A, and L the side length of the square of Johnny's kingdom. It’s guaranteed that both kingdoms don’t share any lands originally. Also after kingdom B is extended, it’s guaranteed that the intersection area will not cover Johnny's brother kingdom completely. The absolute value for all decimal numbers will be less than 109.

      Output Format

      There should be T lines, containing the following format.

      k. S

      Where k is the test case number (starting at 1), a single period, a single space and S represent a decimal number with exactly 3 digits after the decimal point representing the wall length. If there’s no possibility of war, print “No problem”.

      Sample Input

      Sample Output

      3

      0.0 0.0 10.0 0 3 3

      0.0 0.0 4.121 0 3 3

      -1 3 1 -1 2 7.071

      1. No problem

      2. 2.971

      3. 3.994

       


      Added by:Gareev
      Date:2012-10-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LCPC 2012









      SPOJ Problem Set (classical)

      12407. Johnny The Gambler

      Problem code: LCPC12F

      Johnny is a gambling addict. He entered a casino and started playing a game with the dealer. The game is as follows: the dealer deals a sequence of N cards, each card containing a number C[i] and asks Johnny how many pairs (j, k) such that j < k and C[j] + C[k] = X. If Johnny answers correctly he wins, otherwise the dealer wins.

      Input Format         

      The first line of input contains an integer T, the number of test cases. T test cases follow, Each test case start with the value of 0 <= X <= 2*103 followed by the number of cards 0 < N <= 105 followed by N numbers representing the numbers on the cards 0 <= C[i] < 103.

      Output Format

      There should be T lines, containing the following format.

      k. S

      Where k is the test case number (starting at 1), a single period, a single space and S representing the number of valid pairs (j, k) as described above.

      Sample Input

      Sample Input

      1

      10 3 1 5 9

      1. 1

       


      Added by:Gareev
      Date:2012-10-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LCPC 2012









      SPOJ Problem Set (classical)

      12408. Johnny Studies Genetics

      Problem code: LCPC12G

      Description

      While Johnny was studying a biology course he found a chapter about genetics and he started reading about it. Genetics is the study of genes, and studies what genes are and how they work. Genes are how living organisms inherit features from their ancestors; for example, children usually look like their parents because they have inherited their parents' genes. Genetics tries to identify which features are inherited, and explain how these features are passed from generation to generation. Genes are made from a long molecule called DNA, which is copied and inherited across generations. DNA is made of simple units that line up in a particular order within this large molecule. The order of these units carries genetic information, similar to how the order of letters on a page carries information. A chromosome is an organized structure of DNA. It is a single piece of coiled DNA containing many genes, regulatory elements and other nucleotide sequences. Chromosomes also contain DNA-bound proteins, which serve to package the DNA and control its functions.

      Johnny decided to run an experiment to simulate the behavior of inheritance of a chromosome C that can be modeled as an array of integers each element C[i] of the array represents a gene of that chromosome. The value of each gene will be between 0 and 1,000,000,006. Since Johnny does not like programming he requested your help to run a simulation for a very large number of generations to check the values of the chromosome after G generations. On each generation T the value of each gene is the summation of some genes from the generation T-1 mod 1,000,000,007. For example if the chromosome of length 3, has values of genes 4, 7, and 12 initially and the 1st gene in new generation calculated as sum of 1st gene and 2nd gene in previous generation and 2nd gene in new generation calculated as sum of 2nd gene and 3rd gene in previous generation and 3rd gene in new generation calculated as sum of 3rd gene and 1st gene in previous generation. So after 1st generation chromosome will be 11, 19, and 16 and after 2nd generation chromosome will be 30, 35, and 27 and so on till generation G.

      Input Format

      Input will start with T number of test cases. The first line of each test case will contain two integers G, N where 0 <= G < 1018 representing number of generations and 1 <= N <= 100 representing length of the chromosome. Followed by a line containing N integers n[i] separated by space where 0 <= i < N and 0 <= n[i] < 1,000,000,007 representing the value of each gene in the given chromosome. Followed by N lines, each line i start with integer M[i] representing the number of genes from the previous generation that is going to be added together to get the value of the new gene i at the new generation, followed by M[i] numbers x[j] where 0 <= j < M[i] and 0 <= x[j] < N representing the indices of genes to be added. The value of the gene at the new generation is  

      Output Format

      For each test case, output the result using the following format:

      k. n[0] n[1] …. n[N-1]

      Where k is the test case number (starting at 1), a single period, a single space, and n[i] is the value of ith gene after G generations.

      Sample Input

      Sample Output

      1

      2  3

      4 7 12

      2 0 1

      2 1 2

      2 2 0

      1. 30 35 27

       


      Added by:Gareev
      Date:2012-10-06
      Time limit:50s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LCPC 2012









      SPOJ Problem Set (classical)

      12409. Johnny at school

      Problem code: LCPC12H

      After Johnny spent a long day in school, he decided to play a spot game with his friends. A Spot game is played as follows, there are N spots on a horizontal line one after another, each spot i has a radius R[i]. The player may start at any spot, but is only allowed to move from one spot to another if it occurs after it in the line and its radius is greater than the previous one. When he plays a move on a spot i he earns P[i] points. The player wins when he goes through the maximum number of spots if there are multiple ways, He must earn the maximum sum of points, if there are still multiple ways he must select the one that is lexicographically maximal (Let A=(a1,...,aN) and B=(b1,...,bN) be two different but equally large solution, with a1 >= a2 >= ... >= aN and b1 >= b2 >= ... >= bN. Let x be the smallest index such that ax != bx. If ax > bx, we say that the set A is lexicographically larger than the set B). As Johnny is a smart boy he wants to play optimally, so he asked you to show him which spots to move in order to win the game, Can you help him? 

      Input Format

      Input will start with T number of test cases. Each test case starts with N where 1 <= N <= 1500 represent number of spots. Then follow N lines each contains two integers R[i] and P[i] where 1 <= R[i] <= 300 is the radius of i-th spot and 1 <= P[i] <= 2,000,000 is the points earned when you move on i-th spot.

      Output Format

      For each test case, output the result using the following format:

      K (start with 1) followed by a period, and a single space, then print the indices (1-based) of the spots that Johnny visits separated by a single space. If there are more than one subsequence of spots that makes Johnny wins then print the lexicographically largest.

       

      Sample Input

      Sample Output

      2

      6
      1 3
      2 3
      6 3
      4 20
      3 15
      9 10
      6
      1 3
      1 3
      6 3
      4 20
      3 15
      9 10

       

       

      1. 1 2 4 6

      2. 2 4 6

       

       


      Added by:Gareev
      Date:2012-10-06
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LCPC 2012









      SPOJ Problem Set (classical)

      12413. Toward Infinity

      Problem code: PONY6

      Story: Twilight Sparkle was working on some formulas when she came across a strange pattern.

      When she added 1/2 + 1/4 + 1/8 + ..., she saw that it kept getting closer and closer to 1.

      She was able to figure out that problem and a few more, but there are others that are too difficult. She needs your help.

      Problem Statement

      Given k and r, integers, find

      Sum from n = 1 to infinity of n^k / r^n.

      Also you must output the exact value, as a fraction in lowest terms.

      Input

      You will be given a number T on the first line. The following T lines will be of the form

      S k r

      where S is a String label with no spaces, and both k and r are as described above.

      Output

      Your output will contain T lines of the form

      S N / D

      where S is the label you were given in the input, N is the numerator of the answer, and D is the denominator. D may be 1.

      To be more precise, if the fraction is negative, then output the negative sign next to N.

      Example

      Input:
      6
      Case1: 0 2
      Case2: 0 3
      Case3: 0 -3
      Label: 2 9
      Otherlabel: 12 16
      Biggest: 50 -555
      
      
      Output:
      Case1: 1 / 1
      Case2: 1 / 2
      Case3: -1 / 4
      Label: 45 / 256
      Otherlabel: 268201436794928 / 320361328125
      Biggest: -71542844799237379223056641850683038399677651990786654293842285446351016224553939010
      

      882650681431892067495137019178862799169155069446928707568453465 /

      7086055907083154841158073677533359179964732523333455695465110902606507148230087594593

      20274728690683789654784801111318621847552

      Note: The output for each case should all be on one line. It is split in the final case here for readability.

      Bounds

      T <= 10000

      0 <= k <= 50

      1 < |r| <= 1000

      The timelimit per case is ~x5 my Java solution.


      Added by:Alex Anderson
      Date:2012-10-06
      Time limit:1s-5.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12421. Chocolate Distribution

      Problem code: KSELECT


      Problem Statement

      It is little John's birthday, and he has just received n boxes of chocolates as presents from his friends and family ( 1 < n <= 50 ). Now his mother knows that if she allows him to keep all the chocolates for himself, then he will definitely eat them all and end up with a stomach ache. So she instructs John to give one box each to each of the students in his class ( excluding himself ).

      Now John's class has k students, excluding himself, ( 1 <= k < 50 ) and the ith box of chocolates contains exactly a[ i ] chocolates inside ( 1 <= a[ i ] <= 1000 ). So John obviously wants to select the k boxes such that the sum of the chocolates in the remaining ( n-k ) boxes is maximized, so he has more chocolates for himself.

      This would be an easy task, except that John is very superstitious and wants to select these boxes in a very specific manner. He considers the number 4 and all its multiples to be extremely unlucky, and at no stage does he want the number of chocolates that he has to be a multiple of 4. Luckily, the sum of all the chocolates in all the n boxes is not a multiple of 4, and he wants to keep things that way.  So, while distributing the boxes, he will only consider handing out a box, if the sum of the remaining chocolates that he has is not a multiple of 4.

      John is confused as to how he should do this, so please help him out. Your task is to help John select k boxes from the n boxes one at a time, such that at no stage is the number of remaining chocolates a multiple of 4, and such that the final number of chocolates remaining with John is maximized ( and also not a multiple of 4 ).     

      NOTE : At every step, the sum of the chocolates in the remaining boxes must not be a multiple of 4. That is, after handing out the ith box, ( 1 <= i <= k ), the sum of the chocolates in the remaining ( n-i ) boxes should not be a multiple of 4.

       

      Input

      In the first line we have a single integer T - the number of test cases ( T <= 55 ). Then T test cases follow.

      Each test case contains 2 lines. The first line contains 2 space separated numbers - n, the number of boxes ( 1 < n <= 50 ), and k, the number of students in John's class, excluding himself ( 1 <= k < 50  )

      The second line contains n space separated numbers, such that the ith number ( a[ i ] ) denotes the number of chocolates in the ith box ( 1 <= a[ i ] <= 1000 ).

       

      Output

      For each test case, on a single line, print the maximum possible chocolates that John can end up with after a valid distribution sequence. Print -1 if no such distribution exists.

       

      Example

      Input:
      
      2
      6 3
      1 1 1 1 1 1
      8 6
      1 6 1 10 1 2 7 11

      Output:
      -1
      21


      Explanation:


      For the first case, the initial total number of chocolates is 6. After giving away any one of the boxes, the sum of chocolates remaining with John becomes 5. At this point, it becomes impossible to select any of the remaining boxes without making the sum with John a multiple of 4.


      For the second test case, the maximum chocolates that can remain with John after a valid distribution sequence is 21.

       

       


      Added by:Gowri Sundaram
      Date:2012-10-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      12436. The One-Dimensional Pool Table

      Problem code: THEPOOL


      A set of N billiard balls are set on a one-dimensional table. The table is 105 meters long, with two pockets at either side. Each ball has zero width and there is no friction so it is moving with a fixed velocity of either left or right and bounces back in a perfect elastic collision from other balls it encounter on its way (or drop into one of the pockets). Your job is to keep track of the balls' movements.

      Input

      The first number, N, is the number of balls (<= 105).

      This is followed by N pairs of numbers: the distance in meters from the left end of the table and the velocity (positive speed meaning it moves towards right).

      The next line tells you which ball you have to track ( 1 <= tracked ball <= N).
      The last line tells you the time T at which you have to locate the tracked ball.

      Note: Each number is on a separate line.

      Output

      You have to output the position (from the left end) of the tracked ball after time T.

      Example 1

      Input:
      1 
      50
      1
      1
      6 Output: 56

      Example 2

      Input:
      2 
      95
      -1
      10
      1
      1
      60 Output:
      35

      Explanation : 
      2 is the number of balls,
      One ball is placed at 95 from the left end. It's velocity is -1 (i.e. 1 m/s towards left).
      Another ball is at distance 10. Velocity is 1 (i.e. towards right).
      The first ball from left end is to be tracked. (i.e. ball at distance 10 from left end).
      You need to find the new position of the tracked ball at time t=60s.

      Added by:Vishrut Patel
      Date:2012-10-09
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IEEE Xtreme 5.0









      SPOJ Problem Set (classical)

      12446. BHAAD MEI JAAO

      Problem code: JUNL

       

       You are on vacation on a drunken island, but you couldn't resist the temptation of solving a good old problem. It all started when a group of kids played a game they call "The Falling Coconuts". In this game, a number of coconuts fall to the ground, one by one, on a single axis, at the locations given in drops. If a coconut X lands on the ground, it remains where it is. If it lands on top of another coconut Y, one of the following things happens: 
      - If coconut Y is surrounded on both sides by coconuts (denoted by 'O'), coconut X remains where it is.
           X
          OYO
      - If there is no coconut directly to the right of coconut Y, coconut X slides down to the position directly to the right of coconut Y.
           X
          OY   ->  OYX
           X
           Y   ->   YX
      - If there is a coconut directly to the right of coconut Y, but no coconut directly to the left of coconut Y, coconut X slides down to the position directly to the left of coconut Y.
           X
           YO  ->  XYO
      Each time coconut X slides down to a different position, it will continue to slide (following the behavior outlined above) until it's in a place where it will not slide any further. 
      The task is to display the final coconut configuration.
       

       

       

       You are on vacation on a drunken island, but you couldn't resist the temptation of solving a good old problem. It all started when a group of kids played a game they call "The Falling Coconuts". In this game, a number of coconuts fall to the ground, one by one, on a single axis, at the locations given in drops. If a coconut X lands on the ground, it remains where it is. If it lands on top of another coconut Y, one of the following things happens: 

       

      - If coconut Y is surrounded on both sides by coconuts (denoted by 'O'), coconut X remains where it is.

           X

          OYO

      - If there is no coconut directly to the right of coconut Y, coconut X slides down to the position directly to the right of coconut Y.

           X

          OY   ->  OYX

           X

           Y   ->   YX

      - If there is a coconut directly to the right of coconut Y, but no coconut directly to the left of coconut Y, coconut X slides down to the position directly to the left of coconut Y.

           X

           YO  ->  XYO

      Each time coconut X slides down to a different position, it will continue to slide (following the behavior outlined above) until it's in a place where it will not slide any further. 

      The task is to display the final coconut configuration.

       

       

       

      Input

      First line is t = number of test cases.

      Each test case consists of 2 lines , first line conataining the number of coconuts and second line contains n integers denoting the position of each cocnut on the x-axis. 

      Output

      As described in the problem statement.

      Example

      Input:
      2
      8
      8 9 10 11 12 8 12 10
      10
      6 8 10 7 9 8 8 8 8 8
      Output:
      ---O---
      OOOOOOO
       --O---
      -OOO--
      OOOOOO
      Explanation of test case 1:
      The configuration after each fallen coconut is given below:
                                                                               				  X
      X  ->  OX  ->  OOX  ->  000X  ->  0000X  ->  X00000  ->  000000X  ->  0000000
      In this diagram, 'X' denotes the last fallen coconut.
      

      Added by:Therapist
      Date:2012-10-12
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:AVIRAL,YASH,AMAN,ARADHYA









      SPOJ Problem Set (classical)

      12448. HOW MANY GAMES

      Problem code: GAMES

      Problem Statement:

      A player has played unknown number of games. We know the average score of the player (sum of scores in all the games / no. of games). Find the minimum number of games the player should have played to achieve that average.

      The player can score any non-negative integer score in a game.

      Input:

      The first line consists of an integer t, the number of test cases. Each test case consists of a single Rational Number which represents the average score of the player.


      Output:

      For each test case, find the minimum number of matches the player should have played to achieve that average.

      Input Constraints:

      1<=t<=1000
      1<=avg<=1000000 (maximum 4 digits after the decimal place)

      Example:

      Sample Input:

      3

      5

      5.5

      30.25

       

      Sample Output:

      1

      2

      4


      Added by:cegprakash
      Date:2012-10-12
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set ()

      12462. Boggle Scoring

      Problem code: BOGGLE


      In Boggle, you win points for words you find on the board which no other player finds. If another player finds the same word as you, neither player gets points for that word.

      For words of 4 or fewer letters, 1 point is awarded. 5-letter words are worth 2 points, 6-letter words are worth 3 points, 7-letter words are worth 5 points, and words longer than 7 letters are worth 11 points.

      Given the set of words that some boggle players found, determine the score of the winner.

      Input:
      The first line is the number of players (at most 100).
      Each subsequent line is the space-separated list of no more than than 50 words each no more than 50 characters (ASCII 33-126) that player found

      Output:
      The score of the winning player

      Input Output
      2
      one two three
      two three four
      1
      3
      good dual strange stranger would
      dual would duality dregs gnaw
      dual gnaw draw would student
      17
      2
      grid grades dread bread thread threads
      grid grids grade brood broods thread threads
      9

      Added by:Ben Dilts
      Date:2012-10-12
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK C++ 4.3.2 CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 PYTH 3.2.3 n SCALA SED TCL









      SPOJ Problem Set (classical)

      12471. DIE HARD

      Problem code: DIEHARD


      Problem Statement:

      The game is simple. You initially have ‘H’ amount of health and ‘A’ amount of armor. At any instant you can live in any of the three places - fire, water and air. After every unit time, you have to change your place of living. For example if you are currently living at fire, you can either step into water or air.

      If you step into air, your health increases by 3 and your armor increases by 2

      If you step into water, your health decreases by 5 and your armor decreases by 10

      If you step into fire, your health decreases by 20 and your armor increases by 5

      If your health or armor becomes <=0, you will die instantly

      Find the maximum time you can survive.

      Input:

      The first line consists of an integer t, the number of test cases. For each test case there will be two positive integers representing the initial health H and initial armor A.


      Output:

      For each test case find the maximum time you can survive.

       

      Note: You can choose any of the 3 places during your first move.

       

      Input Constraints:

      1<=t<=10
      1<=H,A<=1000

      Example:

      Sample Input:

      3

      2 10

      4 4

      20 8

       

      Sample Output:

      1

      1

      5


      Added by:cegprakash
      Date:2012-10-13
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      12474. MAXIMUM WOOD CUTTER

      Problem code: MAXWOODS


      Problem Statement:


      The image explains it all. You initially step at 0,0 facing right. At each step you can move according to the conditions specified in the image. You cannot step into the blocked boxes (in blue). Find the maximum number of trees you can cut.

      Input:

      The first line consists of an integer t, the number of test cases. For each test case the first line consists of two integers m and n, the number of rows and columns. Then follows the description of the matrix M.

      M[i][j]=’T’ if the region has a tree.

      M[i][j]=’#’ if the region is blocked.

      M[i][j]=’0’ (zero) otherwise.

      Output:

       

      For each test case find the maximum trees that you can cut.

       

      Input Constraints:

      1<=t<=10

      1<=m,n<=200

       

      Example:

      Sample Input:

      4

      5 5

      0TTTT

      T#T#0

      #TT#T

      T00T0

      T0#T0

      1 1

      T

      3 3

      T#T

      TTT

      T#T

      1 1

      #

      Sample Output:

      8

      1

      3

      0

       

      Solution for test case #1:


      Added by:cegprakash
      Date:2012-10-14
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Inspired from http://codeforces.com/problemset/problem/115/B









      SPOJ Problem Set (classical)

      12556. Another Traffic Problem

      Problem code: CDC12_A


       

      One day in a faraway city, Ronny, a famous scientist, was stuck in traffic once again. This thing
      happens everyday when he tries to get back home from work. But this time it was different,
      Ronny was working in a project that includes these situations about traffic and stuff. So in
      the middle of this dense traffic, Ronny started to think about a very interesting problem that
      includes traffic and how the cities are connected, including their avenues and intersections. The
      problem goes like this: There are at most N cities, connected by at most M roads. These roads
      are in one direction, so if you can go from city A to city B, then you can’t go from city B to city
      A. Following this scheme, every road will lead always forward from Ronny’s work to Ronny’s
      house.
      In a city i there are at most Ai avenues and at most Ii intersections, these ones are not in a
      singular direction. If an avenue Z let you go from the intersection X to intersection Y, then the
      same avenue Z will let you go from Y to X.
      Due the horrible traffic that hits the cities everyday and the smoke derivated from it, the au-
      thorities of each one of them will close a bunch of roads, allowing only one way from intersection
      1 to intersection Ii . This only way will be the way with the maximum capacity, i.e., there exist
      no other way with a higher capacity than this. Obviously, the capacity of this way is determined
      by the street with the minimum capacity.
      Due to the horrible traffic that hit the cities everyday, the authorities of each city close some
      avenues to avoid the city to overheat with the cars’ smoke. Of course, they will keep open
      those avenues that leads from the begining to the end of the city, i.e., from intersection 1 to
      intersection Ii . Beside that, the authorities will close exactly those avenues that are strictly not
      necesarily to maximize the ammount of vehicles that can transit in the city at a time.
      Fortunately, Ronny knows every little detail about the problem, even data! But not the an-
      swers. He will give you all the data of the problem, i.e., the number of cities, how are they
      connected, and the structure of each city, their avenues and how they connect their intesections.
      You may know that every road that goes from city A to city B, connects the last intersection of
      city A to the first intersection of city B. Ronny need your help to figure out whats the maximum
      ammount of vehicles that can go from Ronny’s work to Ronny’s house at a time.
      Input
      The first line contains an integer T , which specifies the number of test cases. Then, will follow
      the descriptions of T test cases.
      Every test case will have a line with 2 integers, N and M . Then N descriptions will follow,
      with a string N ame (That represents the name of the city, this one will contain only lower case
      CEIDEC 2012 - Contest Session
      2
      letters) and 2 integers Ii and Ai . Then Ai lines with 3 integers, X, Y and Cap; this mean
      that there is an avenue between the intersections X and Y with a capacity of Cap vehicles.
      After all N descriptions, M lines will follow, with 2 strings, S and D, and one integer C. This
      indicates that exists a road that goes from city S to city D with capacity of C vehicles at a
      time. You should know that Ronny’s house and Ronny’s work are valid cities, but they’re not
      included on the N cities that were mentioned before. These ”special” cities are going to be
      called "ronnys_house" and "ronnys_work". It is sure that it will exist at least one way to get
      from Ronny’s work to Ronny’s house.
      The input must be read from standard input.
      Output
      For each input case you must print "Scenario #i: " where i is the number of the test case
      that you are evaluating (Starting by 1). Then you have to print a single integer that maximum
      ammount of vehicules that can transit from Ronny’s house to Ronny’s work.
      The output must be written to standard output.

       

      One day in a faraway city, Ronny, a famous scientist, was stuck in traffic once again. This thing

      happens everyday when he tries to get back home from work. But this time it was different,

      Ronny was working in a project that includes these situations about traffic and stuff. So in

      the middle of this dense traffic, Ronny started to think about a very interesting problem that

      includes traffic and how the cities are connected, including their avenues and intersections. The

      problem goes like this: There are at most N cities, connected by at most M roads. These roads

      are in one direction, so if you can go from city A to city B, then you can’t go from city B to city

      A. Following this scheme, every road will lead always forward from Ronny’s work to Ronny’s

      house.

       

      In a city i there are at most Ai avenues and at most Ii intersections, these ones are not in a

      singular direction. If an avenue Z let you go from the intersection X to intersection Y, then the

      same avenue Z will let you go from Y to X.

      Due the horrible traffic that hits the cities everyday and the smoke derivated from it, the au-

      thorities of each one of them will close a bunch of roads, allowing only one way from intersection

      1 to intersection Ii . This only way will be the way with the maximum capacity, i.e., there exist

      no other way with a higher capacity than this. Obviously, the capacity of this way is determined

      by the street with the minimum capacity.

       

      Due to the horrible traffic that hit the cities everyday, the authorities of each city close some

      avenues to avoid the city to overheat with the cars’ smoke. Of course, they will keep open

      those avenues that leads from the begining to the end of the city, i.e., from intersection 1 to

      intersection Ii . Beside that, the authorities will close exactly those avenues that are strictly not

      necesarily to maximize the ammount of vehicles that can transit in the city at a time.

      Fortunately, Ronny knows every little detail about the problem, even data! But not the an-

      swers. He will give you all the data of the problem, i.e., the number of cities, how are they

      connected, and the structure of each city, their avenues and how they connect their intesections.

      You may know that every road that goes from city A to city B, connects the last intersection of

      city A to the first intersection of city B. Ronny need your help to figure out whats the maximum

      ammount of vehicles that can go from Ronny’s work to Ronny’s house at a time.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow

      the descriptions of T test cases.

      Every test case will have a line with 2 integers, N and M . Then N descriptions will follow,

      with a string N ame (That represents the name of the city, this one will contain only lower case

      letters) and 2 integers Ii and Ai . Then Ai lines with 3 integers, X, Y and Cap; this mean

      that there is an avenue between the intersections X and Y with a capacity of Cap vehicles.

      After all N descriptions, M lines will follow, with 2 strings, S and D, and one integer C. This

      indicates that exists a road that goes from city S to city D with capacity of C vehicles at a

      time. You should know that Ronny’s house and Ronny’s work are valid cities, but they’re not

      included on the N cities that were mentioned before. These ”special” cities are going to be

      called "ronnys_house" and "ronnys_work". It is sure that it will exist at least one way to get

      from Ronny’s work to Ronny’s house.

      The input must be read from standard input.

       

      Output

      For each input case you must print "Scenario #i: " where i is the number of the test case

      that you are evaluating (Starting by 1). Then you have to print a single integer that maximum

      ammount of vehicules that can transit from Ronny’s house to Ronny’s work.

      The output must be written to standard output.

      Input Output

      2

      2 4

      caracas 4 4

      1 2 2

      1 3 2

      2 3 2

      2 4 1

      valencia 4 5

      1 2 2

      1 3 3

      1 4 5

      2 4 1

      3 4 1

      ronnys_work caracas 4

      ronnys_work valencia 5

      caracas ronnys_house 2

      valencia ronnys_house 3

      4 7

      caracas 4 4

      1 2 2

      1 3 2

      2 3 2

      2 4 1

      valencia 4 4

      1 2 2

      1 3 3

      1 4 5

      3 4 1

      maracay 3 2

      1 2 2

      2 3 2

      maracaibo 5 6

      1 3 5

      1 4 2

      2 3 4

      2 4 4

      2 5 3

      4 5 4

      ronnys_work caracas 4

      ronnys_work maracaibo 5

      ronnys_work maracay 3

      caracas valencia 2

      maracay valencia 3

      valencia ronnys_house 4

      maracaibo ronnys_house 3

      Scenario #1: 4

      Scenario #2: 6

       

       

      Constraints

      • 1 ≤ T ≤ 10

      • 1 ≤ N ≤ 100

      • 1 ≤ Ii ≤ 30

      • 1 ≤ |S|, |D|, |N ame| ≤ 20

      • 1 ≤ X, Y ≤ Ii

      • 1 ≤ C, Cap ≤ 10,000

       


      Added by:Venezuelan Programming League
      Date:2012-10-27
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for UCV-CEIDEC contest.









      SPOJ Problem Set (classical)

      12557. Basic Routines

      Problem code: CDC12_B

       

      Ronny is arriving from the work and the terrible traffic he was on. He leaves the car keys and decides to go and lay down to think about the activities he must do. He soon realizes that some activities require more energy than others. Ronny has N activities planned, and each activity has a name and a value associated, which is the amount of energy Ronny will spend by doing this activity. In addition, Ronny recovers energy each time he finishes an activity. He recovers number of energy points equal to number activities he has completed. For example, if he has 80 points of energy and doing an activity X costs Y energy, then he will have 80−Y+1 energy points. If he then performs another activity with costing Z energy, he will have (80−Y +1)−Z+2 energy points. Ronny’s energy must never be lower than 0 points.

      He realized that he may not be able to complete all the activities. You are required to write a program to help him choose an subset of activities that can be finished with the given amount energy. See output description for more details.

       

      Input

      The first line contains an integer T , number of test cases. Then, descriptions of T test cases. Each test case will begin with two integers N and E, denoting respectively the number of activities that Ronny has planned and Ronny’s initial energy. N lines will follow, each with a string A and an integer V , denoting the name of the activity and the value associated with it.

      The data must be read from standard input.

       

      Output

      For each input case you must print two lines line. First must start with string "Scenario #i:", where i is the test case number (starting by 1). Next a space and the maximum number of activities Ronny can do. Second line must contain a list of activities sorted by name (order of execution may be different). There must be an space after each name.

      If there are many possible solutions, output the subset that requires the least amount of energy. If there is still a tie, output the lexicographical smaller sequence of names.

      The output must be written to standard output.

       

      Input Output
      2
      5 80
      CleanClothes 45
      MakeFood 40
      Shower 10
      EatFood 20
      WatchTv 5
      4 80
      Gaming 20
      TVShow 30
      ScoreSomeCoke 20
      DrinkCoke 10
      Scenario #1: 4
      EatFood MakeFood Shower WatchTv
      Scenario #2: 4
      DrinkCoke Gaming ScoreSomeCoke TVShow

       

      Constraints

       T ≤ 100

       1 ≤ N ≤ 100,000

       1 ≤ E ≤ 1,000,000

       1 ≤ |A| ≤ 100

       1 ≤ V ≤ 100

       

      First case analysis:

      Ronny can choose activities {1, 3, 4, 5} or {2, 3, 4, 5}. Doing the second set of activities costs him less energy, so that's the final answer.

       

      News: Inserted all test cases from the original contest. Statement updated.


      Added by:Venezuelan Programming League
      Date:2012-10-27
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for UCV-CEIDEC contest.









      SPOJ Problem Set (classical)

      12558. Collision Issue

      Problem code: CDC12_C

       

      When Ronny finished his routines, received a call from the Center of Extraordinary Investiga-
      tions Defining Excluded Creatures (or CEIDEC by its acronym).
      CEIDEC found a planet going through the orbit of the Earth at a great velocity, the planet was
      named Rainbowland by its fancy colors. We don’t know if this planet contains living creatures,
      what CEIDEC knows is that the collision is almost imminent. However, that’s why the CEI-
      DEC calls you: to create a program that, given three points in the space and assuming that
      the space only has two dimensions, compute if the three given points makes a perfect triangle,
      an isosceles triangle or an scalene triangle.
      In addition, CEIDEC would like to know the angle formed by these three points. Computing
      this would make the calculations for collision easier to perform. Obviously, CEIDEC will give
      you a useful formula to discover the angle θ on the triangle knowing the length of sides A,B
      and C. You must manipulate the following formula in order to get the angle formed by these
      three points:

       

      When Ronny finished his routines, received a call from the Center of Extraordinary Investiga-

      tions Defining Excluded Creatures (or CEIDEC by its acronym).

      CEIDEC found a planet going through the orbit of the Earth at a great velocity, the planet was

      named Rainbowland by its fancy colors. We don’t know if this planet contains living creatures,

      what CEIDEC knows is that the collision is almost imminent. However, that’s why the CEI-

      DEC calls you: to create a program that, given three points in the space and assuming that

      the space only has two dimensions, compute if the three given points makes a perfect triangle,

      an isosceles triangle or an scalene triangle.

      In addition, CEIDEC would like to know the angle formed by these three points. Computing

      this would make the calculations for collision easier to perform. Obviously, CEIDEC will give

      you a useful formula to discover the angle θ on the triangle knowing the length of sides A,B

      and C. You must manipulate the following formula in order to get the angle formed by these

      three points:

      sqrt( (A²) + (B²) - [ {8*A³*B³}^(1/3) * sin³(ø) * cot³(ø) * sec²(ø) ] ) = c

      That formula will find the angle between the vertex a and b.
      you must find if a triangle is Equilateral, Isosceles or Scalene and, in addition,
      you must find the name of the interior angular triangle, knowing that.


      • The sum of all interior angles must be equal to 180◦
      • A triangle will be Equiangular if all the angles are the same.
      • A triangle will be Right Triangle if one and only one angle is equal to 90◦
      • A triangle will be Obtuse if one angle is greater than 90◦
      • A triangle will be Acute if all the angles are lesser than 90◦


      Two floating points numbers will be considered equal if their absolute difference is lower than
      10⁻² . (Rounded), by instance, 3.14159265 it is considered 3.14.


      Input
      The first line contains an integer T , which specifies the number of test cases. Then, will follow
      the descriptions of T test cases.
      Each case will contain 3 lines, each of these three lines will contain two integers, denoting the
      coordinates (x,y) of every vertex in the triangle.
      The input must be read from standard input.


      Output
      For each input case you must print the string "Scenario #i:" where i is the test case you are
      analyzing (starting by 1) followed by the name by side of the triangle and (only for large cases)
      the name by interior angle of the triangle separated by a single space.
      The output must be written to standard output.

      Input Output
      4
      0 0
      0 3
      3 0
      0 0
      0 4
      3.464 2
      1 1
      5 5
      4 0
      1252 1322
      1904 1950
      1700 1700
      Scenario #1: Isosceles Right Triangle
      Scenario #2: Equilateral Equiangular
      Scenario #3: Scalene Acute
      Scenario #4: Scalene Obtuse

       

       

      Constraints

      • 1 ≤ T ≤ 100

      • -1,000,000 ≤ X ≤ 1,000,000

      • -1,000,000 ≤ Y ≤ 1,000,000

       


      Added by:Venezuelan Programming League
      Date:2012-10-27
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for UCV-CEIDEC contest.









      SPOJ Problem Set (classical)

      12559. Drastic Race

      Problem code: CDC12_D


       

      Rainbowland and planet Earth made a giant and a fancy collision! Now Ronny ran out of the
      CEIDEC worried and running to search his family, however, when he was running to his car, a
      Rainbowlandian explode the car, teddy bears flew out of it and Ronny was the first to discover
      officially that we’re not alone on this universe.
      Angry about his car explosion, Ronny shouted to the Rainbowlandian all sort of swearings,
      then, in the blink of an eye, several Rainbowlandians appeared with some strange vehicles de-
      scribing circles around Ronny and challenging him to do a race to some point of the empty
      highway. What the rainbowlandians don’t know is that Ronny got some special compound that
      gives him super reflexes and he can, with that, overtake the rainbowlandians by increasing his
      speed to the limit. However, this compound is very limited so Ronny must to use it wisely. He
      wants to reach his destination as soon as possible and faster than any other rainbowlandian
      chasing him, otherwise, the rainbowlandian will blow him up as they did with the car. Can you
      help him to determine whether he can win the race?
      You should take the following aspects in count:
      • Ronny can use the compound if and only if he is able to.
      • Ronny can restore the compound if and only if he stays still without moving.
      • Ronny can only win if his time is lesser than the fastest Rainbowland, so, in case of tie,
      Ronny lose.
      Input
      The first line contains an integer T , which specifies the number of test cases. Then, will follow
      the descriptions of T test cases.
      Each case will have 6 integers P , M , V , S, K, D, each of these denotes, respectively, the
      time that will take to the fastest rainbowlandian to get to the finish line, the meters up to the
      finish line, the normal velocity of Ronny, the boost that Ronny acquires when using the com-
      pound, the time that he can use the ability and the amount of compound he restores by second.
      (Have in count that he will not restore the compound more than what is given at the beginning)
      The input must be read from standard input.
      CEIDEC 2012 - Contest Session
      11
      Output
      For each input case you must print the string "Scenario #i: " where i is the test case you’re
      analyzing (starting by 1) followed by the string "Ronny wins in time R" if and only if Ronny
      is able to win the race, R is the units of time that Ronny takes to win the race, otherwise print
      "Ronny will be annihilated". (Quotes for clarity)
      The output must be written to standard output.

      Rainbowland and planet Earth made a giant and a fancy collision! Now Ronny ran out of the

      CEIDEC worried and running to search his family, however, when he was running to his car, a

      Rainbowlandian explode the car, teddy bears flew out of it and Ronny was the first to discover

      officially that we’re not alone on this universe.

      Angry about his car explosion, Ronny shouted to the Rainbowlandian all sort of swearings,

      then, in the blink of an eye, several Rainbowlandians appeared with some strange vehicles de-

      scribing circles around Ronny and challenging him to do a race to some point of the empty

      highway. What the rainbowlandians don’t know is that Ronny got some special compound that

      gives him super reflexes and he can, with that, overtake the rainbowlandians by increasing his

      speed to the limit. However, this compound is very limited so Ronny must to use it wisely. He

      wants to reach his destination as soon as possible and faster than any other rainbowlandian

      chasing him, otherwise, the rainbowlandian will blow him up as they did with the car. Can you

      help him to determine whether he can win the race?

      You should take the following aspects in count:

      • Ronny can use the compound if and only if he is able to.

      • Ronny can restore the compound if and only if he stays still without moving.

      • Ronny can only win if his time is lesser than the fastest Rainbowland, so, in case of tie,

      Ronny lose.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow

      the descriptions of T test cases.

      Each case will have 6 integers P , M , V , S, K, D, each of these denotes, respectively, the

      time that will take to the fastest rainbowlandian to get to the finish line, the meters up to the

      finish line, the normal velocity of Ronny, the boost that Ronny acquires when using the com-

      pound, the time that he can use the ability and the amount of compound he restores by second.

      (Have in count that he will not restore the compound more than what is given at the beginning)

      The input must be read from standard input.

       

      Output

      For each input case you must print the string "Scenario #i: " where i is the test case you’re

      analyzing (starting by 1) followed by the string "Ronny wins in time R" if and only if Ronny

      is able to win the race, R is the units of time that Ronny takes to win the race, otherwise print

      "Ronny will be annihilated". (Quotes for clarity)

      The output must be written to standard output.

      INPUT OUTPUT
      2
      10 500 40 40 5 1
      7 1000 40 40 5 1
      Scenario #1: Ronny wins in time 8
      Scenario #2: Ronny will be annihilated

       

      Constraints

      • 1 ≤ T ≤ 20

      • 1 ≤ P ≤ 10,000

      • 1 ≤ M ≤ 10,000

      • 1≤V ≤M

      • 1≤S≤M

      • 1 ≤ K ≤ 100

      • 1≤D≤K

       

       


      Added by:Venezuelan Programming League
      Date:2012-10-27
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for UCV-CEIDEC contest.









      SPOJ Problem Set (classical)

      12560. External Falling Objects

      Problem code: CDC12_E

       

       

      After Ronny finished the race challenge, he decided to go home. When he arrives, he notice
      that his family it’s not there, instead, there is a note that says: ”We are at the basement”.
      Ronny read this and decided to go to the basement. This one it’s located at some point of the
      backyard, but due to the collision and fusion of the planets, there are objects of the external
      planet falling from the sky, therefore, streets and gardens are full of these objects.
      These objects have different sizes and shapes, but always with the colors of the rainbow. Beside
      this, Ronny’s family will close the basement door after K minutes, to avoid a possible invasion
      of the new life forms that are arriving to the Earth. Ronny need to get to the basement before
      these K minutes. You must know that every object has a number, this number represents the
      time that Ronny will take to avoid it. Ronny can move to any of the adjacent position but
      never diagonal. Every step that Ronny make will take 1 second.
      Input
      The first line contains an integer T , which specifies the number of test cases. Then, will follow
      the descriptions of T test cases.
      For each test case, there will be a line with 3 integers, H, W and K. H and W are the dimen-
      sions of the garden, and K it’s the time in seconds that Ronny’s family will wait until they lock
      the door. Then H lines will follow, with W characters each; you may know that:
      • The character ’.’ denotes a free space on the garden.
      • One digit character denotes an object. An object with the number X on it represents
      that Ronny will take X seconds to avoid it.
      • The character ’R’ indicates the initial position of Ronny in the garden.
      • The character ’D’ indicates the door of the basement where is located Ronny’s family.
      The input must be read from standard input.
      Output
      For each input case you must print a line with "Scenario #i: " where i is the number of the
      test case that you are evaluating (starting by 1), followed by the minimum time that Ronny
      will take to reach his family. If it’s impossible to Ronny to reach his family in less than K units
      CEIDEC 2012 - Contest Session
      13
      of time, then you should print "Ronny will be destroyed". (Quotes for clarity)
      The output must be written to standard output.

       

      After Ronny finished the race challenge, he decided to go home. When he arrives, he notice

      that his family it’s not there, instead, there is a note that says: ”We are at the basement”.

      Ronny read this and decided to go to the basement. This one it’s located at some point of the

      backyard, but due to the collision and fusion of the planets, there are objects of the external

      planet falling from the sky, therefore, streets and gardens are full of these objects.

      These objects have different sizes and shapes, but always with the colors of the rainbow. Beside

      this, Ronny’s family will close the basement door after K minutes, to avoid a possible invasion

      of the new life forms that are arriving to the Earth. Ronny need to get to the basement before

      these K minutes. You must know that every object has a number, this number represents the

      time that Ronny will take to avoid it. Ronny can move to any of the adjacent position but

      never diagonal. Every step that Ronny make will take 1 second.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow

      the descriptions of T test cases.

      For each test case, there will be a line with 3 integers, H, W and K. H and W are the dimen-

      sions of the garden, and K it’s the time in seconds that Ronny’s family will wait until they lock

      the door. Then H lines will follow, with W characters each; you may know that:

      • The character ’.’ denotes a free space on the garden.

      • One digit character denotes an object. An object with the number X on it represents

      that Ronny will take X seconds to avoid it.

      • The character ’R’ indicates the initial position of Ronny in the garden.

      • The character ’D’ indicates the door of the basement where is located Ronny’s family.

      The input must be read from standard input.

       

      Output

      For each input case you must print a line with "Scenario #i: " where i is the number of the

      test case that you are evaluating (starting by 1), followed by the minimum time that Ronny

      will take to reach his family. If it’s impossible to Ronny to reach his family in less than K units

      of time, then you should print "Ronny will be destroyed". (Quotes for clarity)

      The output must be written to standard output.

      INPUT OUTPUT
      2
      2 2 2
      R9
      1D
      3 3 10
      R..
      42.
      D1.
      Scenario #1: Ronny will be destroyed
      Scenario #2: 6

       

       

      Constraints

      • 1 ≤ T ≤ 100

      • 1 ≤ H ≤ 1,000

      • 1 ≤ W ≤ 1,000

      • 1 ≤ K ≤ 8,000,000

       

       


      Added by:Venezuelan Programming League
      Date:2012-10-27
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for UCV-CEIDEC contest.









      SPOJ Problem Set (classical)

      12561. Forbidden Machine

      Problem code: CDC12_F

       

      Finally Ronny could make it to the safe place, he left his family there and decided to go to this
      new planet and talk to their King. Ronny know that he can’t do this by himself, so he called
      every army of the Earth to have a backup in case that things turn out bad.
      They made it to the new planet, and realize that it was like only rainbows and teddy bears,
      and just at the entrance there was a sign that said: ”Welcome to Rainbowland”. Ronny and
      his army went through this planet directly to their castle. At the entrance, a guard wearing a
      hat colored with rainbow colors, stopped Ronny. He said that Ronny could pass if and only if
      he could solve a puzzle: The Forbidden Machine Puzzle.
      This puzzle consists on a machine that takes strings, and then says if the strings are correct.
      A string is considered correct if it follows the rules of the machine. This rules consists on a
      sequence of state transitions. Each transition tells the machine that if it was in a state X, it
      can go to a state Y with a character Z on the string. The machine starts reading from the first
      position of the string, and each transition move the string one position to the left, so the next
      position to read it’s the second one. It is important to add that the machine always start on
      an initial state and a string follows the rules of the machine if and only if this can made it to
      a final state of the machine, and the string has been read completely. Ronny has a hard time
      understanding this machine, so he would like you to simulate it, in order to have the correct
      answer for the guard.
      Please note that a single state-character combination can lead to several different states.
      Input
      The first line contains an integer T , which specifies the number of test cases. Then, will follow
      the descriptions of T test cases.
      Each test case will contain a line with 4 integers, N , M , F and Q. N is the number of states
      of the machine, M is the number of transitions, F is the number of final states of the machine,
      and Q it’s the initial state. Then F lines will follow with a single integer E on it, representing
      that the state E it’s a final state. Then M lines will follow, with 2 integers I and J and a
      character C; this represents that there exists a transition that goes from state I to state J
      reading the character C. Then will be a line with an integer S, that indicate the number of
      strings to process, and S lines will follow, each one with a string A that has to be evaluated by
      Ronny.
      The input must be read from standard input.
      CEIDEC 2012 - Contest Session
      15
      Output
      For each input case you must "Scenario #i:" where i is the number of the test case that you
      are evaluating (Starting by 1). Then S lines, with the string and the answer of the machine for
      that string, if the string is correct, you should output "Accepted", and if it’s not, you should
      output "Rejected" (Quotes for clarity).
      The output must be written to standard output.
      Sample input Output for the sample input
      2 Scenario #1:
      4 8 1 0 ababbaa Rejected
      0 abababab Accepted
      0 1 a aaaabbbb Accepted
      1 0 a Scenario #2:
      1 2 b aaabcccc Rejected
      2 1 b aabbbbcdc Rejected
      0 3 b abbcdddcc Rejected
      3 0 b acdddddd Accepted
      3 2 a abc Accepted
      2 3 a 
      ababbaa 
      abababab 
      aaaabbbb 
      6 8 2 0 
      0 0 a 
      0 1 a 
      1 1 b 
      1 2 c 
      1 3 c 
      3 4 d 
      4 4 d 
      4 5 d 
      aaabcccc 
      aabbbbcdc 
      abbcdddcc 
      acdddddd 
      abc 
      CEIDEC 2012 - Contest Session
      Constraints
      • 1 ≤ T ≤ 100
      • 1 ≤ N ≤ 100
      • 1 ≤ F , Q, I, J, E ≤ N
      • 1 ≤ S ≤ 100
      • 1 ≤ |A| ≤ 1000

       

      Finally Ronny could make it to the safe place, he left his family there and decided to go to this new planet and talk to their King. Ronny know that he can’t do this by himself, so he called every army of the Earth to have a backup in case that things turn out bad.

      They made it to the new planet, and realize that it was like only rainbows and teddy bears, and just at the entrance there was a sign that said: ”Welcome to Rainbowland”. Ronny and his army went through this planet directly to their castle. At the entrance, a guard wearing a hat colored with rainbow colors, stopped Ronny. He said that Ronny could pass if and only if he could solve a puzzle: The Forbidden Machine Puzzle.

      This puzzle consists on a machine that takes strings, and then says if the strings are correct. A string is considered correct if it follows the rules of the machine. This rules consists on a sequence of state transitions. Each transition tells the machine that if it was in a state X, it can go to a state Y with a character Z on the string. The machine starts reading from the first

      position of the string, and each transition move the string one position to the left, so the next position to read it’s the second one. It is important to add that the machine always start on an initial state and a string follows the rules of the machine if and only if this can made it to a final state of the machine, and the string has been read completely. Ronny has a hard time understanding this machine, so he would like you to simulate it, in order to have the correct answer for the guard.

      Please note that a single state-character combination can lead to several different states.

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow

      the descriptions of T test cases.

      Each test case will contain a line with 4 integers, N , M , F and Q. N is the number of states of the machine, M is the number of transitions, F is the number of final states of the machine, and Q it’s the initial state. Then F lines will follow with a single integer E on it, representing that the state E it’s a final state. Then M lines will follow, with 2 integers I and J and a character C; this represents that there exists a transition that goes from state I to state J reading the character C. Then will be a line with an integer S, that indicate the number of strings to process, and S lines will follow, each one with a string A that has to be evaluated by Ronny.

      Output

      For each input case you must "Scenario #i:" where i is the number of the test case that you are evaluating (Starting by 1). Then S lines, with the string and the answer of the machine for that string, if the string is correct, you should output "Accepted", and if it’s not, you should output "Rejected" (Quotes for clarity).

      Sample input Output for the sample input

      INPUT OUTPUT

      2

      4 8 1 0 

      0 1 a 

      1 0 a 

      1 2 b 

      2 1 b

      0 3 b 

      3 0 b 

      3 2 a 

      2 3 a 

      ababbaa 

      abababab 

      aaaabbbb 

      6 8 2 0 

      0 0 a 

      0 1 a 

      1 1 b 

      1 2 c 

      1 3 c 

      3 4 d 

      4 4 d 

      4 5 d 

      aaabcccc 

      aabbbbcdc 

      abbcdddcc 

      acdddddd 

      abc 

      Scenario #1:

      ababbaa Rejected

      abababab Accepted

      aaaabbbb Accepted

      Scenario #2:

      aaabcccc Rejected

      aabbbbcdc Rejected

      abbcdddcc Rejected

      acdddddd Accepted

      abc Accepted

       

      Constraints

      • 1 ≤ T ≤ 100

      • 1 ≤ N ≤ 100

      • 1 ≤ F , Q, I, J, E ≤ N

      • 1 ≤ S ≤ 100

      • 1 ≤ |A| ≤ 1000

       

       


      Added by:Venezuelan Programming League
      Date:2012-10-27
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for UCV-CEIDEC contest.









      SPOJ Problem Set (classical)

      12562. Glory War

      Problem code: CDC12_G

       

      Ronny is hiding on the building where he left his family after failing the guard test (the guard

      told him not to cheat and got angry after your help). The rainbowlandians are brutally attack-

      ing the citizens of planet Earth, there are corpses everywhere and desesperate people running

      on the street. Ronny must protect his family and that’s why he has decided to take down all

      the rainbowlandians inside the building as soon as possible.

      Ronny know very little about the rainbowlandians, but he knows that he must be silent when

      he takes down one of then, hence, he hides his noisy gun in his pocket, impeding him to attack

      them from the distance. In order to take down the Rainbowlandians, a knife or a good flying

      kick will do the job. Ronny must step on the same space a Rainbowlandian is to take him

      down. The building is full of rubble and some paths will lead to a trap. Fortunately, Ronnie

      can throw a rope and go up or down through floors while he is walking the building. Obviously,

      he cannot throw the rope if this will lead him to a rubble-full step.

      Given the dimensions of the building, its width, height and depth and the marked targets,

      you’re to make a program to help Ronny take down the Rainbowlandians in the minimum

      steps possible so he can do the minimum noise possible.

      Please note that:

      • Ronny starts at the north west corner of the first floor of the building (1,1,1)

      • Ronny can only move to these possible directions: east, west, north, south, in addition,

      he can go while moving up or down.

      • Ronny cannot leave the building at any moment and there’s no basement in the building

      neither, so he can’t be lower than height 1.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow

      the descriptions of T test cases.

      Each test case will start with two integers N and H, where N denotes the width and depth of

      each floor and H denotes the number of floors. Then, there will be H N×N matrices, each one

      describing each floor. The floor description is composed of the following characters:

      • The character ’#’ denotes a rubble space.

      • The character ’.’ denotes a free space.

      • The character ’*’ denotes a rainbowlandian.

      The input must be read from standard input.

       

      Output

      For each input case you must print the string "Scenario #i: " where i is the test case you’re

      evaluating (starting by 1), followed by the minimum steps that Ronny have to make to take

      down all the enemies inside the building. If this is impossible, print -1.

      The output must be written to standard output.

       

      Input Output
      2 1 
      .. 
      .* 
      3 2 
      .#. 
      .## 
      ##. 
      #.# 
      ### 
      .#* 
      4 3 
      .... 
      .##. 
      #### 
      **** 
      #### 
      #### 
      .... 
      #.## 
      #### 
      *..* 
      *..* 
      #### 

      3

      2 1

      ..

      .*

      3 2

      .#.

      .##

      ##.

      #.#

      ###

      .#*

      4 3

      ....

      .##.

      ####

      ****

      ####

      ####

      ....

      #.##

      ####

      *..*

      *..*

      ####

      Scenario #1: 2

      Scenario #2: -1

      Scenario #3: 13

       

       

       

      Constraints

      • 1 ≤ T ≤ 30

      • 1 ≤ N ≤ 20

      • 1 ≤ H ≤ 20

      • 1 ≤ Targets ≤ 10

       


      Added by:Venezuelan Programming League
      Date:2012-10-27
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for UCV-CEIDEC contest.









      SPOJ Problem Set (classical)

      12563. Halt The War

      Problem code: CDC12_H


       

      The war was terrible, thousands of humans and rainbow people lying down on the streets.
      Ronny didn’t know what to do, so he decided to go and search for the Rainbowland Castle
      and talk to the King. The rainbowlandians stared at Ronny with caution, waiting him to do
      something bad just to get him and rainbow-kill him. Finally, Ronny made it to the King’s room
      and talked to him about stopping this horrible war. The King accepted Ronny’s proposal, but
      only with one condition, Ronny needed to prove once again what humanbeings were capable
      of. The King said that if Ronny answered the Q queries that he had for him about an order
      line of rainbow people numbered from 1 to N , he and his nation would go away. These rainbow
      people had a letter with a number on it (Initially this number it’s 0).
      There are two types of queries, modification queries and answer queries. The modification
      queries consists on, given an interval from A to B inclusive ([A,B]), Ronny needed to update
      those rainbow people’s letter, adding one to the number on it; so, by instance, if the interval is
      [1,2], then Ronny needed to add one to the first and second rainbowlandian on the line. The
      answer queries consists on, given an interval from A to B inclusive, Ronny should say the sum
      of every rainbow people’s letter.
      If Ronny can do this, the humans are saved! So he need your help, because he is not really that
      good in maths and fast sums.
      Input
      The first line contains an integer T , which specifies the number of test cases. Then, will follow
      the descriptions of T test cases.
      For each test case you will get an integer N and an integer Q, that represents the number of
      rainbowlandian in the line and the number of queries the King asks for. Then, Q lines will
      follow, each containing a string and 2 integers, the type of query, that can be "modification"
      or "answer" (Quotes for clarity), the first and the last rainbowlandian that Ronny must have
      in mind in order to answer the query.
      The input must be read from standard input.
      Output
      For each input case you must print the string "Scenario #i:" where i is the number of the
      test case (Starting by 1), followed by Q lines with the answer of each query. If the query was
      a modification query, then you should output "OK" (Quotes for clarity), otherwise, output the
      CEIDEC 2012 - Contest Session
      21
      sum of the number from A to B inclusive.
      The output must be written to standard output.

       

      The war was terrible, thousands of humans and rainbow people lying down on the streets.

      Ronny didn’t know what to do, so he decided to go and search for the Rainbowland Castle

      and talk to the King. The rainbowlandians stared at Ronny with caution, waiting him to do

      something bad just to get him and rainbow-kill him. Finally, Ronny made it to the King’s room

      and talked to him about stopping this horrible war. The King accepted Ronny’s proposal, but

      only with one condition, Ronny needed to prove once again what humanbeings were capable

      of. The King said that if Ronny answered the Q queries that he had for him about an order

      line of rainbow people numbered from 1 to N , he and his nation would go away. These rainbow

      people had a letter with a number on it (Initially this number it’s 0).

      There are two types of queries, modification queries and answer queries. The modification

      queries consists on, given an interval from A to B inclusive ([A,B]), Ronny needed to update

      those rainbow people’s letter, adding one to the number on it; so, by instance, if the interval is

      [1,2], then Ronny needed to add one to the first and second rainbowlandian on the line. The

      answer queries consists on, given an interval from A to B inclusive, Ronny should say the sum

      of every rainbow people’s letter.

      If Ronny can do this, the humans are saved! So he need your help, because he is not really that

      good in maths and fast sums.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow

      the descriptions of T test cases.

      For each test case you will get an integer N and an integer Q, that represents the number of

      rainbowlandian in the line and the number of queries the King asks for. Then, Q lines will

      follow, each containing a string and 2 integers, the type of query, that can be "modification"

      or "answer" (Quotes for clarity), the first and the last rainbowlandian that Ronny must have

      in mind in order to answer the query.

      The input must be read from standard input.

       

      Output

      For each input case you must print the string "Scenario #i:" where i is the number of the

      test case (Starting by 1), followed by Q lines with the answer of each query. If the query was

      a modification query, then you should output "OK" (Quotes for clarity), otherwise, output the

      sum of the number from A to B inclusive.

      The output must be written to standard output.

      INPUT OUTPUT
      2
      4 4
      answer 1 4
      modification 1 2
      modification 2 3
      answer 2 2
      8 6
      modification 2 4
      modification 4 8
      modification 4 5
      answer 8 8
      modification 5 7
      answer 4 8
      Scenario #1:
      0
      OK
      OK
      2
      Scenario #2:
      OK
      OK
      OK
      1
      OK
      11
      Constraints
      • 1 ≤ T ≤ 100
      • 1 ≤ N ≤ 100,000
      • 1 ≤ Q ≤ 100,000

       

       


      Added by:Venezuelan Programming League
      Date:2012-10-27
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem used for UCV-CEIDEC contest.









      SPOJ Problem Set (classical)

      12579. Search Insert Delete

      Problem code: SID


      You are given a bunch of data (all are positive 32 bit numbers) to operate on. The only operations on the data are search, insert, and delete. When storing the data you have to remember its rank, that is the original position when the data is being inserted. All successful operations must return the ranks of the data. Failed operations should return NONE as the answer.

      Your objective is to execute all of the operations as fast as possible.

      Input

      The first line of input is N and M, separated by a space, N is the number of initial data. ( 0 <= N < 1000000 ) and M is the number of operations against the data. ( 0 <= M < 1000000).

      The second line contains N data, seperated by blanks. All data are positive 32 bits numbers

      The next M lines contains operations against the data. Each line contains a symbol and a number, separated by a space. 

      There are 3 symbols (S, I, D), each representing search, insert, and delete operation.

      'S number' tries to find the number in the stored data, and outputs its first rank in the stored data (as originally inserted), or NONE if no such number exists.

      'I number' inserts the number into the stored data, and outputs its rank in the stored data. (Data can be duplicated).

      'D number' deletes the least ranked number found in the stored data, and outpus its rank, or NONE if no such number originally exists.

      Output

      There is an output for each executed operation. See the above input description about each operation for the detail of the output.

      Example

      Input:
      10 6
      20 12 10 28 20 50 49 8 51 1
      S 20
      I 3
      S 11
      D 20
      I 2
      S 20

      Output:
      1
      11
      NONE
      1
      12
      5

      Added by:Jimmy Tirtawangsa
      Date:2012-10-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own problem









      SPOJ Problem Set (classical)

      12587. CAMPANADAS 1

      Problem code: CAMPANA1


       

      The priest of a church want to know the number of times the bell will ring during a specified time interval. This interval starts on d1:h1:m1, and ends on d2:h2:m2; where d1:h1:m1 is the day-hour-minute of beginning, and d2:h2:m2 is hour-minute of the end.
      d1:h1:m1 and d2:h2:m2 are in the same day, and d1:h1:m1 <=  d2:h2:m2.
      El cura de una iglesia local quiere conocer exactamente cuántas veces deben sonar las campanas en un intervalo de tiempo determinado, y quiere que le desarrollemos un pequeño programa donde pueda ingresar la hora de comienzo y de final de dicho intervalo, y obtenga la cantidad de campanadas en él. (las campanas deben tocarse 1 vez en los minutos: 0, 15, 30 y 45).
      d1:h1:m1 y d2:h2:m2 están en el mismo día, y d1:h1:m1 <=  d2:h2:m2.
      Input - Entrada
      The input comes as a series of intervals, each in a different line. In each line there are six integers indicating day, hour and minute of the beginning and the end of the interval. The last line contains the values ??0 0 0 0 0 0, indicating end of data and should not be processed.
      In no case will be more than 1000 intervals in the input.
      La entrada viene como una serie de intervalos, cada uno en un renglón diferente. En cada renglón vienen 4 enteros que indican hora y minuto de comienzo, y hora y minuto de final. El último renglón contiene los valores 0 0 0 0, que indican final de datos y no deben procesarse.
      En ningún caso habrá más de 1000 intervalos en la entrada.
      Output - Salida
      The output to show in each input case, will be an integer indicating the number of times that the bell will ring.
      Como salida para cada uno de los casos de entrada, debe mostrarse un entero indicando la cantidad de campanadas de ese intervalo.
      Example - Ejemplo 
      Input - Entrada:
      8 0 8 56
      7 16 8 16
      0 0 0 0
      Output - Salida:
      4
      5

      Problem (english version) - Problema (versión en español)

      The priest of a church want to know the number of times the bell will ring during a specified time interval. This interval starts on h1:m1, and ends on h2:m2; where h1:m1 is the hour-minute of beginning, and h2:m2 is hour-minute of the end.

      h1:m1 and h2:m2 are in the same day, and h1:m1 <  h2:m2.

      El cura de una iglesia local quiere conocer exactamente cuántas veces deben sonar las campanas en un intervalo de tiempo determinado, y quiere que le desarrollemos un pequeño programa donde pueda ingresar la hora de comienzo y de final de dicho intervalo, y obtenga la cantidad de campanadas en él. (las campanas deben tocarse 1 vez en los minutos: 0, 15, 30 y 45).

      h1:m1 y h2:m2 están en el mismo día, y h1:m1 <  h2:m2.


      Input - Entrada

      The input comes as a series of intervals, each in a different line. In each line there are six integers indicating day, hour and minute of the beginning and the end of the interval (not included). The last line contains the values 0 0 0 0 0 0, indicating end of data and should not be processed.

      In no case will be more than 1000 intervals in the input.

      La entrada viene como una serie de intervalos, cada uno en un renglón diferente. En cada renglón vienen 4 enteros que indican hora y minuto de comienzo, y hora y minuto de final (no incluído). El último renglón contiene los valores 0 0 0 0, que indican final de datos y no deben procesarse.

      En ningún caso habrá más de 1000 intervalos en la entrada.


      Output - Salida

      The output to show in each input case, will be an integer indicating the number of times that the bell will ring.

      Como salida para cada uno de los casos de entrada, debe mostrarse un entero indicando la cantidad de campanadas de ese intervalo.

       

      Example - Ejemplo 

      Input - Entrada:

      8 0 8 56

      7 16 8 16

      0 0 0 15

      0 0 0 0


      Output - Salida:

      4

      4

      1


       


      Added by:Coach UTN FRSF
      Date:2012-10-29
      Time limit:1s-500s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      12600. Blade Master

      Problem code: BMASTER

      Loda and Maelk are legendary ChefCraft players. They have played so many games that this number doesn't fit in a standard 32-bit integer type. Today Loda and Maelk are going to sort the things out and find out who is the greatest ChefCraft player ever. So the great fight is coming. There are a lot of different heroes you may choose to play ChefCraft. Obviously every hero has his pros and cons. Loda perfectly plays Blade Master. His main skill is to make mirror images of himself to spoof the enemy.

       

      As every other popular game ChefCraft is played on a rectangular grid which consists of N rows and M columns. Rows of the grid are numbered by integers from 1 to N. So the upper row of the grid has number 1 and the lower row has number N. The same holds for columns. They are numbered by integers from 1 to M such that the most left column has number 1 while the most right column has number M.

       

      At the beginning of the game the only Blade Master's image stands on some starting cell (Sx, Sy) where 1 ≤ Sx ≤ N and 1 ≤ Sy ≤ M. Then Loda makes T moves. Maelk knows how the distribution of images on the grid changes after each Loda's move. This happens according to the following rules.

       

      1. If there is an image standing on the cell (i, j) then the new images appear by the next rules:

       

      • Let F(i, j) be the total number of images in the "cross" of the cell (i, j). The "cross" of the cell (i, j) is union of all cells in the i-th row of the grid and in the j-th column of the grid. So N + M − 1 cells belongs to the "cross".
      • Let X = F(i, j) mod 6, that is X is the remainder of the division of F(i, j) by 6.
      • For every possible value of X we have following values: D1, D2, P1 and P2.
      • D1 and D2 may be equal to one of the 4 values ['U', 'R', 'D', 'L'] and mean some two directions. Here 'U' means up, 'R' means right, 'D' means down and 'L' means left.
      • P1 and P2 are integer numbers.
      • New mirror images will appear at every cell in the direction D1 with the period P1 starting from cell (i, j) and in the direction D2 with the period P2 also starting from the cell (i, j). Of course, no images will appear out of the grid. For example, if D1 = 'U' and P1 = 2 then images appear at the cells (i − 2, j), (i − 4, j), (i − 6, j), and so on.
      • Loda always use the same values for D1 and D2. Namely,
        D1 = 'U', D2 = 'D' for X = 0,
        D1 = 'L', D2 = 'R' for X = 1,
        D1 = 'U', D2 = 'R' for X = 2,
        D1 = 'R', D2 = 'D' for X = 3,
        D1 = 'D', D2 = 'L' for X = 4,
        D1 = 'L', D2 = 'U' for X = 5.
      • But values P1 and P2 may vary for different games. But once chosen they will be the same for all moves.

       

      2. Appearing of new mirror images happens immediately.

       

      3. Whenever there is more than one image at the cell they start one on one fights. In each fight two images participate and both die. So if the number of images in the cell was even than all images will disappear in the end, otherwise exactly one image will remain at this cell.

       

      Now Maelk wants to choose his hero in order to win the fight. The most important thing he needs to know for this is how the number of images changes during Loda's moves. So he asks you for help. Denote by C(t) the number of images on the grid after the t-th Loda's move for t from 1 to T. For convenience we denote C(0) = 1 with meaning that 0-th move is the putting of the only Blade Master's image at the starting cell. Maelk wants you to calculate the sum C(0) + C(1) + ... + C(T). Since Maelk doesn't know what to expect from Loda he would like to know the answer for several values of T. As you remember the total number of games played by Maelk and Loda at ChefCraft doesn't fit in a standard 32-bit integer type. Of course, the same can hold for the number of moves in their final fight. Since Maelk plays ChefCraft the whole life he is not strong in math and can't calculate such large sums. So let's help him to win the final fight and become the only ChefCraft master ever.

      Input

      The first line of the input contains three space separated integers N, M and Q. Here N and M are sizes of the grid described above and Q is the number of Maelk's queries. The second line contains two space separated integers Sx and Sy, row index and column index of the starting position of the first image. Each of the following six lines contains two space separated integers, the values P1 and P2 for the corresponding X, that is, i-th line among these six lines contains values P1 and P2 for X = i − 1. Each of the following Q lines contains a single integer T, the number of Loda's moves for the corresponding Maelk's query.

      Output

      For every Maelk's query output on a separate line the numbers of images Maelk will see during Loda's move.

      Constrains

      N and M are positive
      NM34
      1SxN
      1SyM
      1P1, P2max{N, M}
      1Q100
      1T1016

      Example

      Input:
      3 3 3
      1 1
      1 1
      1 1
      1 1
      1 1
      1 1
      1 1
      1
      2
      3
      
      Output:
      4
      12
      17
      

      Explanation

      The initial grid looks as follows:
      100
      000
      000
      Here '1' represents a cell with an image and '0' represents a free cell.

      After the first move grid is
      111
      000
      000

      After the second move grid is
      101
      111
      111

      Finally, after the third move we have
      011
      101
      010

      So after the first move Maelk will see 3 images, after the second move – 8 images and after the third move – 5 images. Hence the answers for T = 1, 2, 3 are 1 + 3 = 4, 1 + 3 + 8 = 12 and 1 + 3 + 8 + 5 = 17 respectively.


      Added by:Roman Rubanenko
      Date:2012-10-31
      Time limit:1s-3.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CodeChef November Challenge 2012









      SPOJ Problem Set (classical)

      12609. Different Vectors

      Problem code: DIFFV

      You are given set of N vectors, each vector consists of K integers. Vector ex equals ey iff there exist function bijection f and integer r, such that ex[i] = f( ey[(i+r)%K] ), for each i in range [0, K> Eg. (1, 2, 2, 3) == (22, 3, 4, 22), with r=2 and f(22)=2, f(3)=3 and f(4)=1. But (22,3,22,4) is not equal to (1, 2, 2, 3).

      How many different vectors are there in set of N given vectors ?

      Constraints :

      n <= 10000

      k <= 100

      vector values are from range [0, 10^9]

      Input

      First number contains T (T <= 10), number of test cases. Each test cases consists of following. First line consists of N and K. N lines follows, the i-th containing K integers describing i-th vector.

      Output

      Output one number, number of different vectors.

      Input:
      2
      3 4
      22 3 4 22
      1 2 2 3
      22 3 22 4
      5 5
      3 3 3 0 3
      8 4 4 4 0
      1 1 1 1 1
      1 1 8 6 1
      1 3 3 3 5
      
      Output:
      2
      3

      Added by:Buda IM
      Date:2012-11-01
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12612. Path of the righteous man

      Problem code: RIOI_2_3


       You are given N*N matrix A filled with integers, which represents map of country "What" ("What" ain't no country I ever heard of) . Our hero is called Brett. Brett has many enemies, namely Jules and Vincent (Jules doesn't like him because he said "what" too many times), but his biggest enemy is Marcellus Wallace, because Brett treated him like a male dog treats female dog. And Marcellus most certainly does not look like a female dog. 

      But Brett cannot sit at home all day enjoying his Big Kahuna burgers, he has to go from cell (sx, sy) to cell (ex, ey).

      From cell (x, y) Bret can go to (x+1, y), (x, y+1), (x-1, y), (x, y-1).

      If A[x][y] = S, we say that this cell is property of mafia boss S. When Brett visits cell (x, y), and has not yet apologised to boss A[x][y], then he apologizes, after that he can visit any cell controlled by A[x][y] without apologizing. Brett does not like to apologise ( because there is always chance to hear Ezekiel 25 17 ), so he asks you to find him path which minimizes number of times he has to apologise.

      You are given N*N matrix A filled with integers, which represents map of country "What" ("What" ain't no country I ever heard of) . Our hero is called Bret. Bret has many enemies, namely Jules and Vincent (Jules doesn't like him because he said "what" too many times), but his biggest enemy is Marcellus Wallace, because Bret treated him like male dog treats female dog. 

      Bret has to go from cell (sx, sy) to cell (ex, ey).
      From cell (x, y) Bret can go to (x+1, y), (x, y+1), (x-1, y), (x, y-1).
      If A[x][y] = S, we say that this cell is property of mafia boss S. When Bret visits cell (x, y), and has not yet apologised to boss A[x][y], then he apologizes, after that he can visit any cell controlled by A[x][y] without apologizing. Bret does not like to apologise ( because there is always chance to hear Ezekiel 25 17 ), so he asks you to find him path which minimizes number of times he has to apologise.

      Constranits: 

      N <= 50

      0 <= A[i][j] < 10

      Input

      First line contains number t donating number of testcases. First line of each testcase consists of number N. N lines followscontaining N numbers donating matrix A. After that two lines follow, containing sx, sy and ex, ey.

      Output

      For each test output number minimal number of times bret has to apologise.

      Example

      Input:
      3
      5
      0 1 0 2 3
      0 2 0 3 1
      0 5 0 0 0
      0 5 7 8 0
      0 0 0 0 0
      0 0
      0 4 
      5
      0 1 0 2 3
      0 2 0 3 1
      0 5 0 0 0
      0 5 7 8 0
      0 0 0 0 0
      0 0
      0 2
      5
      0 1 0 8 3
      0 2 0 3 1
      0 5 0 0 0
      0 5 7 8 9
      0 0 0 0 0
      0 0
      0 3
      Output:
      3
      1
      2
      Explanation of second test case : Bret can reach cell (0, 2) following path on which each cell is controled by boss 0.
      NOTE : If you wish to understand references in problem statement, 
      watch movie Pulp Fiction, or this clip http://www.youtube.com/watch?v=aBs3Mu-qous

      Added by:Buda IM
      Date:2012-11-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12651. Finding Fishes

      Problem code: FISHES


      Marlin engaged Dory, last April and they decided to marry in next November. Unfortunately, Dory  is not like normal girls who their dowry is money, rings or furniture! She has many pictures of fishes and she wants a program that draws boxes around the fishes in the images. Time is passing and Marlin’s program just process the image and output some data that could be used to find the correct locations of these boxes. Please help him to save his marriage dream.

      Marlin outputs for every image:

      • 2 integers H and K.
      • A 2D Matrix M of integer values from 1 to K.
      • T integer vectors Vi, each of length K. Each vector is coupled with an integer value Xi.

      A Score Evaluator function is used to calculate the score of any box in the image, such that the higher box score, the more confidence in the box to tightly contain a fish. Hence, Marlin targets the box with the highest score that contains a fish.

      Given 4 corners of box B, the function works as following:

      • Construct vector V that has the frequencies of the values in M corresponding to B.
      • Calculate the score as:

      Score = H + SUM{i=1 to T}[Xi * (V.Vi)]

      where (a.b) means the dot product.

      Input

      The first line of input contains an integer S that represents the number of test cases, then S test cases follow. Each test case start with a line of 5 numbers R C H K T, where R and C are number of rows and columns for the matrix. K, T and H are as described in the problem. R lines follow each with C numbers corresponding to the matrix. Then T lines for the vectors follow each line starts with X of that vector, then K numbers of the vector.

      1 ≤ R,  C, H≤ 100, 1 ≤ K ≤ 500, 0 ≤ T ≤ 500, 0 ≤ G ≤ 100 and -5 ≤ X ≤ 5. G is the range of values for vectors Vi.

      Output

      For each test case, output on a single line “Case #K:” where K is the number of the test case, followed by a single integer which is the score of the box with highest to have a fish.

      Example

      Input:
      1
      3 4 7 3 2
      1 1 2 2
      1 2 2 3
      2 3 1 3
      -3 1 1 2
      4 7 2 10 Output: Case #1:
      234

      Explanation:
      Let's evaluate the first 2x2 box which is:
      1 1
      1 2
      1 occurred 3 times, 2 occurred 1 time and 3 occurred 0 times.
      Then the frequencies vector is [3 1 0] and its function evaluation is:
      7 + (- 3 * ([3 1 0]. [1 1 2]) + 4 * ([3 1 0].[7 2 10]) ) = 7 + (-12 + 92) = 87

      The first line of input contains an integer S that represents the number of test cases, then S test cases follow. Each test case start with a line of 5 numbers R C H K T, where R and C are number of rows and columns for the matrix. K, T and H are as described in the problem. R lines follow each with C numbers corresponding to the matrix. Then T lines for the vectors follow each line start α of the vector, then K numbers of the vector.

      1 ≤ R,  C, H≤ 100, 1 ≤ K ≤ 500, 0 ≤ T ≤ 500, 0 ≤ G ≤ 100 and -5 ≤ α ≤ 5. G is the range of values for vectors Vi.

      Added by:Mostafa Saad
      Date:2012-11-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:11th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      12660. Co-Prime

      Problem code: LCPC11B

      Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.

      Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.

      Input Specification

      The first line on input contains T (0 < T <= 100) the number of test cases, each of the next T lines contains three integers A, B, N where (1 <= A <= B <= 1015) and (1 <= N <= 109).

      Output Specification

      For each test case, print the number of integers between A and B inclusive which are relatively prime to N. Follow the output format below.

      Sample Input

      2

      1 10 2

      3 15 5

      Sample Output

      Case #1: 5

      Case #2: 10

      In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.

       


      Added by::-P
      Date:2012-11-06
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:LCPC2011









      SPOJ Problem Set (classical)

      12713. Strings

      Problem code: STRSOCU

      This problem features a story of a certain Black Kitten. Perhaps you saw a funny image where a few kittens sit and think about some mundane stuff, like “I want this”, “I want that”, while the black one thinks “I want to rule the Universe”... Well, that’s true! The Black Kitten took a long sheet of paper and wrote a String on it. That String should give him power to rule the Universe!.. (Or was he just going to win ACM ICPC Finals in 2013 with it?)

      The sad thing is that we’ll never know for sure because of other kittens and their stupid games. As you may know, many kittens like to shred furniture, wallpaper and other stuff like that. To make a long story short, a certain White Kitten shred the paper on which the String was written! No more ultimate power for the Black one. (What a mess.)

      Luckily, the String was only cut into two parts: the First part and the Second one. The Black Kitten now performs some rituals with the two parts. That, he believes, will help him gain some of the magical power. (Or maybe he is just practicing for the Finals?)

      Anyway, right now, the Black Kitten calculates the number of different substrings of the First part that occur in the Second part exactly K times. Two or more occurrences may overlap. Two substrings are considered different if they are not equal as strings. You may try and calculate the answer for him.

      Perhaps some of the power will be yours, too. (At the very least, you have a chance to improve your programming and problem solving skills by doing so.)

      Input

      The first line of input contains an integer T that represents the number of test cases. Every following test case is three lines, The first line of test case contains the First part of the String. The second line contains the Second part.

      Each of the parts is a non-empty string consisting of lowercase English letters, and the size of each is no more than 8,000 characters. The third line contains one positive integer K not exceeding the length of each of the given parts.

      Output

      For each test case, output on a single line “Case #T:” where T is the number of the test case, followed by a line contains one integer: the number of different substrings of the First part that occur in the Second part exactly K times.

      Example

      Input:
      3
      egyptnational
      ecpc
      1
      egyptnational
      ecpc
      2
      fastlast
      bestmost
      2 Output: Case #1:
      2
      Case #2:
      0
      Case #3:
      3

      Added by:Mostafa Saad
      Date:2012-11-10
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:11th Egyptian Collegiate Programming Contest -









      SPOJ Problem Set (classical)

      12714. Fatawy

      Problem code: FATAWY

      Fatawy is one of the most popular social networking site in Egypt during the last period. Every user is posting Fatwa through his profile to share his thoughts with his followers. And everyone can re-post a Fatwa and make some small modifications to this Fatwa before re-posting it.

      Zezo was interested to analyze all Fatawy from his followers and know what are the trending topics they are discussing in Egypt on a given day. So he tried to model a system to extract some features from every Fatwa, such that every Fatwa can be represented by at most 10 features and every feature is represented by one Capital Alphabetic character. And through his system he decided to define a relation between Fatawy, that's fatwa 'A' is on the same topic as Fatwa 'B', if values of fractions length(lcs)/length(A) and length(lcs)/length(B) in percent must both be bigger than TH where: lcs is the longest common subsequence of the feature vector of Fatwa 'A' and feature vector of Fatwa 'B' and TH is a threshold percentage of the Fatwa length. If Fatwa 'A' is on the same topic of Fatwa 'B', and Fatwa 'A' is on the same topic of Fatwa 'C', then Fatwa 'B' is on the same topic of fatwa 'C'. (See sample 1 for details).

      So as you all know that Zezo is not that good at programming and implementing this system, he will just help you by giving you the feature vector of every Fatwa, and he kindly ask you to find the number of different topics in that day.

      Note:
      The longest common subsequence (LCS) problem is to find the longest subsequence common to all sequences in a set of sequences (often just two). And it is good to notice that substrings are consecutive parts of a string, while subsequences need not be.

      Input

      The first line of input contains an integer T that represents the number of test cases. Every following test case will start with a line contains two integers N and TH (1 <= N <= 500) number of Fatway in a given day and TH is an integer number in the interval ]0, 100[ which is the threshold percent as explained in the problem description, followed by N lines every line contains a single string Fi of uppercase characters where 1 <= length(Fi) <= 10.

      Output

      For each test case, output on a single line “Case #T:” where T is the number of the test case, followed by a line contains the number of trending topics in that day.

      Example

      Input:
      2
      3 60
      ABC
      ABB
      ACC
      5 80
      BCCBC
      AAABB
      CACBC
      CABCB
      ABCAB Output: Case #1:
      1
      Case #2:
      2

      Explantation:

      the LCS between (ABC,ABB) = 2, Len(ABC) = 3, Len(ABB)=3, Len(ACC)=3
      LCS / Len(ABC) = 66.66 >= 60% && LCS / Len(ABB) = 66.66 >= 60%
      so ABC and ABB considered to be on the same topic.

      The same Applies for ABC and ACC: (ABC,ABB) are on the same topic, (ABC,ACC) are on the same topic, so (ABC, ACC, ABB)
      are considered to be on the same topic.

      Added by:Mostafa Saad
      Date:2012-11-10
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:11th Egyptian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      12721. Pell (Mid pelling)

      Problem code: PELL2

      D is a given positive integer, consider the equation :
      X² = D×Y² + 1, with X and Y positive integers.
      Find the minimum numbers (X,Y) within all solutions.
      Sometimes it's possible, sometimes not!

      Examples :
      If D=2, 3² = 2×2² + 1, so X=3 and Y=2.
      If D=3, 2² = 3×1² + 1, so X=2 and Y=1.
      If D=4, it's impossible!

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there is one integer D.

      Output

      For each test case, if possible print X and Y the answer of the problem for D, else "-1".

      Example

      Input:
      3
      2
      3
      4
      
      Output:
      3 2
      2 1
      -1
      

      Constraints

      T <= 1000
      1 < D <= 10^7, the numbers D were randomly chosen. (but XerK modified one of them!)
      190 bytes of sub-optimal python code can get AC in less than 2.5 seconds, there's many rooms to make faster code.
      If you have TLE, you should first consider EQU2 first.


      Added by:Francky
      Date:2012-11-11
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Old problem









      SPOJ Problem Set (classical)

      12726. XOR Game

      Problem code: QN01

      Problem Statement

      You are given an array of n integers ( 0 <= n <= 1000 ). Find a contiguous subsequence of these numbers [ ai, aj ] ( 1 <= i, j <= n ), such that the Exclusive-OR of these numbers is maximum. ( That is,  ai XOR ai+1 XOR... aj should be maximum ).

       

      Input

      The test case contains exactly 2 lines of input.

      The first line contains a single integer n ( 0 <= n <= 1000 ), the total number of integers in the sequence given to you.
      The next line contains n space separated integers such that the ith integer denotes ai. ( 0 <= ai <= 109 ). Note that these integers need not necessarily be distinct.

       

      Output

      Output two lines. In the first line, print out the value of the maximum XOR.
      In the second line, print out i and j with a space separating them, such that [ ai, aj ] ( both endpoints inclusive ) denotes the contiguous subsequence with the maximum XOR value.

      In case there is more than one subsequence with the maximum XOR value, print out the pair ( i, j ) such that ( i, j ) is lexicographically smallest. ( Formally, we say that a pair ( a, b ) is lexicographically smaller than another pair ( c,d ) if and only if (i) a < c or (ii) a=c and b < d. )

      NOTE : The subsequence must be non-empty, but may be allowed to contain just one integer. ( i.e, in this case, i = j )

       

      Example

      Input #1:
      
      1
      4
      Output #1:
      4
      1 1


      Input #2:

      3
      1 2 3

      Output #2:

      3
      1 2


      Explanation:
      1. In the first test case, since there is only one number, the maximum XOR would be simply the value of that number ( in this case, 4 ), and i = j = 1.
      2. In the second test case, the maximum XOR value is 3, but there are 2 contiguous subsequences that define the same XOR value - (i) [ 1, 2 ] since 1 XOR 2 = 3 (ii) [ 3, 3 ] since this subsequence contains just the single integer 3. But since [ 1, 2 ] is lexicographically smaller than [ 3, 3 ], [ 1, 2 ] is the desired output.

      Added by:Gowri Sundaram
      Date:2012-11-12
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      12734. Seating Arrangement

      Problem code: QN02


      Problem Statement

      In DA-IICT, the end sems are just around the corner and it seems like all the students are working very hard. But it's not just students, the professors are hard at work too. In particular, the Dean (Students) is very busy working out the exam seating arrangements for all the students.

      Now normally, as we all know, the benches in each of the exam halls can seat exactly 2 students. Also, it is ensured that every bench contains exactly 2 students from different batches (so that there is no copying). But inspite of this, the Dean has noticed that even if the 2 students are from totally different batches, if they are friends, then they tend to help each other (or atleast try to, depending on how much they both know). The Dean wants to prevent this, so the seating arrangement is such that no two friends sit side by side during any exam, so that the students prepare well for the exams. But he is falling short of ideas to work this out.

      Please help him out. You are given a list of pairs of IDs ( A, B ), such that the student with ID A is friends with the student with ID B. For every query ( C, D ) please print out whether or not these 2 students are friends ( meaning they cannot be seated with each other ).

      Note: In this case, please assume friendship to be both symmetric and transitive. That is, if A is friends with B, B is also friends with A. Moreover, if A and B are friends and B and C are friends, this implies that A and C are also friends.

       

      Input

      The input comprises of several lines. The first line contains 2 integers - n and m, where n is the number of students who will be writing the exam ( 2 <= n <= 100000 ) and m is the number of pairs of student IDs in the input. ( 0 <= m <= 100000. Also m <= n*( n+1 ) / 2  ).

      This is followed by m lines of the form : A B

      This indicates that the student with ID A is friends with the student with ID B. ( 0 <= A,B < n ).
       
      This is followed by a line containing a single integer q ( 1 <= q <= 100000 ) indicating the number of queries you have to answer. q lines of queries follow. Each query consists of a single line containing 2 space separated integers C and D. ( 0 <= C,D < n ). These are the 2 student IDs for which you have to state whether or not they are friends.

      Note
      : All student IDs are unique, and range from 0 to n-1.

       

      Output

      For each query, output a single line with "YES" if the 2 students are friends, and "NO" otherwise. Please note that the quotes are just for clarity, and that the output is case-sensitive.

       

      Example

      Input:
      
      7 4
      1 2
      2 3
      1 3
      4 5
      4
      1 3
      4 6
      5 1
      5 4

      Output:

      YES
      NO
      NO
      YES

      Added by:Gowri Sundaram
      Date:2012-11-12
      Time limit:1s-8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      12746. Colorful Circle (EASY)

      Problem code: CRCLE_UI

      ------------------------
      I take this problem from my midterm exam today, because for me and some of my friends it's interesting, so I decided to translated this problem into english and upload this problem to SPOJ. See the original problem in indonesian language here.
      ------------------------ 

      Given N sectors where 1<N<101000, from a circle that sown in the picture below:

      circle

      We will color each sector with K different colors, where 2<K<101000 such that each sector colored with one color and each adjacent sector must have different color. Your task is to count how many ways to color all that sectors.

      Input

      First line, there is a number T(0<T<1000) denoting number of test cases, then T lines follow.
      each line containing two integers: N and K separated by a space.

      Output

      For each test case, output number of ways to color the circle, since the number can be too large, take modulo 109+7.

      Example

      Input:
      2
      2 3
      3 3
      
      Output:
      6
      6

      Explanation:

      For the first case, we have two sectors and three colors, here is all possibilities:

      2 sectors 3 colors

      For second test case, we have three sector and three colors, here is all possibilities:

      3 sectors 3 colors

       

      Time limit set so that ~128 Bytes of python 3 code can get accepted, also my C top speed program AC in 0.12s
      Have fun :) 

       

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2012-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Discrete Math II, Midterm exam, question number 4, University of Indonesia, 14 November 2012 | Translated by: Tjandra









      SPOJ Problem Set (classical)

      12749. Dynamic Assignment Problem

      Problem code: DAP

      Description

      You‘ve been given a N×N matrix {W_ij} containing the cost of a weighted bipartite graph, on this graph, you need to implement the following operations:

      • C i j w : Change Wij to w.
      • X i x0 x1 ... xn-1 : Change all Wij to xj.
      • Y i y0 y1 ... yn-1 : Change all Wji to yj.
      • A : Add a new pair of node to the current bipartite graph, then increase N by 1. The weight of those 2n+1 new edges will be set to 0 by default.
      • Q : Query the current maximum weighted matching.

      Input

      N
      (.. . following the N×N matrix .. .)
      M
      (.. . following the M operation .. . .. . )

      Output

      ... 
      (for each query, simply print the result. )

      Example

      Input 1:
      2
      1 0
      0 1
      3
      Q
      C 0 1 9
      Q

      Output 1:
      2
      9

      Input 2:
      10
      76 98 80 30 87 84 78 75 53 26
      85 7 83 15 21 91 47 84 82 78
      36 39 49 64 71 14 53 2 82 21
      83 31 32 30 78 19 46 95 50 55
      50 76 63 54 99 55 50 16 29 26
      58 74 77 32 3 91 90 18 34 3
      56 23 2 78 84 83 71 41 32 54
      53 75 39 29 61 25 42 79 58 2
      19 13 65 94 9 33 61 5 1 70
      34 56 45 37 72 98 47 40 80 79
      20
      Q
      Y 3 62 90 89 41 58 56 34 55 53 53
      X 0 7 30 30 76 2 48 8 18 89 88
      Q
      C 2 0 3
      C 3 0 0
      C 8 0 2
      C 1 0 3
      C 1 0 6
      C 5 0 9
      Q
      A
      X 10 93 8 56 40 4 56 30 32 59 11 52
      Y 10 84 62 26 13 66 21 53 23 54 81 52
      Q
      Y 9 13 38 99 50 20 25 59 7 6 77 82
      C 4 0 8
      C 6 0 6
      C 10 0 8
      Q

      Output 2:

      870
      849
      844
      844
      839

      Restriction

      We guarantee the N will never be more than 100 even during the running time .. .
      The total operation M will less than 10000, and among them the Query Operation will less than 1000 .. .


      Added by:xiaodao
      Date:2012-11-14
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12807. Recursive Sequence (Version X)

      Problem code: SPP2


      Sequence (ai) of natural numbers is defined as follows:

      ai = bi (for i <= m)
      ai = c1ai-1 + c2ai-2 + ... + ctai-t (for i > t)

      where bj and cj are given natural numbers. Your task is to compute an and output it modulo 109+7.

       

       

      The above is the description of the original problem SEQ. However, to be a problem in a regional contest, the description will be slightly modified to make the problem a little bit complicated: for almost all integers i > m, ai follows the formula given above, but there are q exceptions n1, n2, ..., nq:

       

       

      ani = di1ani-1 + di2ani-2 + ... + ditiani-ti (for 1 <= i <= q)

       

       

      Input

      For each test case, the first line contains three integers n (m < n <= 109), m (1 <= m <= 100), q (0 <= q <= 100). The second line contains m integers b1, b2, ..., bm. The following line contains several integers, first comes t (t ≤ 100), then t integers c1, c2, ..., ct. The following q lines describe q special cases of the recurrent formula, each containing several integers, namely ni, ti (ti ≤ 100, ti < ni), di1, di2, ..., diti, as mentioned earlier. It is satisfied that all ni are distinct. All integers are non-negative. Unless specified, all integers are not greater than 109. Input is terminated by EOF. You might assume that all given data is correct. That is to say, all the required numbers can be fixed uniquely by the given input data.

      Output

      For each test case output the answer in a single line. Refer to the example for more format details.

      Example

      Input:
      7 5 0
      1 1 2 3 5
      2 1 1
      10 5 1
      1 1 2 3 5
      2 1 1
      10 2 1 2
      
      Output:
      Case 1: 13
      Case 2: 76
      

       

       


      Added by:[Trichromatic] XilinX
      Date:2012-11-21
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2012









      SPOJ Problem Set (classical)

      12809. Yet Another Mathematical Problem

      Problem code: MATHII


      Calculate the number of ordered triples of positive integers (a, b, c) such that their multiple abc is not larger than a given integer N (1 <= N <= 1011).

      Input

      Each test case contains a single line - N. Input terminates by EOF.

      Output

      For each test case output its case number (starting from 1) and the answer in a single line.

      Example

      Input:
      1
      3
      6
      10
      15
      21
      28
      
      Output:
      Case 1: 1
      Case 2: 7
      Case 3: 25
      Case 4: 53
      Case 5: 95
      Case 6: 161
      Case 7: 246
      

      Added by:[Trichromatic] XilinX
      Date:2012-11-21
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2012









      SPOJ Problem Set (classical)

      12810. Yet Another Multiple Problem

      Problem code: MULTII

      Given a positive integer N (1 <= N <= 10000) and some digits, find the smallest positive multiple of N whose decimal notation does not contain any of the given digits.

      Input

      Each test case contains two lines. The first line contains two integers N and m separated by a single space. The second line contains m digits separated by spaces. Input terminates by EOF.

      Output

      For each test case output its case number (starting from 1) and the answer in a single line, or "-1" (without quotes) if the answer doesn't exist.

      Example

      Input:
      2345 3
      7 8 9
      100 1
      0
      
      Output:
      Case 1: 2345
      Case 2: -1
      

      Added by:[Trichromatic] XilinX
      Date:2012-11-21
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACM/ICPC Regional Contest, Chengdu 2012









      SPOJ Problem Set (classical)

      12824. Print Big Binary Numbers

      Problem code: PBBN2

      Some answers for some problems could be huge binary numbers. In order to check the computation, one could ask you the sum of its digits. With a little base, the answer is a small number too, but not with a bigger base.

      XerK would like to avoid precomputed results and wish check you've computed his huge numbers. Here's a problem that check computation of a big number N. A tutorial edition exists without language restrictions.

      Let define the function CHK(N, B):
      Input : N a big number in binary representation, B a power of two. Consider N as a base B number.
      Output : the sum of its digits in this base.

      Example :with B=2^8, 12345678 = 78 + 97*B + 188*B*B, so CHK(12345678, B) = 78 + 97 + 188

      This should be easily computed with few bitwise-AND, bitshifts and additions.

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are four integers A, B, C, D, given in base 10.

      Output

      For each test case :
      * compute N = (A^B) XOR (C^D).
      * print CHK(N, 2^16384) as a base 10 number.
      (^ denote the power, and XOR the bitwise operator)

      Example

      Input:
      2
      7 3 5 4
      1234 5678 9012 4444
      
      
      Output:
      806
      1194204158794232147799<...snip...>9938532444216215551948305
      

      Explanations

      For test case 1:
      7^3 = 343, 5^4 = 625, 343 XOR 625 = 806, CHK(806, 2^16384) = 806.

      For test case 2:
      You have to output all 4933 digits of the result.

      Constraints

      1 < T <= 321
      1 < A, B, C, D <= 10^4
      

      Added by:Francky
      Date:2012-11-23
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:ASM C C++ 4.3.2 C++ 4.0.0-8 C99 strict D FORT PAS fpc PAS gpc
      Resource:Own problem









      SPOJ Problem Set (classical)

      12855. Teleport

      Problem code: TPORT

      Little Aron has to visit the planets of one system. Imagine that the planets are ordered in line and labeled with the numbers 1, ..., n.

      Aron has n-1 teleports labeled with 1, 2, ..., n-1. The teleport labeled with t could transmit only once, one human from a planet labeled with m to the planets with label m+t or m-t, if such planet exists. Using a space-stop Aron could go to the planet labeled with k, i.e. he starts his journey from a planet with a label k. For the given n and k you have to find the best way Aron can use the teleports in order to visit as many different planets of the system, as possible.

      Input

      First line containts two integers, n and k (1 <= k <= n <= 1 000 000).

      Output

      Output should contain indices t, of the teleports that Aron used, in the order in which he used them. Moreover you have to output t if he used the teleport to jump from a planet with the smaller number to a planet with a higher, and -t if he jumped from a planet with a higher number to a planet with a smaller number.

      If there are several solutions with the same number of teleports, you can output any one of them.

      Example

      Input:

      6 2

      Output:

      4 -5 3 -1 2

      NOTE - A simpler version of this task appeared on ITI 2012, Shumen.

      Added by:Dominik Gleich
      Date:2012-11-28
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Authors: Mislav Balunoviæ, Dominik Gleich









      SPOJ Problem Set (classical)

      12866. Nlogonian Tickets

      Problem code: NTICKETS

      You live in Nlogonia, a country that has N cities connected by some bidirectional roads (as usual). In Nlogonia, there is exactly one path between any pair of cities.

      You can't use the roads during your travels for free. There is an officer at each road that will let you use it only if you show him a certain number of tickets. If you don't have the required amount of tickets, you just can't use that road.

      The officer will not keep the tickets, though. You need to show the tickets to him, but you can keep them after that. This indicates that you can use the same ticket in more than one road, if you want to.

      You are given a description of the road system of Nlogonia and a number of queries. For each query, find the minimum number of tickets you must have to go from a city A to a city B. Consider that city A is the only place where you can buy tickets, so you must be holding all the tickets you will need during the travel before leaving city A.

      Input

      Each test case starts with a line containing the integer N (2 ≤ N ≤ 105), the number of cities in Nlogonia. The cities are numbered from 1 to N.

      Each of the next N-1 lines contains the description of a road, A B T (1 ≤ A, B ≤ N, A ≠ B, T ≤ 109), indicating that there's a road between the cities A and B, and you must show T tickets to use it. It's guaranteed that no pair of cities will appear more than once in the input.

      The next line contains the integer Q (1 ≤ Q ≤ 5×105), the number of queries. Each of the next Q lines contains two city numbers A B (1 ≤ A, B ≤ N, A ≠ B).

      The last test case is followed by a line containg the number 0.

      Output

      For each query A B, print the minimum number of tickets needed during the travel from city A to city B. Print a blank line after each test case.

      Example

      Input:
      6
      1 2 1
      1 3 5
      3 4 3
      3 5 8
      1 6 2
      3
      2 6
      5 2
      4 6
      0

      Output:
      2
      8
      5


      Added by:Ricardo Oliveira [UFPR]
      Date:2012-12-01
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:UFPR/Own problem









      SPOJ Problem Set (classical)

      12880. Sheep

      Problem code: KOZE

      Mirko has a herd of sheep, surrounded by fences backyard. While he was asleep, wolves have sneaked into the fenced area and attacked the sheep.

      Backyard is of a rectangular shape, and consists of fields arranged in rows and columns.

      Character '.' (fullstop) represents a blank field.

      Character '#' represents a fance.

      Character 'k' represents a sheep.

      Character 'v' represents a wolf.

       

      Two fields belong to the same sector if we can move from the field A to the field B without going over the fence, by making only horizontal and vertical steps (we cannot move diagonally).

      If we can escape from field A from the backyard, that field does not belong to any sector.

      Luckily, Mirko taught his sheep Kung-Fu skills, and they can defend themselves against wolves only if they outnumber the wolves in that sector. When there are more sheep in the sector than wolves, all wolves die without sheep casualties. Otherwise all sheep perish and wolves are unharmed. If a field doesn't belong in any sector, sheep will flee and wolfs will be left without a prey, so every animal survives.

       

      Write a program that will determine how many sheep and wolves will survive this bloody night.

       

      Input

      Integers N and M, number of rows and columns which represent Mirko's backyard.

      In every of the N lines, there are M characters representing the appearence of Mirko's backyard - positions of the fences, wolves and sheep.

       

      Constraints

      3 <= N, M <= 250

       

      Output

      In the first and the only line, print the number of sheep and wolves that will survive.

       

      Example

      Input:
      8 8  
      .######.  
      #..k...#  
      #.####.#  
      #.#v.#.#  
      #.#.k#k#  
      #k.##..#  
      #.v..v.#  
      .######. Output: 3 1

      Added by:Erik Lonèarek
      Date:2012-12-02
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Croatian Regionals 2005









      SPOJ Problem Set (classical)

      12887. Ant Colony Optimization

      Problem code: DCEPCA02

      Ants are known to move in groups and in perfect order. However, in our problem the ants can move only in directions Left(L), Right(R), Up(U), Down(D). The place is a rectangular grid. There lives 2 types of ants : Type A and Type B. Each ant type has its own queen ant which defines the 2 directions at which their type of ants can reproduce ants.

      A starting cell is given where one ant of each type is standing (A and B). When the process begins, each type of ant produces 4 ants, 2 ants of their type in the 2 directions (1 ant per direction) specified by their queen ant and 2 ants of the other type in the remaining 2 directions. So if queen ant of type A says LR and queen ant of type B says UD then A ant produces new type A ants at left cell and right cell and new type B ants at up cell and down cell of the original cell. Similarly, type B ant produces 2 new type A ants in left and right cell and 2 new type B ants in up cell and down cell. The ants produced again reproduce more ants at their adjacent cells according to the same directions given by the their queen ant.

      Reproducing ants at adjacent cells take 1 time unit. You need to find the sum of the minimum time in which type A ant reaches the endpoint and the minimum time in which type B ant reaches the endpoint. If any type of ant cannot reach endpoint, the answer is -1.

      Constraints

      T <= 10
      0 < M <= 500
      0 < N <= 500
      0 <= SX, EX < M
      0 <= SY, EY < N

      Input

      T denotes the number of testcases.
      Each testcase consists of 4 lines.
      First line gives M , N which is the size of grid
      Second line gives starting cell cordinates. SX , SY
      Third line gives endpoint cell cordinates  EX , EY
      Fourth line gives a permutation of LRUD denoting the directions provided by queen ant to move. The first two characters of the string gives the directions of queen ant type A and last two characters gives direction of queen ant type B.

      Output

      Print T lines each giving the minimum time in which ant of both types can reach the ending cell for each testcase ie. Find  sum of (minimum time at which A type ant reaches endpoint + minimum time at which B type ant reaches endpoint)

      Example

      Input:
      3
      5 5
      1 1
      3 4
      LRUD
      2 4
      0 2
      0 3
      RULD
      2 4
      0 2
      1 1
      URDL

      Output:

      10
      -1
      6

      Explanation:

      TestCase 1 : Minimum time at which A type ant reaches end point = 5
      Minimum time at which B type ant reaches endpoint = 5
      TestCase 2 : B cannot reach endpoint. Hence answer is -1.
      TestCase 3 : Minimum time at which A type ant reaches end point = 4
      Minimum time at which B type ant reaches endpoint = 2


      Added by:dce coders
      Date:2012-12-03
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12889. MAD

      Problem code: DCEPCA10

      Penny has started taking mathematics classes and has got better at it. She now wants to challenge Sheldon at this expertise and make a fool out of him. She writes down a list of numbers as list A and calculates the median of it. The she calculates the absolute deviation of each number from this median value to make list B. Now she finds the median of this list B. She asks Sheldon to find the minimum number of elements he needs to change in list A so that the median of list B becomes equal to 0.Can you help Sheldon doing this?

      For example :

      List of numbers (A):  4 5 3 1 2
      Median of list A=3
      List of Absolute Deviation from median(B) = 1 2 0 2 1
      Median of list B = 1

      Note: Median of even length list is the mean of 2 middle values.

      Constraints

      0 < T <= 10
      0 < N <= 10^5
      0 <= A[i] <= 10^9

      Input

      T No of testcases followed 2T lines.
      First line of testcase contains N , size of array
      Second line contains A[0] to A[N-1]  the numbers of the array.

      Output

      T lines each containing a single number which denotes the minimum number of elements we need to change to get the median of the absolute deviation of numbers from median to be 0.

      Example

      Input:
      2
      5
      4 5 3 1 2
      10
      5 5 5 254 5 5 768 5 5 5

       Output: 2
      0

      Added by:dce coders
      Date:2012-12-03
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12893. Short Select

      Problem code: DCEPCA04

      ICPC has grown very big this year and 100 teams have put in their applications to appear for onsite event. The problem setters were also able to make 44 problems which can be selected for the onsite event. Moreover,  they are very familiar with all the 100 teams and exactly know which team will be able to to solve which problem in the contest. They set a number X which should be the minimum number of total accepted solutions with which they can call the contest to be successful. Help them to find the ways in which they can select 10 problems out of 44 such that the  total number of accepted solutions are greater than or equal to the minimum number set by the judges.

      Note: There is only one testcase.

      Constraints

      0 <= X <= 10^9

      Input

      First 100 lines contain a binary matrix 100 by 44 which denotes which problem is solved by which team in the contest. Ie if A[i][j] = 1, it denotes that the ith team can solve jth problem.
      Next line contains a number X which is the minimum number of accepted solutions that is required by the judges

      Output

      Print a number which is the number of ways in which problem setters can select 10 problems out of 44 such that the total number of accepted solutions are greater than or equal to the number X set by them.

      Example

      Input:
      1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
      11
      Output: 0

      Added by:dce coders
      Date:2012-12-03
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12902. Good Luck

      Problem code: DCEPCA01

      A number is called lucky if it consists of only digits 4 and 7 ie. 4, 7, 44, 47 are lucky numbers while 3, 45, 4478 are not lucky. For a given lucky number the functions F(i) and G(i) are defined as follows

      F(i) = the number of 4’s from 0th to ith position in the number including positions 0 and i.
      G(i) = the number of 7’s from 0th to ith position in the number including positions 0 and i.

      Let H(i)= absolute(F(i)-F(i+1)-F(i+2)+F(i+3))

      A "Dynamic Number" is a lucky number which has maximum of summation(H(i)) from i = 0 to n-4 amongst all lucky numbers of length N.

      Given a number N , you need to find out the sum of the two smallest Dynamic Numbers of length N.If only one Dynamic Number is possible, then only that number is the answer.

      Note : Most significant bit is defined as the 0th position of the number.

      Constraints

      0 < T <= 100
      4 <= N <= 10^5

      Input

      It consists of T+1 lines. T denotes the number of test cases. Followed by T lines, each containing one number N.

      Output

      Output T lines, each containing a number as required.

      Example

      Input:
      1
      4

      Output: 8924

      Added by:dce coders
      Date:2012-12-04
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12903. Saving BOB - 2

      Problem code: DCEPCA08


      Alice and Bob devised a new game to play. Alice wrote an expression on the paper and started generating an array of numbers from that. She wrote the formula as
      a[i]=(51*a[i-1]+52)%53+1
      The array starts from index 1 and a[0]=1

      Bob takes all the numbers from that array upto an index N also given by Alice. He makes all the subsets possible from that array. He calculates the sum of numbers in each of the subsets and finds which of the subset is prime.A subset is prime if the sum of numbers in the subset is a prime number.Bob gets boggled by the enormous size of array that alice is generating and asking him to do this.Can you help Bob calculate the number of different prime subsets that can be made from the given array ?

      Constraints

      0<T<=100
      0<N <=10^5

      Input

      It consists of T+1 lines were T is the number of test cases and N is the index of the array upto which Bob has to calculate. The array of the numbers can always be formed from the formula that Alice wrote.
      Note : Array index starts from 1. Hence a[0] is not an element of the array.

      Output

      Print T lines each containing the number of different prime subsets that can be made from the array given.

      Example

      Input:
      2
      4
      5

       Output:
      3
      6
       

      Added by:dce coders
      Date:2012-12-04
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12908. Binary Matrix

      Problem code: BNMT

       You are given a matrix of size r x c. Each of the elements can be either 0 or 1.  In each operation you can flip any element of this matrix, i.e. convert 0 to 1 or convert 1 to 0. Your goal is to convert the matrix such that -

       

      1. Each of the rows will have the same number of 1s and

      2. Each of the columns will have the same number of 1s.

       

      What is the minimum number of operations required to achieve this?

       

      Input:

      Input starts with a positive integer T (~1000) which indicates the number of inputs.

       

      Each case starts with two integers m and n (1 <= r, c <= 40), here r is the number of rows and c is the number of columns of the matrix. Each of the next m lines will have n integers each, either 0 or 1.

       

      Output:

      For each test case, output “Case #: R” in a single line, where # will be replaced by case number and R will be replaced by the minimum number of steps required to achieve the target matrix. Replace R by -1 if it is not possible to reach target matrix.

       

      Sample Input:

      3

      2 3
      111

      111

      3 3

      011

      011

      011

      2 3
      001

      000

       

      Sample Output:

      Case 1: 0

      Case 2: 3

      Case 3: 1

       


      Added by:Race with time
      Date:2012-12-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACM ICPC Hatyai 2012









      SPOJ Problem Set (classical)

      12912. Saving BOB

      Problem code: DCEPCA06


      Alice and Bob start playing a new game. Alice writes 2 numbers - N and K. She asks Bob to find an integer which is N digits long such that the absolute difference in the adjacent digits is greater than or equal to K. Bob realizes that a lot of integers satisfy this condition.  Can you help Bob to find the total number of N digit integers which satisfy the condition set by Alice?
      Since the answer can be very large, print the answer modulus 1000000007.

      Note :

      The adjacent digits to a digit constitute both the left and right neighbor of the digit. Starting from the left, only the second digit is regarded as adjacent to the first digit and only the second last digit is regarded as adjacent to the last digit.

      Constraints

      T = 100
      2 <= N <= 10^9
      0 <= K <= 9

      Input

      First line contains T- the number of test cases. The next T lines contains two numbers N and K as given by Alice.

      Output

      Print T lines each containing the total number of integers of N digit mod 1000000007 which satisfy the condition set by Alice.

      Example

      Input:
      2
      2 9
      2 8
       
      Output: 1
      4

      Added by:dce coders
      Date:2012-12-05
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12914. Totient Extreme

      Problem code: DCEPCA03


      Given the value of N, you will have to find the value of H. The meaning of H is given in the following code

      H=0;

      For( i=1;i<=n;i++){

                      For( j=1;j<=n;j++){

                          H=H+totient(i)*totient(j);

                }

      }

      Totient or phi function, φ(n) is an arithmetic function that counts the number of positive integers less than or equal to n that are relatively prime to n. That is, if n is a positive integer, then φ(n) is the number of integers k in the range 1 ≤ k ≤ n for which gcd(n, k) = 1

      Constraints

      0 < T <= 50
      0 < N <= 10^4

      Input

      The first line contains T, the number of test cases. It is followed by T lines each containing a number N .

      Output

      For each line of input produce one line of output. This line contains the value of H for the corresponding N.

      Example

      Input:
      2
      3
      10
      
      Output:
      
      16
      1024

      Added by:dce coders
      Date:2012-12-05
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12916. MMM

      Problem code: DCEPCA09

      Everyone knows how to find mean, median and mode of an array of numbers. For people who don’t know this, here is the description:
      Mean is the arithmetic average of a set of values.
      Median of a finite list of numbers can be found by arranging all the observations from lowest value to highest value and picking the middle one. If there is an even number of observations, then there is no single middle value; the median is then usually defined to be the mean of the two middle values.
      The mode is the value that appears most often in a set of data. If more than one number is applicable to be the mode, select the highest value number amongst them as the mode.

      The problem is just to find these 3 values. Given an array of numbers and two indices i and j , find the mean , median and mode of elements in the interval i to j including numbers at indices i and j. Note that i and j are 0 index based.

      Constraints

      2 <= N <= 10000
      1 <= Q <= 10000
      0 <= A[i] <= 10^8
      0 <= i < N
      i <= j < N

      Input

      First line contains N which is the total number of numbers in the array. The next line contains N numbers A[i] which are the elements of the array. Next line contains a number Q which defines the total number of queries we are making for the interval i to j. It is followed by Q lines each containing 2 numbers i and j which denotes the indices to be queried for.

      Output

      Print Q lines each containing 3 numbers Mean, Median and Mode respectively. If the answer for any case comes to be a floating point, then take the integer part of the number as the answer.
      For example: if mean, median and mode comes up to be 6.44 7.8 9 then the final answer is 6 7 9.

      Example

      Input:
      5
      6 5 3 7 7
      2
      1 2
      0 4

       Output: 4 4 5
      5 6 7

      Added by:dce coders
      Date:2012-12-05
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12933. n-divisors

      Problem code: NDIV


      we all know about prime numbers, prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself .

      we can Classify the numbers by its number of divisors, as n-divisors-numbers, for example number 1 is 1-divisor number, number 4 is 3-divisors-number... ect .

      Note: all prime numbers are 2-divisors numbers.

      example :
      8 is a 4-divisors-number [1,2,4,8].

      Input

      three integers a, b, n.

      Output

      print single line the number of n-divisors numbers between a and b inclusive.


      Example

      Input:
      1 7 2
      Output:
      4

      constraints

      1 <= a,b<=10^9
      0 <=b - a <= 10^4 .
      1<= n <= 100


      Added by:abdelkarim
      Date:2012-12-07
      Time limit:1.200s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Owner









      SPOJ Problem Set (classical)

      12943. Counting

      Problem code: RIOI_3_2

      Given integers N and M, output in how many ways you can take N distinct positive integers such that sum of those integers is <= M. Since result can be huge, output it modulo 1000000007 (10^9 + 7)

      N <= 20 

      M <= 100000 

      Input

      First line of input is number t, number of test cases. Each test case consists only of 2 numbers N and M, in that order. 

      Output

      Output number aksed in description.

      Example

      Input:
      3
      6 16
      4 16
      4
      6 16
      4 16
      1 14
      3 7
      1 14
      Output: 0
      27
      14
      2

      Added by:Buda IM
      Date:2012-12-08
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Known Problem









      SPOJ Problem Set (classical)

      12958. Another Gift Problem

      Problem code: VPL0_A


       Luis is becoming mad because his family hid all the christmas gift in the family’s apartment, as his family is wealth, they own a giant skyscrapper that has many floors, by using elevators, he wants to find all the gifts.

      Luis’ parents went out and this is the perfect opportunity he has to sneak and view the christmas gifts before christmas eve! Luis earned a map of the building and marked the places where he can find the gifts. An elevator of the building can only go up and go down, now, you can assume that the elevators will always be on any floor and will be able to take it, however, the elevator takes one unit of time to bring Luis to any floor Ai , Luis should never leave the building at any moment using the elevators.

      When Luis gets to any floor, he will start seeking the gift from the position (0,0), after seeing all the room he will return to the elevator and keep his way. his searching ends when he finds all the gifts. Luis can ignore places that aren’t marked, so for example, if he knows that in a floor Fi there is no gifts, he can continue his way through the elevators. You can assume some things out of Luis’ skyscrapper building.

      • He lives on the first floor of the skyscrapper (floor 0, position 0,0).

      • Luis must be in each floor in the position (0,0) in order to use an elevator.

      • There will no gifts in his floor, because his parents try to hide it from him.

      • He will never leave the building at any moment using elevators

      • Every floor of the skyscrapper is perfectly the same one from another and can be represented as a NxN matrix

      • The elevators will be always available and can go up or down, never both. (You can assume that the elevators will be always moving).

      • The coordinates of the gift are uniques, that is, you can safely assume that no gift will overlap another one.

      • Luis can only walk in a floor from point (a,b) through point (c,d) going into vertical and horizontal directions, that is, for each unit of time, he can move north, east, west or south.

      • The transition of one elevator through another takes one unit of time, the time inside the elevator is immediate.

      Finally, knowing the number of floors, the number of elevators and their values, the number of gifts and the position of each gift, and then the size NxN of every floor in the apartment, determine the minimum time that Luis can delay checking all his gifts and returning to the point 0,0 on the last gift's floor after he sees the last one.

      It is guaranteed that a solution will always exist.

       

      Input

      The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.

      Four integers will begin every test case; M, E, K and N , denoting, respectively, the number of floors, the number of elevators, the number of gifts and the size for every floor in the skyscrapper.

      Then, E lines will follow, meaning that the i-th elevator goes ”up” Ei floors. (If the number is negative, then it goes down Ei floors.

      After that, K lines will follow, each one of them with three integers denoting that the i-th gift is on floor f at the position (r,c).

      The input must be read from standard input.

       

      Output

      For each input case you must print the string "Scenario #i: " where i represent the case you’re analyzing (starting from 1), followed by the minimum units of time that takes Luis to check all the gifts.

      The output must be written to standard output.

       

      Input

      Output for the sample input

      5

      5 1 1 1

      1

      3 0 0

      5 3 1 1

      1

      4

      -1

      3 0 0

      5 1 2 1

      1

      2 0 0

      4 0 0

      10 3 2 1

      1

      8

      -2

      4 0 0

      6 0 0

      5 3 3 5

      1

      2

      -1

      2 1 3

      2 4 1

      2 3 4

      Scenario #1: 3

      Scenario #2: 2

      Scenario #3: 4

      Scenario #4: 3

      Scenario #5: 17

      Explanation of the last case:

      Luis starts in floor 0, takes an elevator to floor 2, lets call the three gift on the second floor (A,B,C) with A={1,3}, B={4,1}, C={3,4}, he can pick the gifts in several ways; A,B,C; B,C,A; C,A,B; C,B,A; A,C,B; B,A,C; However, the minimal combination is B,A,C and return to the origin (0,0) that is 16 steps used plus the unit of time in the elevator, total = 17. 


      • 1 ≤ T ≤ 10

      Subtask 1 - 5%

      • 2 ≤ M ≤ 100

      • 1 ≤ E ≤ 1

      • 1 ≤ K ≤ 1

      • 1 ≤ N ≤ 1 You can assume that the gift will be at the origin point (0,0).

      Subtask 2 - 5%

      • 2 ≤ M ≤ 1,000

      • 1 ≤ E ≤ 10

      • 1 ≤ K ≤ 10

      • 1 ≤ N ≤ 1 You can assume that the gift will be at the origin point (0,0).

      Subtask 3 - 10%

      • 2 ≤ M ≤ 100

      • 1 ≤ E ≤ 10

      • 1 ≤ K ≤ 1

      • 2 ≤ N ≤ 100

      Subtask 4 - 10%

      • 2 ≤ M ≤ 1,000

      • 1 ≤ E ≤ 100

      • 1 ≤ K ≤ 1

      • 2 ≤ N ≤ 1,000

      Subtask 5 - 20%

      • 2 ≤ M ≤ 1,000

      • 1 ≤ E ≤ 20

      • 1 ≤ K ≤ 10

      • 2 ≤ N ≤ 100 It is guaranteed that all the gift will be on different floors.

      Subtask 6 - 20%

      • 1 ≤ M ≤ 1,000

      • 1 ≤ E ≤ 100

      • 1 ≤ K ≤ 10

      • 1 ≤ N ≤ 1,000

      Subtask 7 - 30%

      • 1 ≤ M ≤ 1,000

      • 1 ≤ E ≤ 100

      • 1 ≤ K ≤ 10

      • 1 ≤ N ≤ 1,000,000

       


      Added by:Venezuelan Programming League
      Date:2012-12-08
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for VPL0-Contest









      SPOJ Problem Set (classical)

      12959. Basic Grapes Instinct

      Problem code: VPL0_B

      Dickie is croping grapes for Christmas! He’s very excited about the traditional grape eating race on December 31th, so he picked every possible raceme of grape in his farm and collect them in a big bucket. Nevertheless, he’s having a serious problems ordering the racemes because there are so many of them!

      In order to organize in a efficient way the humongous amount of grape racemes, he decided to build a stemplot out of them. A stemplot goes as follows:

      • The input values for a stemplot are a sequence of numbers and a stem unit.

      • Data is classified based on the stem value, i.e., if a number in the sequence is 403 and the stem unit is 100, then this number is classified in the category 4.

      • For each category, a list of leaf values are render in a single line, sorted in increasing order.

      • Stem values and leafs are separated by a | (pipe character). All | should be vertically aligned.

      • Stem values are sorted in increasing order, omitting empty stems.

      Given the sequence s = { 44 46 47 49 63 64 66 68 68 72 72 75 76 81 84 88 106 }, the stemplot generated with a stem unit of 10 is rendered as follow:

       4 | 4 6 7 9

       6 | 3 4 6 8 8

       7 | 2 2 5 6

       8 | 1 4 8

      10 | 6

      Dickie is having big trouble rendering these stemplots of grape racemes, can you do the job for him and save the traditional grape race of December 31th?

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow the descriptions of T test cases.

      The first line of each case will contain 2 integers N and U , indicating the size of the sequence and the stem unit. Next N lines will contain a single element of the sequence si.

       

      The input must be read from standard input.

       

      Output

      For each case you should print the string "Scenario #i:" where i is the test case you are

      evaluating (starting from 1), a blank line, and then the corresponding stemplot following the

      rules stated above. Print a blank line after each stemplot.

       

      The output must be written to standard output.

       

      Input

      Output for the sample input

      2

      17 10

      44

      46

      47

      49

      63

      64

      66

      68

      68

      72

      72

      75

      76

      81

      84

      88

      106

      5 23

      1

      9

      127

      23

      73

      Scenario #1:

       4 | 4 6 7 9

       6 | 3 4 6 8 8

       7 | 2 2 5 6

       8 | 1 4 8

      10 | 6

       

      Scenario #2:

      0 | 1 9

      1 | 0

      3 | 4

      5 | 12

       

      Subtask 1 - 30%

      • 1 ≤ T ≤ 100

      • 1 ≤ N ≤ 100

      • 1 ≤ U ≤ 100

      • 1 ≤ si ≤ 1,000

      Subtask 2 - 70%

      • 1 ≤ T ≤ 100

      • 1 ≤ N ≤ 10,000

      • 1 ≤ U ≤ 1,000

      • 1 ≤ si ≤ 1,000 


      Added by:Venezuelan Programming League
      Date:2012-12-08
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for VPL0-Contest









      SPOJ Problem Set (classical)

      12960. Collision on Christmas Eve

      Problem code: VPL0_C

      Danny is preparing to receive his christmas gift, their parents said that it is a very awesome gift and Danny could not think on anything else than what is inside the box.

      Weeks ago, the parents of Danny gave him a homework that Danny didn’t complete because it was too boring for him, but suddenly, at December 25th, the parents are asking Danny to give the answer of his homework! Danny is falling into desperation and requires your help.

      Now, before giving the christmas gift, the parents asked Danny for the homework, and it goes like this: given two numbers N and K, find the number with the largest quantity of divisors following the progression: A0=1, A1=A0+K+1, A2=A1+K+2, and so on. The value of An should not exceed the number N given.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow the descriptions of T test cases. Each case contains only two numbers N and K, giving the maximum number to evaluate and the value of the progression’s constant.

       

      The input must be read from standard input.

       

      Output

      For each input case you must print the string "Scenario #i: " where i is the test case you’re analyzing (starting by 1), followed by the number who contains the largest quantity of divisors in it with the number of divisors associated, in case of a tie, choose the smaller.

       

      The output must be written to standard output.

       

      Input

      Output for sample input

      4

      4 0

      28 1

      2 2

      78 3

      Scenario #1: 4 3

      Scenario #2: 28 6

      Scenario #3: 1 1

      Scenario #4: 40 8

       

      Subtask 1 - 20%

      • 1 ≤ N ≤ 1,000

      • 10 ≤ K ≤ 100

      Subtask 2 - 30%

      • 1 ≤ N ≤ 100,000

      • 0 ≤ K ≤ 100

      Subtask 3 - 50%

      • 1 ≤ N ≤ 10,000,000

      • 0 ≤ K ≤ 100 


      Added by:Venezuelan Programming League
      Date:2012-12-08
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for VPL0-Contest









      SPOJ Problem Set (classical)

      12961. Drastic Grapes

      Problem code: VPL0_D


       It’s December 31st. New year’s Day. Lino and his family are waiting to eat grapes as part of one Venezuelan tradition to ask for wishes to become the New Year. Lino’s parents do it because of the tradition while his little sister Shouri gives a priority to each wish according to its importance, If she has a wish with P priority she must eat a grape with P power, however, the grapes are on the table and she is not tall enough to take them and she gives Lino a list of size N with her priorities. In addition, Lino has another list of size M given by his mother with a brief description of the grapes on the table. Grapes have different characteristics and Lino’s mission is to maximized Shouri’s wishes but with some restrictions:

      • Lino only takes grapes with the same priorities and power.

      • Lino can only take the i-th grape on the table if and only if the grapes taken before and the new one are in the same order in both lists, in other words, if there is on the list of priorities {5,4,1,3,2} and the grapes on the table are {7,1,5,4,9,3,2,1,2,0}, he can choose {4,2} or {4,3,2} but never {1,4} or {1,2,3,4}

      • if Lino can choose between grapes {1,2,3} and {4,5} he choose the ones with the maximum power {4,5}

      • if Lino encounters two groups of grapes with the same power, he will choose the biggest group, example, between {4,5} and {3,3,3} he will choose {3,3,3}.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow the descriptions of T test cases.

      Each line contains two integers K and N , denoting, respectively, the list of grapes that Shouri holds and the grapes that are on the table. After that, follows a line containing K integers with the description previously mentioned and another line with N integers with the description mentioned too.

      The input must be read from standard input.

       

      Output

      For each input case you must print the string "Scenario #i: " where i denotes the test case you are evaluating (starting by 1) followed by two numbers, each one denoting the maximum power achievable and the number of grapes to be taken. If there are no group that can satisfy Shouri’s needs, then print 0 0 as maximum power and maximum number of grapes.

      The output must be written to standard output.

       

       

       

       

      Input

      Output for sample input

      3

      3 3

      1 2 3

      3 2 1

      3 3

      2 4 5

      3 2 5

      5 7

      3 3 3 4 5

      4 5 3 8 3 12 3

      Scenario #1: 3 1

      Scenario #2: 7 2

      Scenario #3: 9 3

       

      Subtask 1 - 20%

      • 1 ≤ T ≤ 100

      • 1 ≤ K ≤ N

      • 1 ≤ N ≤ 15

      Subtask 2 - 30%

      • 1 ≤ T ≤ 100

      • 1 ≤ K ≤ N

      • 1 ≤ N ≤ 100

      Subtask 3 - 50%

      • 1 ≤ T ≤ 20

      • 1 ≤ K ≤ N

      • 1 ≤ N ≤ 1000 


      Added by:Venezuelan Programming League
      Date:2012-12-08
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for VPL0-Contest









      SPOJ Problem Set (classical)

      12969. To inifinity and Beyond

      Problem code: BUZZ

      You probably don't know toys walk, play and talk when we are not around. And there are toys who can perform intergalactic missions! But lets forget about alien planets now, the toy-land on earth is in danger, “Zurg” the evil emperor from outer world is planning to capture it. But as always when toyland is in trouble the great space ranger “Buzz Lightyear” of star command comes for the rescue!

       

      Buzz

      Toyland consists of several cities and bidirectional roads. The Toyland chief wants to take following steps to save Toyland:

      1. First divide the cities of Toyland into multiple regions. Two cities MUST be included in same region if there is at least one cyclic route connecting both cities. One city can be included in multiple regions. Size of each region should be maximal, that means extra city can't be added in a region.
      2. There are limited number of “Buzz” toys available. After creating the regions, one “Buzz” toy will be sent to each of them to save that region from Zurg!

      Toys need energy. Each city can supply energy to infinite number of toys but the amount of energy a city provides daily to a single toy is limited otherwise toys may waste energy. A toy is assigned to a single region but it can get energy from any city with in its region.

      For a single toy, the total daily energy supply is sum of the energy supply of all the cities within its region.

      Each “Buzz” may need different amount of energy to work. If a region provides too less energy than additional energy need to be provided anyhow and it is considered as a lose. But if the region provides more energy than required, “Buzz” wastes it by playing with laser and flying all around. So:

      Daily Lose in region X =

      | Daily Energy required by “Buzz” assigned in that region - Daily Energy supplied by region X |

      Exactly one “Buzz” must be assigned in each region, if there are more toy than needed, they'll keep them for emergency. The chief wants to minimize the maximum wastage among all the regions and he needs your help desperately.

      Help the toyland to survive, expand your mind To Infinity and Beyond and find the answer.

      Input Specification:

      Input consists of several files. First line of each file will consist the number of test cases(T<=101). For each case, first line will consists number of cities (1<=N<=251) , roads(E>=0) and number of Buzz toys available(1<=B<=251). In next line there are N integers less than 1000, i-th integer denotes energy supply in city i. In next line there are B integers less than 1000, j th integer denotes energy required by Buzz j. Next there are E lines each consisting two integer u and v denoting there is a bidirectional road between u and v(u!=v). There are at most one roads between two cities. All inputs are non-negative.

      Output Specification:

      First print number of regions. Than if number of regions is more than number of buzz available, output “No”. Otherwise print the maximum wastage amount among all the regions. Dont print any extra spaces or newlines. Print case number for every case, see sample output for details.

      Large input File, use faster I/O.

      Sample input:

      2

      6 7 3

      5 4 8 1 2 6

      10 14 9

      1 2

      2 3

      3 1

      3 4

      4 5

      3 5

      5 6

      4 3 1

      5 4 8 1

      10

      1 2

      2 3

      3 1

      Sample Output:

      Buzz Mission 1: 3 3

      Buzz Mission 2: 2 No

      Case 1 Explanation


      Added by:Shafaet
      Date:2012-12-11
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem (9th IIUC Inter-University Programming Contest, Bangladesh)









      SPOJ Problem Set (classical)

      12978. SHAPE GAME

      Problem code: SGAME

      You probably might have played the game of constructing a figure without lifting up the pencil.But it seems too easy for us.
      Let's add some twist to it!
      What about start constructing a figure from a point and returning to the same point resulting in the figure without lifting up the pencil.

      Note: Figure is bounded and one can't retrace an arc or line.

       

      INPUT SPECIFICATION

      Input consists of several test data.There are 't' test cases. For each case you are given the point index 'n' from which to start and end.Then follows two space separated index that define a line from index 'i' to index 'j'.These integers follow up until "-1 -1" is encountered.

       

      OUTPUT SPECIFICATION

      Output "YES", if it's possible to construct figure satisfying the specification and "NO" if it's not possible (without quotes).

       

      CONSTRAINTS

      t<=100
      1<=n<=300
      1<=i,j<=300
      i!=j

       

      EXAMPLE

      Sample Input:
      
      1
      1
      1 2
      1 4
      2 3
      2 5
      2 6
      3 6
      4 7
      5 6
      6 7
      -1 -1
      
      Sample Output:
      
      YES
      

      Added by:Swapnil R.Mehta
      Date:2012-12-12
      Time limit:0.300s-0.310s
      Source limit:3000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3
      Resource:Own Problem









      SPOJ Problem Set (classical)

      12981. Fences

      Problem code: CEOI08A


      One morning, fruit farmer Fred visits his apple trees and notices that one of them was cut overnight. This means a loss of 111e – the money he can make from the apples of a tree on average. In order to prevent further losses, he decides to erect a fence on his plantation.
      The fence consists of posts connected by wire.

      The fence posts can only be placed at a given set of pre-drilled holes. While Fred can get wire for free, he needs to buy the fence posts for 20e each. So it might not always be worth or even possible to fence in all of his trees.

       

      fences

      The plantation is square and 1 000 × 1 000 m2 large. In bird’s eye view, the lower left corner has
      coordinates (0, 0), the upper right (1 000, 1 000). In this example there are four pre-drilled holes (circles) and three trees (squares). It is optimal to buy three fence posts and put them into selected holes (filled circles), to connect them by wire (lines), and to leave the upper left hole empty. The cost of erecting the fence is 3 · 20e + 1 · 111e = 171e since three posts were bought and one tree could not be fenced in (which means a loss of that tree’s harvest).


      Write a program that reads the positions of the pre-drilled holes and the trees on Fred’s plan-tation and outputs the minimum cost of erecting a fence or erecting no fence at all. You can neglect the actual shape of the trees and calculate with their positions only.

      Input

      The first line contains two integers N and M (3 ≤ N ≤ 100, 1 ≤ M ≤ 100). N is the number of pre-drilled holes, and M is the number of trees. This line is followed by N lines that describe the positions of the holes, and then by M lines that describe the positions of the trees. Allpositions are given as pairs of integers x y on one line (0 ≤ x, y ≤ 1 000). You can expect thatno two positions (of holes and trees) coincide and that no three positions are colinear.


      Output
      Output a single line containing one integer: Fred’s minimum cost. In case Fred buys P posts
      and fails to fence in T trees, his cost are 20P + 111T .

       

      Sample Input

      4 3
      800 300
      200 200
      200 700
      600 700
      400 300
      600 500
      800 900

      Output:

      171

      This example corresponds to the picture above.

      (Official Test Data)

       


      Added by:Shafaet
      Date:2012-12-13
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:15th Central Europe Olympiad in Informatics, Germany









      SPOJ Problem Set (classical)

      13002. For Loops Challenge

      Problem code: PFORLOOP

      Bjarne is learning about programming. Yesterday’s lesson was about for loops. To put his skills into practice, he had to write a number of for loops that printed consecutive positive integers. He was so proud of his creation that he stored the output of his program into a file. For example, the contents of the file could have looked like this:


      5 6 7 8 9 10 11 12 13 14
      56 57 58 59 60 61 62 63 64 65
      100 101 102 103 104 105 106


      Today, he opened his file and realized it is now inconsistent: the numbers weren’t sorted in ascending order anymore! His wife told him she was bored so she swapped some numbers around. He’s so frustrated he can’t rewrite the program.

       

      Your task is to help him out. Read out the numbers and print all the C++ for loops that recreate the original file.


      Input

      There are many lines in the input. The i-th line contains a sequence of space-separated positive integers, where each integer is between 0 and 1000000000. It is guaranteed there are no repeated integers and that there will be at minimum one line with one integer, no line will have more than 1000 integers.


      Output

      Output all the for loops that generate Bjarne’s original file, one per line. Print the for loops in  order. That is, if the numbers of the i-th loop are less than the numbers of the j-th loop, the i-th for loop must be printed first.

       

      Notes:

       

      • Name ‘i’ the variable of each for loop.

      • Don’t use brackets.

      • The for loop condition must be inclusive, that is, use ‘<=’.


      • The increment section of the for loop must be "i++".
      • The C++ code you print need not include a line ending command.

      • Beware of spaces. All your for loops must contain the same number of spaces as this sample:

      for (int i = a; i <= b; i++) cout << i << “;





      Example

      Input
      9 6 100 1 3 105
      2 4 101 102 103 104 5 7 8
      Output
      for (int i = 1; i <= 9; i++) cout << i << “ “;
      for (int i = 100; i <= 105; i++) cout << i << “ “;

       

       


      Added by:kojak_
      Date:2012-12-15
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:OPPAI Practice Problems









      SPOJ Problem Set (classical)

      13007. Easy Programming Tutorials

      Problem code: EPTT


       

      The ACM-ICPC movement has become very strong in the Dominican Republic and many students are now looking for specialized programming classes to tackle their specific needs. You work at a top school that has produced many world-class programmers. These programmers have a lot of time to spare and would like to tutor as many students as possible so as to continue producing more world-class programmers. Nonetheless, you have a very limited budget and thus want to minimize costs. 
      Every day you receive a number of requests from students where each request Ri has a start time Si. Each tutorial lesson lasts exactly 30 minutes. Luckily, you always have more tutors than requests. On any day, however, tutors are constrained to work only one stretch of at most two hours and each can only service one request at a time. For example, if there is a request coming in at time 0 and another one coming in at time 31, you would need two tutors to service both. If instead the second one comes at time 30, you would then need only one tutor.
      Given a list of requests for a day, compute the minimum number of tutors necessary to serve them all.
      Input
      The first line contains a single integer R (1 <= R <= 1,000,000), the number of requests for the day. Then there are R lines. Each line contains the i-th request. Each request is represented by its integer start time in the range [0, 1410]. Thus the input has in total 1 + R lines.
      Output
      The output is a single integer representing the minimum number of tutors needed to serve all requests for the day.
      Sample Input:
      5
      0
      0
      30
      60
      61
      Sample Output:
      3

       

      The ACM-ICPC movement has become very strong in the Dominican Republic and many students are now looking for specialized programming classes to tackle their specific needs. You work at a top school that has produced many world-class programmers. These programmers have a lot of time to spare and would like to tutor as many students as possible so as to continue producing more world-class programmers. Nonetheless, you have a very limited budget and thus want to minimize costs. 

       

      Every day you receive a number of requests from students where each request Ri has a start time Si. Each tutorial lesson lasts exactly 30 minutes. Luckily, you always have more tutors than requests. On any day, however, tutors are constrained to work only one stretch of at most two hours and each can only service one request at a time. For example, if there is a request coming in at time 0 and another one coming in at time 31, you would need two tutors to service both. If instead the second one comes at time 30, you would then need only one tutor.

       

      Given a list of requests for a day, compute the minimum number of tutors necessary to serve them all.

       

      Input

       

      The first line contains a single integer R (1 <= R <= 1,000,000), the number of requests for the day. Then there are R lines. Each line contains the i-th request. Each request is represented by its integer start time in the range [0, 1410]. Thus the input has in total 1 + R lines.

       

      Output

       

      The output is a single integer representing the minimum number of tutors needed to serve all requests for the day.

       

      Sample Input:

      5

      0

      0

      30

      60

      61

      Sample Output:

      3

       

       


      Added by:kojak_
      Date:2012-12-15
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:OPPAI Practice Problems









      SPOJ Problem Set (classical)

      13015. Counting Primes

      Problem code: CNTPRIME


      Tortoise and Achilles are playing the Counting the Primes game. Achilles will give Tortoise some numbers, and some intervals, and then Tortoise needs to count the primes on those intervals. It is an easy game, but Tortoise is doing the counting slowly. Achilles is pissed off, so he has given you the task as you are a good programmer. For a twist, he has changed the game a little bit, that is he will give some intervals for counting the prime as well as he will give some intervals to change the numbers in that interval.

      You are given an array of n elements. After that you will be given M commands. They are -

      • 0 x y v - you have to change all numbers in the range of x to y (inclusive) to v, where x and y are two indexes of the array.
      • 1 x y - output a line containing a single integer which is the number of primes between x and y (inclusive).

      The array is indexed from 1 to n.

      Input:

      Input starts with an integer T (≤ 10), denoting the number of test cases.

      Each case contains two integers n (1 ≤ n ≤ 104) and q (1 ≤ q ≤ 2*104). Then next line, you will be given N integers. After that each of the next q lines will contain a task in one of the following form:

      • 0 x y v (1 ≤ x ≤ y ≤ n, 2 ≤ v ≤ 106)
      • 1 x y (1 ≤ x ≤ y ≤ n)

      And the numbers will be in range of [2, 106].

      Output:

      For each case, print the case number first. Then for each query '1 x y', print the number of primes between x and y [inclusively].

      Sample Input

      Output for Sample Input

      1

      5 3

      78 2 13 12 3

      1 1 2

      0 4 4 5

      1 1 5

      Case 1:

      1

      4



      Note:

      • Use Faster IO like scanf,printf
      • A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first prime numbers are 2,3,5,7,11....2,3,5,7,11,

       


      Added by:Ahmad Faiyaz
      Date:2012-12-16
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      13020. Help MR BEAN

      Problem code: BEANGAME


      Mr. Bean loves to play games. For this he wastes lots of money so Mrs.Bean made a hurdle game for him. Now in the game we have 3 tracks and for moving up to next level he will have to cross some hurdles.Each time he changes the track he gets some drink to increase his energy level by that amount.The drink that he gets is the one which is in between the present track and the adjacent track and in the direction of movement (adjacent track may or may not be the track on which he is targetting to move).Now if at any moment his energy becomes negative his game will be over. So you have make him win this game with maximum energy being available with him at last. He will move in the form of 'L' and 'R' between adjacent tracks with 'L' making him move one step left of the present position and 'R' moving him right. Movement between different level will be seperated by '-' and if their is no change of track between adjacent levels then print 'U' at its corresponding move .

      Image and video hosting by TinyPic

      Input

      First line will have 3 integers Il,Ie,Ns where Il is the initial track on which he is standing, Ie is the initial
      energy he is having and Ns is the number of levels in the game.
      Then it would be followed by 5 lines where the first three will have the values of the hurdles present at each level
      on each track.Fourth line will have Ns-1 integers representing the energy obtained by him on drinking the energy
      drink between continuous levels between track 1 and 2 and similarly fifth line will have Ns-1 values for drinks between
      tracks 2 and 3.

      Output

      Print "DONE IT!" in first line and the steps taken by him in second line following the path which leads to maximum energy available with Mr.Bean beyond final track.
      If it is not possible print "GAME OVER!".

       

      CONSTRAINTS

      Every integer , intermediate values will fit in 32-bit integer.

      Example

      Input:
      1 6 5
      3 2 9 16 3
      4 0 7 26 1
      1 7 3 30 9
      8 19 8 3
      10 3 6 4 Output: DONE IT!
      RR-LL-RR-LL-R

      Added by:Mrs. Bean
      Date:2012-12-17
      Time limit:0.009s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      13031. Vision Field

      Problem code: VISION


      Description

      There are N buildings stand along the horizon line. Each building are been represented as a vertical segment with two end points at (i, 0) and (i, Ai). There are M queries in total. For each query, we wonder know how many buildings you can see if you stand at (0, h).

      .. N, M ≤ 10^6, both Ai && h is positive interger and ≤ 10^9 .. .

      Input

      n
      A1 A2 ... An
      m ... (here following the m query.)

      Output

      ... (for each query, simply print how many buildings you can see. )

      Example

      Input:
      5
      2 3 3 3 4
      3
      3
      2
      4
      Output:
      3
      2
      5

      Added by:xiaodao
      Date:2012-12-20
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      13041. The Black Riders

      Problem code: AMR12A

       

      'Hush!' said Frodo. 'I think I hear hoofs again.'
      They stopped suddenly and stood as silent as tree-shadows, listening. There was a sound of hoofs in the lane, some way behind, but coming slow and clear down the wind. Quickly and quietly they slipped off the path, and ran into the deeper shade under the oak-trees.
      The hoofs drew nearer. They had no time to find any hiding-place better than the general darkness under the trees. 
      - Frodo, Sam and Pippin, when they encounter a Black Rider.
      Indeed, the Black Riders are in the Shire, and they are looking for the One Ring. There are N hobbits out in their fields, but when they hear the Riders approaching, or feel the fear cast by their presence, they immediately wish to run and hide in M holes located nearby.
      Now, each hole has space for just 1 hobbit; however, once a hobbit reaches a hole, he is able to make room for one more hobbit by digging away at the earth. The time required to make enough space for a second hobbit is C units. Also, each hole CANNOT hold more than 2 hobbits, even after digging. Also note that a hobbit can begin making space for the next hobbit only after he reaches the hole.
      You are given the time required to travel from each hobbit's current location to each hole. Find the minimum amount of time it will take before at least K of the hobbits are hiding safely.
      Input (STDIN):
      The first line contains T, the number of test cases.
      The first line of each test case contains 4 integers - N (no of hobbits), M (no of holes), K (minimum number of hobbits to hide) and C (time taken to expand a hole).
      The next N lines contain M integers each, denoting the time taken for each hobbit to each hole.
      Output (STDOUT):
      Output one line per test case which contains the minimum time. 
      Constraints:
      1 <= T <= 6
      1 <= N, M <= 100
      1 <= K <= min(N, 2 * M)
      0 < C < 10,000,000
      0 < Time taken by the hobbits to the holes < 10,000,000
      Time Limit: 2s
      Memory Limit: 64MB
      Sample Input:
      2
      3 3 2 10
      9 11 13
      2 10 14
      12 15 12
      4 3 3 8
      1 10 100
      1 10 100
      100 100 6
      12 10 10
      Sample Output:
      10
      9
      Notes/Explanation of Sample Input:
      For the first test case, there are 3 hobbits and 3 holes, and we need to get atleast 2 of them to safety. We can send the first hobbit to the first hole, and the second hobbit to the second hole, thereby taking 10 time units.
      For the second test case, we can make hobbit #1 reach hole 1 at time 1, hobbit #2 reach hole 1 at time 9 (by when hobbit #1 would have finished digging the hole), and hobbit #3 reach hole 3 at time 6.

      'Hush!' said Frodo. 'I think I hear hoofs again.'

      They stopped suddenly and stood as silent as tree-shadows, listening. There was a sound of hoofs in the lane, some way behind, but coming slow and clear down the wind. Quickly and quietly they slipped off the path, and ran into the deeper shade under the oak-trees.

      The hoofs drew nearer. They had no time to find any hiding-place better than the general darkness under the trees. 

      - Frodo, Sam and Pippin, when they encounter a Black Rider.

       

      Indeed, the Black Riders are in the Shire, and they are looking for the One Ring. There are N hobbits out in their fields, but when they hear the Riders approaching, or feel the fear cast by their presence, they immediately wish to run and hide in M holes located nearby.

       

      Now, each hole has space for just 1 hobbit; however, once a hobbit reaches a hole, he is able to make room for one more hobbit by digging away at the earth. The time required to make enough space for a second hobbit is C units. Also, each hole CANNOT hold more than 2 hobbits, even after digging. Also note that a hobbit can begin making space for the next hobbit only after he reaches the hole.

       

      You are given the time required to travel from each hobbit's current location to each hole. Find the minimum amount of time it will take before at least K of the hobbits are hiding safely.

       

      Input (STDIN):

       

      The first line contains T, the number of test cases.

      The first line of each test case contains 4 integers - N (no of hobbits), M (no of holes), K (minimum number of hobbits to hide) and C (time taken to expand a hole).

      The next N lines contain M integers each, denoting the time taken for each hobbit to each hole.

       

      Output (STDOUT):

       

      Output one line per test case which contains the minimum time. 

       

      Constraints:

      1 <= T <= 6

      1 <= N, M <= 100

      1 <= K <= min(N, 2 * M)

      0 < C < 10,000,000

      0 < Time taken by the hobbits to the holes < 10,000,000

       

      Sample Input:

      2

      3 3 2 10

      9 11 13

      2 10 14

      12 15 12

      4 3 3 8

      1 10 100

      1 10 100

      100 100 6

      12 10 10

       

      Sample Output:

      10

      9

       

      Notes/Explanation of Sample Input:

      For the first test case, there are 3 hobbits and 3 holes, and we need to get atleast 2 of them to safety. We can send the first hobbit to the first hole, and the second hobbit to the second hole, thereby taking 10 time units.

      For the second test case, we can make hobbit #1 reach hole 1 at time 1, hobbit #2 reach hole 1 at time 9 (by when hobbit #1 would have finished digging the hole), and hobbit #3 reach hole 3 at time 6.

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Utkarsh Lath - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13042. Gandalf vs the Balrog

      Problem code: AMR12B

       

      'We fought far under the living earth, where time is not counted. Ever he clutched me, and ever I hewed him, till at last he fled into dark tunnels. Ever up now we went, until we came to the Endless Stair. Out he sprang, and even as I came behind, he burst into new flame. Those that looked up from afar thought that the mountain was crowned with storm. Thunder they heard, and lightning, they said, smote upon Celebdil, and leaped back broken into tongues of fire.' - Gandalf, describing his fight against the Balrog.
      Although Gandalf would not go into the details of his battle, they can be summarized into the following simplified form: both Gandalf and the Balrog have a set of N attacks they can use (spells, swords, brute-force strength etc.). These attacks are numbered from 1 to N in increasing order of Power. When each has chosen an attack, in general, the one with the higher power wins. However, there are a few ("M") anomalous pairs of attacks, in which the lesser-powered attack wins.
      Initially, Gandalf picks an attack. Then the Balrog counters it with one of the remaining attacks. If the Balrog's counter does not defeat Gandalf's, then we say Gandalf receives a score of 2. If however it does, then Gandalf has exactly one more opportunity to pick an attack that will defeat the Balrog's. If he manages to defeat him now, his score will be 1, whereas if he is still unable to defeat him, his score will be 0.
      Your task is to determine, given N and the M anomalous pairs of attacks, what will be Gandalf's score, given that both play optimally. Further, in case Gandalf gets a score of 2, you must also determine which attack he could have chosen as his first choice.
      Note 1: The Balrog can choose only one attack, whereas Gandalf can choose upto two.
      Note 2: The relation A defeats B is not transitive within the attacks. For example, attack A can defeat attack B, attack B can defeat attack C, and attack C can defeat attack A.
      Note 3: Between any two attacks A and B, either attack A defeats attack B or attack B defeats attack A.
      Input (STDIN):
      The first line will consist of the integer T, the number of test-cases.
      Each test case begins with a single line containing two integers N and M.
      This is followed by M lines consisting of 2 integers each x and y, denoting that x and y are an anomalous pair.
      Output (STDOUT):
      For each test-case, output a single line either
      2 A, if Gandalf can defeat any attack the Balrog chooses if he picks attack A,
      1, if Gandalf can choose an attack such that even if the Balrog chooses an attack to defeat him, he can choose an attack to defeat the Balrog's chosen card,
      0, if none of the above two options are possible for all possible choices of Gandalf's attack(s).
      Between successive test cases, there should not be any blank lines in the output.
      Constraints:
      1 <= T <= 15
      3 <= N <= 1,000,000
      0 <= M <= min(N(N-1)/2, 300,000)
      1 <= x < y <= N for all the anomalous pairs (x,y)
      The sum of M over all test-cases will not exceed 300,000.
      Time Limit: 4s
      Memory Limit: 64MB
      Sample Input:
      2
      3 0
      3 1
      1 3 
      Sample Output:
      2 3
      1
      Notes/Explanation of Sample Input:
      In the first case, attack 3 can beat both attacks 1 and 2. So Gandalf just chooses attack 3.
      In the second case, attack 1 beats 3 which beats 2 which beats 1. No matter which attack Gandalf chooses, the Balrog can pick the one which defeats his, but then he can pick the remaining attack and defeat the Balrog's.

      'We fought far under the living earth, where time is not counted. Ever he clutched me, and ever I hewed him, till at last he fled into dark tunnels. Ever up now we went, until we came to the Endless Stair. Out he sprang, and even as I came behind, he burst into new flame. Those that looked up from afar thought that the mountain was crowned with storm. Thunder they heard, and lightning, they said, smote upon Celebdil, and leaped back broken into tongues of fire.' - Gandalf, describing his fight against the Balrog.

       

      Although Gandalf would not go into the details of his battle, they can be summarized into the following simplified form: both Gandalf and the Balrog have a set of N attacks they can use (spells, swords, brute-force strength etc.). These attacks are numbered from 1 to N in increasing order of Power. When each has chosen an attack, in general, the one with the higher power wins. However, there are a few ("M") anomalous pairs of attacks, in which the lesser-powered attack wins.

       

      Initially, Gandalf picks an attack. Then the Balrog counters it with one of the remaining attacks. If the Balrog's counter does not defeat Gandalf's, then we say Gandalf receives a score of 2. If however it does, then Gandalf has exactly one more opportunity to pick an attack that will defeat the Balrog's. If he manages to defeat him now, his score will be 1, whereas if he is still unable to defeat him, his score will be 0.

       

      Your task is to determine, given N and the M anomalous pairs of attacks, what will be Gandalf's score, given that both play optimally. Further, in case Gandalf gets a score of 2, you must also determine which attack he could have chosen as his first choice.

       

      Note 1: The Balrog can choose only one attack, whereas Gandalf can choose upto two.

      Note 2: The relation A defeats B is not transitive within the attacks. For example, attack A can defeat attack B, attack B can defeat attack C, and attack C can defeat attack A.

      Note 3: Between any two attacks A and B, either attack A defeats attack B or attack B defeats attack A.

       

      Input (STDIN):

      The first line will consist of the integer T, the number of test-cases.

      Each test case begins with a single line containing two integers N and M.

      This is followed by M lines consisting of 2 integers each x and y, denoting that x and y are an anomalous pair.

       

      Output (STDOUT):

      For each test-case, output a single line either

      2 A, if Gandalf can defeat any attack the Balrog chooses if he picks attack A,

      1, if Gandalf can choose an attack such that even if the Balrog chooses an attack to defeat him, he can choose an attack to defeat the Balrog's chosen card,

      0, if none of the above two options are possible for all possible choices of Gandalf's attack(s).

      Between successive test cases, there should not be any blank lines in the output.

       

      Constraints:

      1 <= T <= 15

      3 <= N <= 1,000,000

      0 <= M <= min(N(N-1)/2, 300,000)

      1 <= x < y <= N for all the anomalous pairs (x,y)

      The sum of M over all test-cases will not exceed 300,000.

       

      Sample Input:

      2

      3 0

      3 1

      1 3 

       

      Sample Output:

      2 3

      1

       

      Notes/Explanation of Sample Input:

      In the first case, attack 3 can beat both attacks 1 and 2. So Gandalf just chooses attack 3.

      In the second case, attack 1 beats 3 which beats 2 which beats 1. No matter which attack Gandalf chooses, the Balrog can pick the one which defeats his, but then he can pick the remaining attack and defeat the Balrog's.

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Pradeep George Mathias - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13043. The Mirror of Galadriel

      Problem code: AMR12D

       

      With water from the stream Galadriel filled the basin to the brim, and breathed on it, and when the water was still again she spoke. 'Here is the Mirror of Galadriel,' she said. 'I have brought you here so that you may look in it, if you will. For this is what your folk would call magic, I believe; though I do not understand clearly what they mean; and they seem also to use the same word of the deceits of the Enemy. But this, if you will, is the magic of Galadriel. Did you not say that you wished to see Elf-magic?' - Galadriel to Frodo and Sam, describing her Mirror.
      We call a string S magical if every substring of S appears in Galadriel's Mirror (under lateral inversion). In other words, a magical string is a string where every substring has its reverse in the string.
      Given a string S, determine if it is magical or not.
      Input (STDIN):
      The first line contains T, the number of test cases. The next T lines contain a string each. 
      Output (STDOUT):
      For each test case, output "YES" if the string is magical, and "NO" otherwise.
      Constraints:
      1 <= T <= 100
      1 <= |S| <= 10
      S contains only lower-case characters.
      Time Limit: 1s
      Memory Limit: 64MB
      Sample Input:
      2
      aba
      ab
      Sample Output:
      YES
      NO
      Notes/Explanation of Sample Input:
      For the first test case, the list of substrings are : a, b, ab, ba, aba. The reverse of each of these strings is present as a substring of S too.
      For the second test case, the list of substring are : a, b, ab. The reverse of "ab", which is "ba" is not present as a substring of the string.

       

      With water from the stream Galadriel filled the basin to the brim, and breathed on it, and when the water was still again she spoke. 'Here is the Mirror of Galadriel,' she said. 'I have brought you here so that you may look in it, if you will. For this is what your folk would call magic, I believe; though I do not understand clearly what they mean; and they seem also to use the same word of the deceits of the Enemy. But this, if you will, is the magic of Galadriel. Did you not say that you wished to see Elf-magic?' - Galadriel to Frodo and Sam, describing her Mirror.

      We call a string S magical if every substring of S appears in Galadriel's Mirror (under lateral inversion). In other words, a magical string is a string where every substring has its reverse in the string.

      Given a string S, determine if it is magical or not.

       

      Input (STDIN):

      The first line contains T, the number of test cases. The next T lines contain a string each. 

       

      Output (STDOUT):

      For each test case, output "YES" if the string is magical, and "NO" otherwise.

       

      Constraints:

      1 <= T <= 100

      1 <= |S| <= 10

      S contains only lower-case characters.

       

      Sample Input:

      2

      aba

      ab

       

      Sample Output:

      YES

      NO

       

      Notes/Explanation of Sample Input:

      For the first test case, the list of substrings are : a, b, ab, ba, aba. The reverse of each of these strings is present as a substring of S too.

      For the second test case, the list of substring are : a, b, ab. The reverse of "ab", which is "ba" is not present as a substring of the string.

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Varun Jalan - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13044. Dyslexic Gollum

      Problem code: AMR12E

       

      'Light, light of Sun and Moon, he still feared and hated, and he always will, I think; but he was cunning. He found he could hide from daylight and moonshine, and make his way swiftly and softly by dead of night with his pale cold eyes, and catch small frightened or unwary things. He grew stronger and bolder with new food and new air. He found his way into Mirkwood, as one would expect.' - Gandalf, describing Gollum after he ventured forth from Moria.
      Gollum has spent half a millennium in the long darkness of Moria, where his eyes grew used to the dark, and without caring for reading or writing, he became dyslexic. Indeed, as much as he hates the Moon and the Sun, he also hates strings with long palindromes in them.
      Gollum has a tolerance level of K, which means that he can read a word so long as it does not contain any palindromic substring of length K or more. Given the values N and K, return how many BINARY strings of length N can Gollum tolerate reading.
      Input (STDIN):
      The first line contains T, the number of test cases.
      Each test case consists of one line containing 2 integers, N and K.
      Output (STDOUT):
      For each test case, output the answer modulo 1,000,000,007.
      Constraints:
      1 <= T <= 100
      1 <= N <= 400
      1 <= K <= 10
      Sample Input:
      3
      2 2
      3 3
      3 4
      Sample Output:
      2
      4
      8
      Notes/Explanation of Sample Input:
      For the first test case, 01 and 10 are the valid binary strings, while 00 and 11 are invalid.
      For the second test case, 001, 011, 100, 110 are the valid binary strings.
      For the third test case, all possible binary strings of length 3 are valid.

       

      'Light, light of Sun and Moon, he still feared and hated, and he always will, I think; but he was cunning. He found he could hide from daylight and moonshine, and make his way swiftly and softly by dead of night with his pale cold eyes, and catch small frightened or unwary things. He grew stronger and bolder with new food and new air. He found his way into Mirkwood, as one would expect.' - Gandalf, describing Gollum after he ventured forth from Moria.

       

      Gollum has spent half a millennium in the long darkness of Moria, where his eyes grew used to the dark, and without caring for reading or writing, he became dyslexic. Indeed, as much as he hates the Moon and the Sun, he also hates strings with long palindromes in them.

       

      Gollum has a tolerance level of K, which means that he can read a word so long as it does not contain any palindromic substring of length K or more. Given the values N and K, return how many BINARY strings of length N can Gollum tolerate reading.

       

      Input (STDIN):

      The first line contains T, the number of test cases.

      Each test case consists of one line containing 2 integers, N and K.

       

      Output (STDOUT):

      For each test case, output the answer modulo 1,000,000,007.

       

      Constraints:

      1 <= T <= 100

      1 <= N <= 400

      1 <= K <= 10

       

      Sample Input:

      3

      2 2

      3 3

      3 4

       

      Sample Output:

      2

      4

      8

       

      Notes/Explanation of Sample Input:

      For the first test case, 01 and 10 are the valid binary strings, while 00 and 11 are invalid.

      For the second test case, 001, 011, 100, 110 are the valid binary strings.

      For the third test case, all possible binary strings of length 3 are valid.

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Varun Jalan - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13045. Denethors Decryption of Dequeue permutations

      Problem code: AMR12F


       

      'Though the Stewards deemed that it was a secret kept only by themselves, long ago I guessed that here in the White Tower, one at least of the Seven Seeing Stones was preserved. In the days of his wisdom Denethor did not presume to use it, nor to challenge Sauron, knowing the limits of his own strength. But his wisdom failed; and I fear that as the peril of his realm grew he looked in the Stone and was deceived: far too often, I guess, since Boromir departed. He was too great to be subdued to the will of the Dark Power, he saw nonetheless only those things which that Power permitted him to see.' - Gandalf.
      Sauron and Saruman have been communicating from large distances using the Seeing Stones. Denethor, with great difficulty has been able to break into their channel of communication using his strength of will. Despite this however, it seems that their communication has been encrypted. Gondor's spies in Isengard have found out the encryption algorithm they use and have reported back to Denethor.
      The algorithm is as follows :
      We refer to a dequeue as a double-ended queue. We define a "dequeue permutation of N" as a permutation of 1 to N that can be got by starting from a dequeue having elements 1, 2, 3, ..., N (in that order with 1 at the front and N at the back) and performing any sequence of N pop_front() or pop_back() operations. 
      Note that not all permutations of 1 to N are dequeue permutations. For example, with N = 3, you have 3-1-2, 1-3-2 etc. as dequeue permutations whereas 2-1-3, 2-3-1 aren't (you can't have 2 right at the beginning since its not at any end of the dequeue).
      If Sauron wants to encrypt the number K and send it to Saruman, he would instead send the K'th lexicographically smallest (0-based indexed) dequeue permutation of N. That is, if Sauron wanted to send '0' to Saruman, he would just send 1-2-3-...-N (since this is clearly the smallest lexicographic dequeue permutation of N).
      Sauron is transmitting the size of his army to Saruman, so that they can coordinate an attack on the Men of Rohan and Gondor. Since Sauron's will is so powerful, Denethor is able to get only vague glimpses of the numbers, and he is able to remember only the first half (floor(N/2) elements) of the permutation. Further, since these images are so vague, his understanding of the numbers happens out of order. For example, Denethor may understand that the 5th number of the permutation is 4, and later on only understand that the 3rd number was 3. 
      Help him estimate the minimum and maximum possible size of Sauron's army (value of K), given the number N, and incremental understanding of the first half of the permutation, not necessarily in order.
      NOTE 1: Since the values to be output can be rather large, output the values modulo 1,000,000,007.
      NOTE 2: It may be the case that Denethor's understanding of the permutation is flawed. If it is not possible to have a dequeue permutation satisfying all the conditions seen so far, output -1.
      NOTE 3: A permutation p1 is lexicographically smaller than p2 if at the first position where they differ, p1's value is smaller than p2's.
      Input (STDIN):
      The first line consists of the integer T, the number of test cases.
      Each test case begins with a single integer N.
      This is followed by exactly floor(N/2) lines containing 2 integers each: i and j, denoting that Denethor has understood that the i'th element (1-based) of the supposed permutation is j.
      Output (STDOUT):
      For each testcase, output exactly floor(N/2) lines, one for each (i,j) pair. If the recollections till now cannot all be feasible, output '-1' on a line. Else output two space-separated integers: the minimum and the maximum possible value of Sauron's army, K, that are consistent with all the observations seen so far.
      Between successive test cases, there should not be any blank lines in the output.
      Constraints:
      1 <= T < 3 
      2 <= N <= 100,000
      1 <= i <= floor(N/2)
      1 <= j <= N
      All (i, j) pairs are distinct. And for two pairs (i1, j1) and (i2, j2), you have that i1 != i2 and j1 != j2.
      Sample Input:
      2
      3
      1 3
      32
      1 1
      3 2
      2 32
      4 4
      5 5
      6 6
      7 7
      8 8
      9 9
      10 10
      11 11
      12 12
      13 13
      14 14
      15 15
      16 3
      Sample Output:
      2 3
      0 73741816
      536870912 805306367
      536870912 805306367
      -1
      -1
      -1
      -1
      -1
      -1
      -1
      -1
      -1
      -1
      -1
      -1
      -1
      Notes/Explanation of Sample Input:
      For the first test case, for N = 3, there are 4 dequeue permutations, lexicographically ordered as 1-2-3, 1-3-2, 3-1-2, and 3-2-1. Denethor sees the first number of the dequeue permutation as 3, and concludes that the permutation can be either 3-1-2, or 3-2-1.
      In the second test case, we see that
      (a) the 1st number is 1.
      (b) the 3rd number is 2 ... this means that the 2nd number has to be 32.
      (c) the 2nd number is 32 ... this does not add any new information.
      (d) the 4th number is 4. But this is not possible, since the 4th number can now either be 3 or 31. 
      Hence it is inconsistent (and none of the further observations can make it consistent).
      Also notice that in the 2nd test-case, the values have been output modulo 1,000,000,007.

      'Though the Stewards deemed that it was a secret kept only by themselves, long ago I guessed that here in the White Tower, one at least of the Seven Seeing Stones was preserved. In the days of his wisdom Denethor did not presume to use it, nor to challenge Sauron, knowing the limits of his own strength. But his wisdom failed; and I fear that as the peril of his realm grew he looked in the Stone and was deceived: far too often, I guess, since Boromir departed. He was too great to be subdued to the will of the Dark Power, he saw nonetheless only those things which that Power permitted him to see.' - Gandalf.

      Sauron and Saruman have been communicating from large distances using the Seeing Stones. Denethor, with great difficulty has been able to break into their channel of communication using his strength of will. Despite this however, it seems that their communication has been encrypted. Gondor's spies in Isengard have found out the encryption algorithm they use and have reported back to Denethor.

       

      The algorithm is as follows :

      We refer to a dequeue as a double-ended queue. We define a "dequeue permutation of N" as a permutation of 1 to N that can be got by starting from a dequeue having elements 1, 2, 3, ..., N (in that order with 1 at the front and N at the back) and performing any sequence of N pop_front() or pop_back() operations. 

      Note that not all permutations of 1 to N are dequeue permutations. For example, with N = 3, you have 3-1-2, 1-3-2 etc. as dequeue permutations whereas 2-1-3, 2-3-1 aren't (you can't have 2 right at the beginning since its not at any end of the dequeue).

       

      If Sauron wants to encrypt the number K and send it to Saruman, he would instead send the K'th lexicographically smallest (0-based indexed) dequeue permutation of N. That is, if Sauron wanted to send '0' to Saruman, he would just send 1-2-3-...-N (since this is clearly the smallest lexicographic dequeue permutation of N).

      Sauron is transmitting the size of his army to Saruman, so that they can coordinate an attack on the Men of Rohan and Gondor. Since Sauron's will is so powerful, Denethor is able to get only vague glimpses of the numbers, and he is able to remember only the first half (floor(N/2) elements) of the permutation. Further, since these images are so vague, his understanding of the numbers happens out of order. For example, Denethor may understand that the 5th number of the permutation is 4, and later on only understand that the 3rd number was 3. 

       

      Help him estimate the minimum and maximum possible size of Sauron's army (value of K), given the number N, and incremental understanding of the first half of the permutation, not necessarily in order.

       

      NOTE 1: Since the values to be output can be rather large, output the values modulo 1,000,000,007.

      NOTE 2: It may be the case that Denethor's understanding of the permutation is flawed. If it is not possible to have a dequeue permutation satisfying all the conditions seen so far, output -1.

      NOTE 3: A permutation p1 is lexicographically smaller than p2 if at the first position where they differ, p1's value is smaller than p2's.

       

      Input (STDIN):

      The first line consists of the integer T, the number of test cases.

      Each test case begins with a single integer N.

      This is followed by exactly floor(N/2) lines containing 2 integers each: i and j, denoting that Denethor has understood that the i'th element (1-based) of the supposed permutation is j.

       

      Output (STDOUT):

      For each testcase, output exactly floor(N/2) lines, one for each (i,j) pair. If the recollections till now cannot all be feasible, output '-1' on a line. Else output two space-separated integers: the minimum and the maximum possible value of Sauron's army, K, that are consistent with all the observations seen so far.

      Between successive test cases, there should not be any blank lines in the output.

       

      Constraints:

      1 <= T < 3 

      2 <= N <= 100,000

      1 <= i <= floor(N/2)

      1 <= j <= N

      All (i, j) pairs are distinct. And for two pairs (i1, j1) and (i2, j2), you have that i1 != i2 and j1 != j2.

       

      Sample Input:

      2

      3

      1 3

      32

      1 1

      3 2

      2 32

      4 4

      5 5

      6 6

      7 7

      8 8

      9 9

      10 10

      11 11

      12 12

      13 13

      14 14

      15 15

      16 3

       

      Sample Output:

      2 3

      0 73741816

      536870912 805306367

      536870912 805306367

      -1

      -1

      -1

      -1

      -1

      -1

      -1

      -1

      -1

      -1

      -1

      -1

      -1

       

      Notes/Explanation of Sample Input:

      For the first test case, for N = 3, there are 4 dequeue permutations, lexicographically ordered as 1-2-3, 1-3-2, 3-1-2, and 3-2-1. Denethor sees the first number of the dequeue permutation as 3, and concludes that the permutation can be either 3-1-2, or 3-2-1.

      In the second test case, we see that

      (a) the 1st number is 1.

      (b) the 3rd number is 2 ... this means that the 2nd number has to be 32.

      (c) the 2nd number is 32 ... this does not add any new information.

      (d) the 4th number is 4. But this is not possible, since the 4th number can now either be 3 or 31. 

      Hence it is inconsistent (and none of the further observations can make it consistent).

      Also notice that in the 2nd test-case, the values have been output modulo 1,000,000,007.

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:8s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Pradeep George Mathias - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13046. The Glittering Caves of Aglarond

      Problem code: AMR12G

       

      'Strange are the ways of Men, Legolas! Here they have one of the marvels of the Northern World, and what do they say of it? Caves, they say! Caves! Holes to fly to in time of war, to store fodder in! My good Legolas, do you know that the caverns of Helm's Deep are vast and beautiful? There would be an endless pilgrimage of Dwarves, merely to gaze at them, if such things were known to be. Aye indeed, they would pay pure gold for a brief glance!
      'And, Legolas, when the torches are kindled and men walk on the sandy floors under the echoing domes, ah! then, Legolas, gems and crystals and veins of precious ore glint in the polished walls; and the light glows through folded marbles, shell-like, translucent as the living hands of Queen Galadriel.' - Gimli, describing to Legolas the Glittering Caves of Aglarond.
      While these caves are by and large natural, there is one place where the Men of Rohan have chiseled into the rock to create a magnificent exhibit. You have a wall of the cave consisting of 'lighted diamonds' arranged in a N by M grid (basically, you have a light behind each diamond which can be turned on or off). Further, you have a switch corresponding to each row of this diamond-grid. When you operate a switch, it will toggle (flip) the lights corresponding to that row.
      You are given the current configuration of the lighted diamonds. Gimli challenges Legolas to turn on as many diamonds as possible using EXACTLY K on/off operations of the switches. Since Legolas is an Elf of the Wood and doesn't care much for things that glitter, he instead asks for your help. Note that the same switch (i.e. row) can be chosen multiple times.
      Input (STDIN):
      The first line contains the number of test cases T. Each test case contains N, M and K on the first line followed by N lines containing M characters each. The ith line denotes the state of the diamonds in the ith row, where '*' denotes a diamond which is on and '.' denotes a diamond which is off.
      Output (STDOUT):
      Output T lines containing the answer for the corresponding case.
      Between successive test cases, there should not be any blank lines in the output.
      Constraints:
      1 <= T <= 100
      1 <= N,M <= 50
      1 <= K <= 100
      Sample Input:
      2
      2 2 1
      ..
      **
      2 2 2
      ..
      **
      Sample Output:
      4
      2
      Notes/Explanation of Sample Input:
      In the first test case, row 1 can be toggled hence leaving all 4 lights to be in the ON state.
      In the second test case, row 1 (or row 2) can be toggled twice, hence maintaining the state of the initial configuration. 

       

      'Strange are the ways of Men, Legolas! Here they have one of the marvels of the Northern World, and what do they say of it? Caves, they say! Caves! Holes to fly to in time of war, to store fodder in! My good Legolas, do you know that the caverns of Helm's Deep are vast and beautiful? There would be an endless pilgrimage of Dwarves, merely to gaze at them, if such things were known to be. Aye indeed, they would pay pure gold for a brief glance!

      'And, Legolas, when the torches are kindled and men walk on the sandy floors under the echoing domes, ah! then, Legolas, gems and crystals and veins of precious ore glint in the polished walls; and the light glows through folded marbles, shell-like, translucent as the living hands of Queen Galadriel.' - Gimli, describing to Legolas the Glittering Caves of Aglarond.

       

      While these caves are by and large natural, there is one place where the Men of Rohan have chiseled into the rock to create a magnificent exhibit. You have a wall of the cave consisting of 'lighted diamonds' arranged in a N by M grid (basically, you have a light behind each diamond which can be turned on or off). Further, you have a switch corresponding to each row of this diamond-grid. When you operate a switch, it will toggle (flip) the lights corresponding to that row.

       

      You are given the current configuration of the lighted diamonds. Gimli challenges Legolas to turn on as many diamonds as possible using EXACTLY K on/off operations of the switches. Since Legolas is an Elf of the Wood and doesn't care much for things that glitter, he instead asks for your help. Note that the same switch (i.e. row) can be chosen multiple times.

       

      Input (STDIN):

      The first line contains the number of test cases T. Each test case contains N, M and K on the first line followed by N lines containing M characters each. The ith line denotes the state of the diamonds in the ith row, where '*' denotes a diamond which is on and '.' denotes a diamond which is off.

       

      Output (STDOUT):

      Output T lines containing the answer for the corresponding case.

      Between successive test cases, there should not be any blank lines in the output.

       

      Constraints:

      1 <= T <= 100

      1 <= N,M <= 50

      1 <= K <= 100

       

      Sample Input:

      2

      2 2 1

      ..

      **

      2 2 2

      ..

      **

       

      Sample Output:

      4

      2

       

      Notes/Explanation of Sample Input:

      In the first test case, row 1 can be toggled hence leaving all 4 lights to be in the ON state.

      In the second test case, row 1 (or row 2) can be toggled twice, hence maintaining the state of the initial configuration. 

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Varun Jalan - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13047. Saruman of Many Colours

      Problem code: AMR12I


       

      '"For I am Saruman the Wise, Saruman Ring-maker, Saruman of Many Colours!"
      'I looked then and saw that his robes, which had seemed white, were not so, but were woven of all colours. And if he moved they shimmered and changed hue so that the eye was bewildered.' - Gandalf the Grey.
      And so it was that Saruman decided to brand his Uruk-hai army with the many colours that he fancied. His method of branding his army was as follows.
      He straps his army of N Uruk-hai onto chairs on a conveyor belt. This conveyor belt passes through his colouring-room, and can be moved forward or backward. The Uruk-hai are numbered 0 to N-1 according to the order in which they are seated. Saruman wishes that the i'th Uruk-hai be coloured with the colour c[i].
      Further, his colouring-room has space for exactly K chairs. Once the chosen K consecutive Uruk-hai are put into the room, a colour jet sprays all K of them with any fixed colour. The conveyor belt is not circular (which means that the N-1'th and the 0'th Uruk-hai are not consecutive). Note that Uruk-hai can be recoloured in this process.
      Saruman wants to find out what is the minimum number of times that the jet needs to be used in order to colour his army in the required fashion. If it is not possible to colour the army in the required fashion, output -1.
      Input (STDIN):
      The first line contains the number of test-cases T.
      Each test case consists of 2 lines. The first line contains two space-separated integers, N and K.
      This is followed by a single like containing a string of length N, describing the colours of the army. The i'th character of the string denotes the colour of the i'th Uruk-hai in the army.
      Output (STDOUT):
      Output T lines, one for each test case containing the answer for the corresponding test case. Remember if it is not possible to colour the army as required, output -1.
      Constraints:
      1 <= T <= 50
      1 <= K <= N <= 20,000
      The string c has length exactly N and contains only the characters 'a',...,'z'.
      Sample Input:
      2
      3 2
      rgg
      3 3
      rgg
      Sample Output:
      2
      -1
      Notes/Explanation of Sample Input:
      In the first test case, soldiers 0 and 1 can first be painted with 'r', and then soldiers 1 and 2 can be painted with 'g'.
      In the second test case, since N = K, all the soldiers will only have the same color.

       

      '"For I am Saruman the Wise, Saruman Ring-maker, Saruman of Many Colours!"

      'I looked then and saw that his robes, which had seemed white, were not so, but were woven of all colours. And if he moved they shimmered and changed hue so that the eye was bewildered.' - Gandalf the Grey.

      And so it was that Saruman decided to brand his Uruk-hai army with the many colours that he fancied. His method of branding his army was as follows.

      He straps his army of N Uruk-hai onto chairs on a conveyor belt. This conveyor belt passes through his colouring-room, and can be moved forward or backward. The Uruk-hai are numbered 0 to N-1 according to the order in which they are seated. Saruman wishes that the i'th Uruk-hai be coloured with the colour c[i].

      Further, his colouring-room has space for exactly K chairs. Once the chosen K consecutive Uruk-hai are put into the room, a colour jet sprays all K of them with any fixed colour. The conveyor belt is not circular (which means that the N-1'th and the 0'th Uruk-hai are not consecutive). Note that Uruk-hai can be recoloured in this process.

       

      Saruman wants to find out what is the minimum number of times that the jet needs to be used in order to colour his army in the required fashion. If it is not possible to colour the army in the required fashion, output -1.

       

      Input (STDIN):

      The first line contains the number of test-cases T.

      Each test case consists of 2 lines. The first line contains two space-separated integers, N and K.

      This is followed by a single like containing a string of length N, describing the colours of the army. The i'th character of the string denotes the colour of the i'th Uruk-hai in the army.

       

      Output (STDOUT):

      Output T lines, one for each test case containing the answer for the corresponding test case. Remember if it is not possible to colour the army as required, output -1.

       

      Constraints:

      1 <= T <= 50

      1 <= K <= N <= 20,000

      The string c has length exactly N and contains only the characters 'a',...,'z'.

       

      Sample Input:

      2

      3 2

      rgg

      3 3

      rgg

       

      Sample Output:

      2

      -1

       

      Notes/Explanation of Sample Input:

      In the first test case, soldiers 0 and 1 can first be painted with 'r', and then soldiers 1 and 2 can be painted with 'g'.

      In the second test case, since N = K, all the soldiers will only have the same color.

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Varun Jalan - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13048. Escape from the Mines

      Problem code: AMR12J


       

      It was after nightfall when they had entered the Mines. They had been going for several hours with only brief halts, when Gandalf came to his first serious check. Before him stood a wide dark arch opening into three passages: all led in the same general direction, eastwards; but the left-hand passage plunged down, while the right-hand climbed up, and the middle way seemed to run on, smooth and level but very narrow. - The Fellowship of the Ring are lost in the Mines.
      The Mines of Moria are a true testament of Dwarvish genius. And the Fellowship of the Ring are lost in the maze of rooms, halls and caverns. You have managed to acquire a copy of the blueprints, and if only you were part of the Fellowship, Gandalf need not have had to face the Balrog!
      In this problem, we consider the Mines as consisting of rectangular rooms with their sides aligned parallel to the X (West-East) and Y (South-North) axes. Some rooms are situated within other rooms. The boundaries of any two rooms have no point in common. The rooms are numbered 0 to N-1. Your task is to determine for each room i, which room would you enter if you exit room i. If you exit into the open, output -1.
      For example, if the blueprints of the Mines looked like:
      Then, you should determine that:
      Room 0 exits into the open (-1)
      Room 1 exits into Room 0
      Room 2 exits into Room 1
      Room 3 exits into the open (-1)
      Input (STDIN):
      The first line contains an integer N followed by N lines. The i'th line defines the coordinates of the i'th room in the mines: x1_i, y1_i, x2_i, y2_i, where (x1_i, y1_i) are the coordinates of the southwest corner and (x2_i, y2_i) are the coordinates of the northeast corner of the i'th room.
      Output (STDOUT):
      Output N lines, the i'th line containing the number of the room into which the i'th room exits. Output -1 if the i'th room exits into the open.
      Constraints:
      1 <= N <= 100,000
      0 <= x1_i < x2_i <= 1,000,000,000
      0 <= y1_i < y2_i <= 1,000,000,000
      The borders of no two rooms have any point in common.
      Sample Input:
      4
      0 0 10 10
      2 3 7 8
      3 4 5 6
      12 10 13 15
      Sample Output:
      -1
      0
      1
      -1
      Notes/Explanation of Sample Input:
      Given in the diagram. 

      It was after nightfall when they had entered the Mines. They had been going for several hours with only brief halts, when Gandalf came to his first serious check. Before him stood a wide dark arch opening into three passages: all led in the same general direction, eastwards; but the left-hand passage plunged down, while the right-hand climbed up, and the middle way seemed to run on, smooth and level but very narrow. - The Fellowship of the Ring are lost in the Mines.

       

      The Mines of Moria are a true testament of Dwarvish genius. And the Fellowship of the Ring are lost in the maze of rooms, halls and caverns. You have managed to acquire a copy of the blueprints, and if only you were part of the Fellowship, Gandalf need not have had to face the Balrog!

       

      In this problem, we consider the Mines as consisting of rectangular rooms with their sides aligned parallel to the X (West-East) and Y (South-North) axes. Some rooms are situated within other rooms. The boundaries of any two rooms have no point in common. The rooms are numbered 0 to N-1. Your task is to determine for each room i, which room would you enter if you exit room i. If you exit into the open, output -1.

       

      For example, if the blueprints of the Mines looked like:

       

              -----

             |     |

             |     |

              -----3

       

          -------------------

         |     -------       |

         |    |       |      |

         |    |  []   |      |

         |    |   2  |      |

         |     -------1     |

         |                   |

          ------------------0

       

      Then, you should determine that:

      Room 0 exits into the open (-1)

      Room 1 exits into Room 0

      Room 2 exits into Room 1

      Room 3 exits into the open (-1)

       

      Input (STDIN):

      The first line contains an integer N followed by N lines. The i'th line defines the coordinates of the i'th room in the mines: x1_i, y1_i, x2_i, y2_i, where (x1_i, y1_i) are the coordinates of the southwest corner and (x2_i, y2_i) are the coordinates of the northeast corner of the i'th room.

       

      Output (STDOUT):

      Output N lines, the i'th line containing the number of the room into which the i'th room exits. Output -1 if the i'th room exits into the open.

       

      Constraints:

      1 <= N <= 100,000

      0 <= x1_i < x2_i <= 1,000,000,000

      0 <= y1_i < y2_i <= 1,000,000,000

      The borders of no two rooms have any point in common.

       

      Sample Input:

      4

      0 0 10 10

      2 3 7 8

      3 4 5 6

      12 10 13 15

       

      Sample Output:

      -1

      0

      1

      -1

       

      Notes/Explanation of Sample Input:

      Given in the diagram. 

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Varun Jalan - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13049. The Loyalty of the Orcs

      Problem code: AMR12K


       

      'I think that the enemy brought his own enemy with him,' answered Aragorn. 'These are Northern Orcs from far away. Among the slain are none of the great Orcs with the strange badges. There was a quarrel, I guess: it is no uncommon thing with these foul folk. Maybe there was some dispute about the road.' - Aragorn describing the nature of Orcs.
      Indeed, everyone knows that the Orcs are treacherous creatures who look for their own satisfaction and more often than not disregard the rules. The only way to keep them in line, is by maintaining the chain of command over a strict hierarchy among the ranks, wherein each Orc is responsible to his immediate superior all the way up to the army's head.
      Further, the powers that be, have decided to have regular checks of their army's loyalties, just in case some Orc has been killed and all his juniors end up turning rogue!
      There are N orcs, numbered 1 to N, wherein the lead orc is numbered 1.
      Step 1. Randomly choose a fixed order in which to test Orcs' loyalties.
      Step 2. Going in this order, you make a "roll-call" to check if the current Orc is alive or not.
      Step 3. If the current Orc is dead, then he is marked as "deleted".
      With this information, it is possible to tell which all Orcs will be loyal, and which won't be. However, cunning Master Wormtongue suggests the following optimization:
      In step 2, if any of the considered Orc's superiors (not necessarily immediate superior) is marked as deleted, then the roll-call is not made.
      Now, given this algorithm and the hierarchy of the army, along with which Orcs are dead, what is the expected number of roll-calls (taken over all possible orderings in "Step 1") that you save by performing this optimization?
      Input (STDIN):
      The first line contains T, the number of test cases.
      The first line of each test case contains N, the number of orcs in the army. The next N-1 lines contain two space-separated integers u v, denoting that u is the immediate superior of v or vice-versa. The head of the army is the orc labelled 1. The next line contains m, the number of dead orcs. The next line contains m space separated integers, which are the labels of the dead orcs.
      Output (STDOUT):
      Output one real number for each test case containing the expected number of roll-calls that you save. The results should be accurate within an error range of 10^-6.
      Constraints:
      1 <= T <= 5
      1 <= N <= 100,000
      1 <= u, v <= N
      u != v
      The given set of u-v pairs form a valid chain of command. That means every Orc, except the Orc labeeled 1, has exactly one immediate superior.
      Sample Input:
      2
      2
      1 2
      1
      1
      2
      1 2
      1
      2
      Sample Output:
      0.5
      0
      Notes/Explanation of Sample Input:
      For the first test case, the Orc labelled 1 is dead. The two possible orderings are [1, 2] and [2, 1]. With the optimization, for the order [1, 2], we save the roll-call to 2. So, the total number of roll-calls without the optimization is 4, and with the optimization is 3. Expected number of roll-calls is therefore, (4 - 3) / 2 = 0.5 .
      For the second test case, the Orc labeled 2 is dead. Since he does not have any sub-ordinates, the optimization does not have any effect.

       

      'I think that the enemy brought his own enemy with him,' answered Aragorn. 'These are Northern Orcs from far away. Among the slain are none of the great Orcs with the strange badges. There was a quarrel, I guess: it is no uncommon thing with these foul folk. Maybe there was some dispute about the road.' - Aragorn describing the nature of Orcs.

       

      Indeed, everyone knows that the Orcs are treacherous creatures who look for their own satisfaction and more often than not disregard the rules. The only way to keep them in line, is by maintaining the chain of command over a strict hierarchy among the ranks, wherein each Orc is responsible to his immediate superior all the way up to the army's head.

       

      Further, the powers that be, have decided to have regular checks of their army's loyalties, just in case some Orc has been killed and all his juniors end up turning rogue!

       

      There are N orcs, numbered 1 to N, wherein the lead orc is numbered 1.

      Step 1. Randomly choose a fixed order in which to test Orcs' loyalties.

      Step 2. Going in this order, you make a "roll-call" to check if the current Orc is alive or not.

      Step 3. If the current Orc is dead, then he is marked as "deleted".

       

      With this information, it is possible to tell which all Orcs will be loyal, and which won't be. However, cunning Master Wormtongue suggests the following optimization:

      In step 2, if any of the considered Orc's superiors (not necessarily immediate superior) is marked as deleted, then the roll-call is not made.

       

      Now, given this algorithm and the hierarchy of the army, along with which Orcs are dead, what is the expected number of roll-calls (taken over all possible orderings in "Step 1") that you save by performing this optimization?

       

      Input (STDIN):

      The first line contains T, the number of test cases.

      The first line of each test case contains N, the number of orcs in the army. The next N-1 lines contain two space-separated integers u v, denoting that u is the immediate superior of v or vice-versa. The head of the army is the orc labelled 1. The next line contains m, the number of dead orcs. The next line contains m space separated integers, which are the labels of the dead orcs.

       

      Output (STDOUT):

      Output one real number for each test case containing the expected number of roll-calls that you save. The results should be accurate within an error range of 10^-6.

       

      Constraints:

      1 <= T <= 5

      1 <= N <= 100,000

      1 <= u, v <= N

      u != v

      The given set of u-v pairs form a valid chain of command. That means every Orc, except the Orc labeeled 1, has exactly one immediate superior.

       

      Sample Input:

      2

      2

      1 2

      1

      1

      2

      1 2

      1

      2

       

      Sample Output:

      0.5

      0

       

      Notes/Explanation of Sample Input:

      For the first test case, the Orc labelled 1 is dead. The two possible orderings are [1, 2] and [2, 1]. With the optimization, for the order [1, 2], we save the roll-call to 2. So, the total number of roll-calls without the optimization is 4, and with the optimization is 3. Expected number of roll-calls is therefore, (4 - 3) / 2 = 0.5 .

      For the second test case, the Orc labeled 2 is dead. Since he does not have any sub-ordinates, the optimization does not have any effect.

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Utkarsh Lath, Pratik Tandel - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13050. Entmoot

      Problem code: AMR12C

       

      Hoo, ho! Good morning, Merry and Pippin!' he boomed, when he saw them. 'You sleep long. I have been many a hundred strides already today. Now we will have a drink, and go to Entmoot.'
      'Where is Entmoot?' Pippin ventured to ask.
      'Hoo, eh? Entmoot?' said Treebeard, turning round. 'It is not a place, it is a gathering of Ents - which does not often happen nowadays. But I have managed to make a fair number promise to come.'
      Indeed, Entmoot cannot be thought of as any particular place, since where it occurs changes from time to time. The choice of the location however, follows a basic principle: Although the Ents (walking and talking Trees - "shepherds of Fangorn Forest") are by and large not hasty, when it comes to gathering for Entmoot, they would like to choose a location that ensures all the Ents can reach as soon as possible.
      Note however, that the speed they can travel varies from Ent to Ent. Also, although Fangorn Forest has dense overgrowth, with regard to the Ents, the forest poses no obstacles.
      You are given the locations of N Ents who have agreed to join in for Entmoot, as well as their speeds. You need to find out where Entmoot will occur. Formally, given the (x_i,y_i) along with speed s_i for each Ent, find the point (X, Y) such that the maximum time taken by any of the Ents to reach (X, Y) is minimized. Output the earliest time when all the Ents can meet. 
      Input (STDIN):
      The first line contains T, the number of test cases.
      The first line of each test case contains N, the number of Ents.
      The next N lines contain three space-separated integers each. The ith of these lines contains : x_i, y_i, s_i.
      Output (STDOUT):
      Output one line per test case, containing the earliest time when the Ents can meet. Relative and absolute error of 10^-4 are acceptable. 
      Constraints:
      1 <= T <= 10
      2 <= N <= 50
      -1,000,000 <= x_i, y_i <= 1,000,000
      1 <= s_i <= 1,000,000
      Sample Input:
      4
      3
      0 3 3
      4 0 4
      -3 -4 5
      3
      0 10 2
      0 20 2
      0 40 2
      3
      0 100 15
      0 -100 15
      8 0 7
      3
      0 0 1
      10000 0 1
      5000 8661 1
      Sample Output:
      1.000000
      7.500000
      6.666667
      5773.751357
      Notes/Explanation of Sample Input:
      In the first test case, all the ents can meet at origin in 1 unit of time. 
      In the second test case, the first and the third ent reach (25,0) after 7.5 units of ime, whereas the second ent reaches there after 2.5 units of time and waits for the remaining ents to arrive. 
      In the third test case, all the ents can meet at origin in 100/15 units of time.

       

      Hoo, ho! Good morning, Merry and Pippin!' he boomed, when he saw them. 'You sleep long. I have been many a hundred strides already today. Now we will have a drink, and go to Entmoot.'

      'Where is Entmoot?' Pippin ventured to ask.

      'Hoo, eh? Entmoot?' said Treebeard, turning round. 'It is not a place, it is a gathering of Ents - which does not often happen nowadays. But I have managed to make a fair number promise to come.'

       

      Indeed, Entmoot cannot be thought of as any particular place, since where it occurs changes from time to time. The choice of the location however, follows a basic principle: Although the Ents (walking and talking Trees - "shepherds of Fangorn Forest") are by and large not hasty, when it comes to gathering for Entmoot, they would like to choose a location that ensures all the Ents can reach as soon as possible.

       

      Note however, that the speed they can travel varies from Ent to Ent. Also, although Fangorn Forest has dense overgrowth, with regard to the Ents, the forest poses no obstacles.

       

      You are given the locations of N Ents who have agreed to join in for Entmoot, as well as their speeds. You need to find out where Entmoot will occur. Formally, given the (x_i,y_i) along with speed s_i for each Ent, find the point (X, Y) such that the maximum time taken by any of the Ents to reach (X, Y) is minimized. Output the earliest time when all the Ents can meet. 

       

      Input (STDIN):

      The first line contains T, the number of test cases.

      The first line of each test case contains N, the number of Ents.

      The next N lines contain three space-separated integers each. The ith of these lines contains : x_i, y_i, s_i.

       

      Output (STDOUT):

      Output one line per test case, containing the earliest time when the Ents can meet. Relative and absolute error of 10^-4 are acceptable. 

       

      Constraints:

      1 <= T <= 10

      2 <= N <= 50

      -1,000,000 <= x_i, y_i <= 1,000,000

      1 <= s_i <= 1,000,000

       

      Sample Input:

      4

      3

      0 3 3

      4 0 4

      -3 -4 5

      3

      0 10 2

      0 20 2

      0 40 2

      3

      0 100 15

      0 -100 15

      8 0 7

      3

      0 0 1

      10000 0 1

      5000 8661 1

       

      Sample Output:

      1.000000

      7.500000

      6.666667

      5773.751357

       

      Notes/Explanation of Sample Input:

      In the first test case, all the ents can meet at origin in 1 unit of time. 

      In the second test case, the first and the third ent reach (25,0) after 7.5 units of ime, whereas the second ent reaches there after 2.5 units of time and waits for the remaining ents to arrive. 

      In the third test case, all the ents can meet at origin in 100/15 units of time.

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Utkarsh Lath - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set (classical)

      13051. Wormtongues Mind

      Problem code: AMR12H

       

      Wormtongue looked from face to face. In his eyes was the hunted look of a beast seeking some gap in the ring of his enemies.
      'Nay, Eomer, you do not fully understand the mind of Master Wormtongue,' said Gandalf, turning his piercing glance upon him. 'He is bold and cunning. Even now he plays a game with peril and wins a throw.' - Gandalf, trying to figure out Wormtongue's mind.
      In fact, Wormtongue's mind is a complicated system of evaluating various variables and parameters. In essence, each parameter is a uniform random floating point variable between 0 and 1 (inclusive). Further, his mind works on calculating best and worst-case values, which are equivalent to min/max of 2 expressions.
      For example, right now Wormtongue is calculating :
      'Chances of escaping' = max('Theoden letting me go', 'Me killing everyone')
      'Theoden letting me go' = max('Theoden is forgiving by nature', 'Gandalf advises him to let me go').
      'Me killing everyone' = min('Me killing Gandalf', 'Me killing Theoden').
      So, you are given an expression consisting of independent uniform [0, 1] random variables, on which you have an expression consisting of "min", and "max" alone. Help Gandalf figure out Wormtongue's mind by finding the expected value of this expression.
      Input (STDIN):
      The first line contains T, the number of test cases.
      Each test case consists of a single line describing the expression. The characters of the string are derived from the set {'M','m','x'}, where 'M' stands for max, 'm' stands for min, and 'x' is a random variable
      Formally, in the expression tree, each node which asks for max is labeled as 'M', each node which asks for min is labelled 'm', and all the leaves are labeled 'x'. The description of the expression is preorder traversal of this tree.
      For example, Mxmxx describes the expression max(x1, min(x2, x3)).
      Output (STDOUT):
      For each test case, output one line which contains the expected value of the expression. The results should be accurate within an error range of 10^-6.
      Constraints:
      1 <= T <= 1,000
      1 <= input string length <= 100
      Sample Input:
      4
      x
      mxx
      Mxx
      MmxxMxx 
      Sample Output:
      0.500000
      0.333333
      0.666667
      0.700000
      Notes/Explanation of Sample Input:
      For the first test case, it asks for the mean of a random number between 0 and 1, which is 0.5.
      Note:
      It is recommended to use long long and long double data types in calculation to avoid precision errors.

      Wormtongue looked from face to face. In his eyes was the hunted look of a beast seeking some gap in the ring of his enemies.

      'Nay, Eomer, you do not fully understand the mind of Master Wormtongue,' said Gandalf, turning his piercing glance upon him. 'He is bold and cunning. Even now he plays a game with peril and wins a throw.' - Gandalf, trying to figure out Wormtongue's mind.

       

      In fact, Wormtongue's mind is a complicated system of evaluating various variables and parameters. In essence, each parameter is a uniform random floating point variable between 0 and 1 (inclusive). Further, his mind works on calculating best and worst-case values, which are equivalent to min/max of 2 expressions.

       

      For example, right now Wormtongue is calculating :

      'Chances of escaping' = max('Theoden letting me go', 'Me killing everyone')

      'Theoden letting me go' = max('Theoden is forgiving by nature', 'Gandalf advises him to let me go').

      'Me killing everyone' = min('Me killing Gandalf', 'Me killing Theoden').

       

      So, you are given an expression consisting of independent uniform [0, 1] random variables, on which you have an expression consisting of "min", and "max" alone. Help Gandalf figure out Wormtongue's mind by finding the expected value of this expression.

       

      Input (STDIN):

      The first line contains T, the number of test cases.

      Each test case consists of a single line describing the expression. The characters of the string are derived from the set {'M','m','x'}, where 'M' stands for max, 'm' stands for min, and 'x' is a random variable

      Formally, in the expression tree, each node which asks for max is labeled as 'M', each node which asks for min is labelled 'm', and all the leaves are labeled 'x'. The description of the expression is preorder traversal of this tree.

      For example, Mxmxx describes the expression max(x1, min(x2, x3)).

       

      Output (STDOUT):

      For each test case, output one line which contains the expected value of the expression. The results should be accurate within an error range of 10^-6.

       

      Constraints:

      1 <= T <= 1,000

      1 <= input string length <= 100

       

      Sample Input:

      4

      x

      mxx

      Mxx

      MmxxMxx 

       

      Sample Output:

      0.500000

      0.333333

      0.666667

      0.700000

       

      Notes/Explanation of Sample Input:

      For the first test case, it asks for the mean of a random number between 0 and 1, which is 0.5.

       

      Note:

      It is recommended to use long long and long double data types in calculation to avoid precision errors.

       

       


      Added by:Varun Jalan
      Date:2012-12-22
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Utkarsh Lath - ICPC Asia regionals, Amritapuri 2012









      SPOJ Problem Set ()

      13055. New Year Train

      Problem code: IZHONYT

      On the New Year Eve, a government of one country decided to send a train with gifts to each of its towns. For each of the N towns exactly one wagon with gifts was sent. The route was organized in such way that at each place the last wagon would be detached and train would continue on it's way, until all gifts were delivered. Just before the departure it turned out that the loading workers did not pay attention to numeration of the wagons and loaded the gifts in random order. It was impossible to detach a wagon from the middle of the train and there was no time to rearrange gifts. Luckily, there was a depot with parallel tracks. At the entrance of the depot each wagon could be directed to any of the tracks and wagons could leave the depot from the other side in the right sequences 1, 2, 3, 4, and so on. Note that we will then be leaving presents in towns in the reversed order (..., 4, 3, 2, 1).

      For example, let's say we have a train with wagons in the following order: 2, 5, 1, 4, 6, 3. Wagons 2, 5, 6 could be directed to the first track; wagons 1, 4 to the second one and wagon 3 to the third. In this case wagons could leave the depot in the right order. Fortunately, there were enough tracks in the depot to rearrange the train.

      Input

      First line of the input contains two integers N and M: the number of wagons in the train and the number of tracks in the depot respectively (1 <= N <= 800 000, 1 <= M <= 100 000, M <= N). Second line contains N integers: sequence of wagons before the entrance to the depot. It's guaranteed that solution always exists.

      Output

      First line of the output must contain N integers: number of track that should be chosen for each wagon from input sequence (tracts are numbered from 1 to M). On the second line print the number of tracks in order the wagons should leave the depot to result in the sequence 1, 2, 3, and so on. If multiple solutions exists, print the one that results in lexicographically smallest sequence in the first line of the output.

      Example

      Input
      6 3
      2 5 1 4 6 3
      
      Output
      1 1 2 2 1 3
      2 1 3 2 1 1
      

      Added by:KAREN HAMBARDZUMYAN
      Date:2012-12-22
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:IZhO 2012 Day 1









      SPOJ Problem Set (classical)

      13076. Slikar

      Problem code: CSLIKAR


      The evil emperor Cactus has in his possession the Magic Keg and has flooded the Enchanted
      Forest! The Painter and the three little hedgehogs now have to return to the Beaver's den where they  
      will be safe from the water as quickly as possible!  
      The map of the Enchanted Forest consists of R rows and C columns. Empty fields are represented
      by '.' characters, flooded fields by '*' and rocks by 'X'. Additionally, the Beaver's den is represented
      by 'D' and the Painter and the three little hedgehogs are shown as 'S'.  
      Every minute the Painter and the three little hedgehogs can move to 4 neighbouring fields (up,  
      down, left or right). Every minute the flood expands as well so that all empty fields that have at least  
      one common side with a flooded field become flooded as well. Neither water nor the Painter and
      the three little hedgehogs can pass through rocks. Naturally, the Painter and the three little  
      hedgehogs cannot pass through flooded fields, and water cannot flood the Beaver's den.
      Write a program that will, given a map of the Enchanted Forest, output the shortest time needed  
      for the Painter and the three little hedgehogs to safely reach the Beaver's den.
      Note:  The Painter and the three little hedgehogs cannot move into a field that is about to be  
      flooded (in the same minute).

      Input

      The first line of input will contain two integers, R and C, smaller than or equal to 50.  
      The following R lines will each contain C characters ('.', '*', 'X', 'D' or 'S'). The map will contain  
      exactly one 'D' character and exactly one 'S' character

      Output

      Output the  shortest possible time needed for the Painter and the three little hedgehogs to safely  
      reach the Beaver's den. If this is impossible output the word “KAKTUS” on a line by itself.

      Example

      Input:
      3 6
      D...*.
      .X.X..
      ....S.

      Output:
      6

      Added by:Erik Lonèarek
      Date:2012-12-27
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI









      SPOJ Problem Set (classical)

      13078. The Mad Numerologist

      Problem code: MADN

        The Mad Numerologist 

      Numerology is a science that is used by many people to find out a mans personality, sole purpose of life, desires to experience etc. Some calculations of numerology are very complex, while others are quite simple. You can sit alone at home and do these easy calculations without taking any ones help. However in this problem you wont be asked to find the value of your name.

      To find the value of a name modern numerologists have assigned values to all the letters of English Alphabet. The table on the left shows the numerical values of all letters of English alphabets. Five letters A, E, I, O, U are vowels. Rests of the letters are consonant. In this table all letters in column 1 have value 1, all letters in column 2 have value 2 and so on. So T has value 2, F has value 6, R has value 9, O has value 6 etc. When calculating the value of a particular name the consonants and vowels are calculated separately. The following picture explains this method using the name ``CHRISTOPHER RORY PAGE".

       

      IMAGE

      So you can see that to find the consonant value, the values of individual consonants are added and to find the vowel value the values of individual vowels are added. A mad Numerologist suggests people many strange lucky names. He follows the rules stated below while giving lucky names.

      • The name has a predefined length N.
      • The vowel value and consonant value of the name must be kept minimum.
      • To make the pronunciation of the name possible vowels and consonants are placed in alternate positions. Actually vowels are put in odd positions and consonants are put in even positions. The leftmost letter of a name has position 1; the position right to it is position 2 and so on.
      • No consonants can be used in a name more than five times and no vowels can be used in a name more than twenty-one times
      • Following the rules and limitations above the name must be kept lexicographically smallest. Please note that the numerologists first priority is to keep the vowel and consonant value minimum and then to make the name lexicographically smallest.

      Input

      First line of the input file contains an integer N ( 0 < N<=250 ) that indicates how many sets of inputs are there. Each of the next N lines contains a single set of input. The description of each set is given below: Each line contains an integer n ( 0 < n < 211) that indicates the predefined length of the name.

      Output

      For each set of input produce one line of output. This line contains the serial of output followed by the name that the numerologist would suggest following the rules above. All letters in the output should be uppercase English letters.

      Example

      Input:

      3

      1

      5

      5

      Output:

      Case 1: A

      Case 2: AJAJA

      Case 3: AJAJA

       


      Added by::C++:
      Date:2012-12-27
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACM-ICPC Amritapuri Warmup









      SPOJ Problem Set (classical)

      13090. New Strategy

      Problem code: PCPC12D


       

      Meeda will compete this year in the ACM-ICPC world finals, but he is a crazy guy, he created a new strategy to attack the problem set. His new strategy is to solve the problems according to their names. He’ll sort the problem set according to the following rules.
      Remove all whitespace characters from the problem names.
      Replace any capital letters with the corresponding small one. i.e ‘A’ will be ‘a’
      count the occurrence of each character
      Problem A comes before problem B, if A contains lexicographically smaller characters more than B i.e A = “cba” comes before B = “bc” because A contains 1 'a' and B contains 0 'a'.
      But as you may know that meeda is a very lazy guy and he needs to train for this strategy before the world finals, so he needs your help to write an efficient program to help him in the training.
      Input Specification
      The first line of the input contains T, number of test cases, each test case starts with an integer n (0<n<1000) number of problems, follow n lines each containing string s. The ith line is the name of the ith problem. s will be a sequence of characters (a-z, A-Z or any white space character), length of s is less than 100 characters.
      Output Specification
      First line of each test case should contains “case: ” without double quotes followed by the test case number starting from 1, then follow problem names sorted as described above.
      Sample Input
      2
      2
      abc
      ab
      4
      bcsaasd
      dbasaaaa
      azzz
      bayy
      Sample Output
      case: 1
      ab
      abc
      case: 2
      dbasaaaa
      bcsaasd
      bayy
      azzz

       

      Meeda will compete this year in the ACM-ICPC world finals, but he is a crazy guy, he created a new strategy to attack the problem set. His new strategy is to solve the problems according to their names. He’ll sort the problem set according to the following rules.

      Remove all whitespace characters from the problem names.

      Replace any capital letters with the corresponding small one. i.e ‘A’ will be ‘a’

      count the occurrence of each character

      Problem A comes before problem B, if A contains lexicographically smaller characters more than B i.e A = “cba” comes before B = “bc” because A contains 1 'a' and B contains 0 'a'.

      But as you may know that meeda is a very lazy guy and he needs to train for this strategy before the world finals, so he needs your help to write an efficient program to help him in the training.

      Input Specification

      The first line of the input contains T, number of test cases, each test case starts with an integer n (0<n<1000) number of problems, follow n lines each containing string s. The ith line is the name of the ith problem. s will be a sequence of characters (a-z, A-Z or any white space character), length of s is less than 200 characters.

      Output Specification

      First line of each test case should contains “case: ” without double quotes followed by the test case number starting from 1, then follow problem names sorted as described above.

      Sample Input

      2

      2

      abc

      ab

      4

      bcsaasd

      dbasaaaa

      azzz

      bayy


      Sample Output

      case: 1

      abc

      ab

      case: 2

      dbasaaaa

      bcsaasd

      bayy

      azzz

       

      note : sorry for the wrong description .

                 max length is 200 .


      Added by:abdelkarim
      Date:2012-12-28
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:The First Palestinian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      13091. Snakes and Ladders

      Problem code: PCPC12E

      Snakes and Ladders (or Chutes and Ladders) is an ancient Indian board game regarded today as a worldwide classic. It is played between two or more players on a game board having numbered squares (fields) on a grid. A number of "ladders" and "snakes" (or "chutes") are pictured on the board, each connecting two specific board squares. The object of the game is to navigate one's game piece from the start (Bottom square) to the finish (Top Square), helped or hindered by ladders and snakes, respectively. The historic version had root in morality lessons, where a player's progression up the board represented a life journey complicated by virtues (ladders) and vices (snakes).  If, after throwing a dice, a player's token lands on the lower-numbered end of a "ladder", the player moves his token up to the ladder's higher-numbered square. If he lands on the higher-numbered square of a "snake" (or chute), he must move his token down to the snake's lower-numbered square. If any of those cases takes places, we will call a square unstable. Otherwise it is stable.

      The game is a simple race contest lacking a skill component, and is popular with young children.

      In this problem you’re required to calculate the minimum number of 6-sided die throws to move your game piece from the start (bottom square) to the finish (top square).


      Formal game description

      Fields are arranged on an NxM grid and numbered from 1 to N*M. Last field, indicated by N*M, is referred to as Top Square. Each player starts with a token on a square at position "0" (the imaginary space beside the “1” grid field; Bottom Square), which is always stable. So in total we have N*M+1 fields. In every turn player throws the die and moves up by the given number of squares. If that would result in a field higher than Top Square, then token is not moved. If the square that token ends on is unstable, it is moved as indicated by ladder or snake. This is repeated until token is placed a stable field. You can assume that a stable field can be reached from any field on the board. If this final, stable field is the Top Square, game ends and player wins.


       PIC


      Input Specification

      Input contains multiple test cases First line of each test case contains integers N, M, S, L. where n and m are the board dimensions, N (0 < N <= 100), M (0 < M <= 100), and S and L are number of snakes and ladders respectively. Next S lines describes snakes. Each line contains two integers: h and t, where h is the snake’s head position and t is the snake tail position. (0 < t < h <=N*M), Next L lines describes ladders. Each line contains two integers: p and q where p is the ladder’s bottom and q is the ladder’s top (0 < p < q < N*M).

      The input will be terminated by the end of file.

      NOTE! There could be more snakes and/or ladders leading from a single field. In such a case use the last snake/ladder specified in the input.


      Output Specification

      Print one line per test case containing the minimum number of dice throws. If you cannot reach to the finish square print -1


      Sample Input
      
      1 1 0 0
      1 2 1 0
      2 1
      5 10 3 5
      16 6
      47 26
      49 11
      1 38
      4 14
      9 31
      40 42
      36 44
      

      Sample Output
      
      1
      -1
      3
      

      See also: Snakes and Ladders Again


      Added by:abdelkarim
      Date:2012-12-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:The First Palestinian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      13092. Snakes and Ladders Again

      Problem code: PCPC12F


      Snakes and Ladders (or Chutes and Ladders) is an ancient Indian board game regarded today as a worldwide classic. It is played between two or more players on a game board having numbered squares (fields) on a grid. A number of "ladders" and "snakes" (or "chutes") are pictured on the board, each connecting two specific board squares. The object of the game is to navigate one's game piece from the start (Bottom square) to the finish (Top Square), helped or hindered by ladders and snakes, respectively. The historic version had root in morality lessons, where a player's progression up the board represented a life journey complicated by virtues (ladders) and vices (snakes).  If, after throwing a dice, a player's token lands on the lower-numbered end of a "ladder", the player moves his token up to the ladder's higher-numbered square. If he lands on the higher-numbered square of a "snake" (or chute), he must move his token down to the snake's lower-numbered square. If any of those cases takes places, we will call a square unstable. Otherwise it is stable.

      The game is a simple race contest lacking a skill component, and is popular with young children.

      In this problem you’re required to calculate the expected number of 6-sided die throws to move your game piece from the start (bottom square) to the finish (top square).


      Formal game description

      Fields are arranged on an NxM grid and numbered from 1 to N*M. Last field, indicated by N*M, is referred to as Top Square. Each player starts with a token on a square at position "0" (the imaginary space beside the “1” grid field; Bottom Square), which is always stable. So in total we have N*M+1 fields. In every turn player throws the die and moves up by the given number of squares. If that would result in a field higher than Top Square, then token is not moved. If the square that token ends on is unstable, it is moved as indicated by ladder or snake. This is repeated until token is placed a stable field. You can assume that a stable field can be reached from any field on the board. If this final, stable field is the Top Square, game ends and player wins.


       PIC


      Input Specification

      Input contains multiple test cases First line of each test case contains integers N, M, S, L. where n and m are the board dimensions, N (0 < N <= 10), M (0 < M <= 10), and S and L are number of snakes and ladders respectively. Next S lines describes snakes. Each line contains two integers: h and t, where h is the snake’s head position and t is the snake tail position. (0 < t < h <=N*M), Next L lines describes ladders. Each line contains two integers: p and q where p is the ladder’s bottom and q is the ladder’s top (0 < p < q < N*M).

      The input will be terminated by the end of file.

      NOTE! There could be more snakes and/or ladders leading from a single field. In such a case use the last snake/ladder specified in the input.


      Output Specification

      Print one number per test case (each in separate line), expected number of dice throws needed to reach the Top Square. It's guaranteed that the Top is always reachable. Your round the result to exactly 3 decimal places.


      Sample Input
      
      5 10 3 5
      16 6
      47 26
      49 11
      1 38
      4 14
      9 31
      40 42
      36 44
      

      Sample Output
      
      30.198
      

      Before you solve this you may want to try: Snakes and Ladders


      Added by:abdelkarim
      Date:2012-12-28
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:The First Palestinian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      13093. Mosque

      Problem code: PCPC12G

       

      Islam prayer in congregation (jama'ah) is considered to have more social and spiritual benefit than praying by oneself. When praying in congregation, the people stand in straight parallel rows behind the chosen imam, facing Qibla (The Qibla is the direction that should be faced when a Muslim prays). Sometimes some of these rows are cut by poles (n poles divide the row into n+1 parts), and some of the rows do not contain poles (the whole row is just one part). Muslims prefer to stand in the rows which are free of poles, so they may leave one row empty and use the next one if it has fewer poles, but they can’t leave two consecutive rows empty.
      A mosque is divided into n rows each row may contains one or more poles. Each row free of poles can have m Muslims and every additional pole decreases this number by 2, so if the row contains 2 poles, number of Muslims who can stand in this row is m - 4.
      In this problem you are required to arrange the Muslims in rows where number of poles cutting these rows is minimized.
      Input Specification
      Input contains multiple test cases. Each test case will start with the number of n (0<n<=100), m (10<=m<=200), and t (0<t<=20,000), where n is number of rows, m is number of Muslims per row, and t is the total number of people in the mosque, followed by n lines each containing the number of poles in each row. It is guaranteed that the mosque always can fit all the Muslims.  Input will be terminated by end of file.
      Output Specification
      For each test case, print one line containing the minimum number of poles cutting the prayer rows.
      Sample Input
      8 10 26
      1
      2
      0
      2
      1
      1
      1
      2
      8 10 27
      1
      2
      0
      2
      1
      1
      1
      2
      8 10 27
      1
      2
      1
      2
      2
      1
      1
      1
      Sample Output
      2
      3
      5

       

      Islam prayer in congregation (jama'ah) is considered to have more social and spiritual benefit than praying by oneself. When praying in congregation, the people stand in straight parallel rows behind the chosen imam, facing Qibla (The Qibla is the direction that should be faced when a Muslim prays). Sometimes some of these rows are cut by poles (n poles divide the row into n+1 parts), and some of the rows do not contain poles (the whole row is just one part). Muslims prefer to stand in the rows which are free of poles, so they may leave one row empty and use the next one if it has fewer poles, but they can’t leave two consecutive rows empty.


      A mosque is divided into n rows each row may contains one or more poles. Each row free of poles can have m Muslims and every additional pole decreases this number by 2, so if the row contains 2 poles, number of Muslims who can stand in this row is m - 4.


      In this problem you are required to arrange the Muslims in rows where number of poles cutting these rows is minimized.

      Input Specification

      Input contains multiple test cases. Each test case will start with the number of n (0<n<=100), m (10<=m<=200), and t (0<t<=20,000), where n is number of rows, m is number of Muslims per row, and t is the total number of people in the mosque, followed by n lines each containing the number of poles in each row. It is guaranteed that the mosque always can fit all the Muslims.  Input will be terminated by end of file.

      Output Specification

      For each test case, print one line containing the minimum number of poles cutting the prayer rows.

      Sample Input

      8 10 26

      1

      2

      0

      2

      1

      1

      1

      2

      8 10 27

      1

      2

      0

      2

      1

      1

      1

      2

      8 10 27

      1

      2

      1

      2

      2

      1

      1

      1

      Sample Output

      2

      3

      5

       

       


      Added by:abdelkarim
      Date:2012-12-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:The First Palestinian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      13094. Beggars

      Problem code: PCPC12H


       Begging nowadays is an organized profession and team work is extremely important. Beggars target special occasions to maximize revenue, such as Muslim Friday prayers. They wait outside the mosque until the prayer ends and ask people for money as people leave the mosque. In this problem you are to help two beggars to maximize their revenue on Friday after the Friday prayers. These beggars are experienced and know everything they need, specifically they know exactly when each mosque ends the prayer and how much money they will gain if at least one of them stands in front of that mosque when the prayer ends (there is no use if both of them stand at the same mosque).

       

      In their town there are n mosques on a straight line and you will be given the x coordinate for each mosque. The time needed for a beggar to travel from one mosque a to another mosque b is |xa-xb| units of time. As you know, these baggers are professionals and take no time to collect the money from a mosque if they happen to be there when the prayer ends, and can immediately start moving to another mosque.

       

      Of course the beggars can choose to initially start from any mosque. Your task here is to compute the maximum amount of money they can collect together.

      Input Specification

      Input contains multiple test cases. Each test case starts with number of mosques 1<=n<=100, followed by n lines. Each line consists of three 32-bits signed integers x, t, and m representing the x-coordinate of the mosque, the time when the prayer ends, and the amount of money that can be collected from this mosque. The input will be terminated when n equals 0 and should not be treated as a test case.

      Output Specification

      For each test case you should print a single integer, the maximum amount of money that can be collected by the two beggars.

      Sample Input

      3

      7 6 19

      2 3 18

      9 8 13

      4

      1 4 5

      3 4 5

      2 5 5

      4 5 5

      4

      1 4 5

      3 4 5

      2 5 5

      5 5 5

      0

      Sample Output

      50

      20

      15


      Added by:abdelkarim
      Date:2012-12-28
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:The First Palestinian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      13095. peaks

      Problem code: PCPC12I

       

      You are given a sequence of numbers s, you are required to find 3 indices i, j, k, where i < j < k and (s[i] <= s[j] >= s[k] or s[i] >= s[j] <= s[k]) if there are many solutions you should find the one where |s[i]-s[j]| + |s[j]-s[k]| is maximized, if there are still many solutions you should find the one which comes earlier in order (i.e. i1, j1, k1, comes before i2, j2, k2, if i1<i2, or if i1=i2, and j1<j2, or if i1=i2, j1=j2, and k1<k2 ).
      Input Specification
      The problem will be tested on multiple test cases, the first line of the input contains an integer n representing the size of the sequence (3<=n<=10^6) (^ means power), then followed by n integers, All numbers in this sequence do not exceed 10^6 in absolute value. The input is terminated by end of file.
      Output Specification
      For each test case, output a line containing the 3 indices of the pattern i, j, k space separated. If there is no such pattern output -1 instead.
      Sample Input
      7
      2 3 1 7 2 4 8
      5
      2 3 5 7 1
      Sample Output
      3 4 5
      1 4 5
       

       



      You are given a sequence of numbers s, you are required to find 3 indices i, j, k, where i < j < k and (s[i] <= s[j] >= s[k] or s[i] >= s[j] <= s[k]) if there are many solutions you should find the one where |s[i]-s[j]| + |s[j]-s[k]| is maximized, if there are still many solutions you should find the one which comes earlier in order (i.e. i1, j1, k1, comes before i2, j2, k2, if i1<i2, or if i1=i2, and j1<j2, or if i1=i2, j1=j2, and k1<k2 ).

      Input Specification

      The problem will be tested on multiple test cases, the first line of the input contains an integer n representing the size of the sequence (3<=n<=10^6) (^ means power), then followed by n integers, All numbers in this sequence do not exceed 10^6 in absolute value. The input is terminated by end of file.

      Output Specification

      For each test case, output a line containing the 3 indices of the pattern i, j, k space separated. If there is no such pattern output -1 instead.

      Sample Input

      7

      2 3 1 7 2 4 8

      5

      2 3 5 7 1

      Sample Output

      3 4 5

      1 4 5

       

       

       


      Added by:abdelkarim
      Date:2012-12-28
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:The First Palestinian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      13096. Amr Samir

      Problem code: PCPC12J

       

      Amr started to learn division. So he gave a list of numbers to his friend and asked him to find all the divisors of each number in the given list. Now Amr has a new list of numbers containing all divisors of his original list. 
      As Amr loves playing with numbers, he now thinks about the repeated numbers in the new list of divisors. However this time Amr is interested in the luckiest divisor!
      Lucky divisor is defined by Amr as follows: a divisor D is lucky if D divides f, where f is the frequency of this number D in the new list. Obviously f must be greater than zero.
      The luckiest divisor is the divisor D that divides f where f is the maximum and D is the smallest one.
      Since Amr is too lazy to write a program that solves this problem, he decided to submit it to the PCPC chief judge to put it as a problem for the teams to write a solution to it. Can you write this program for Amr?
      Input Specification
      The first line contains a positive integer t <= 100, then follow t test cases. Each test case start with a line containing a single positive integer n <= 10000 number of divisors in Amr’s new list, then follows n positive integers a1, ai, …an (ai<= 100).
      Output Specification
      Your code should print an integer for each test case representing the luckiest divisor or -1 if there is no lucky divisor.
      Sample Input
      2
      5
      2 2 3 3 3
      7
      2 2 2 2 3 3 3
      Sample Output
      3
      2

       

      Amr started to learn division. So he gave a list of numbers to his friend and asked him to find all the divisors of each number in the given list. Now Amr has a new list of numbers containing all divisors of his original list. 

      As Amr loves playing with numbers, he now thinks about the repeated numbers in the new list of divisors. However this time Amr is interested in the luckiest divisor!

      Lucky divisor is defined by Amr as follows: a divisor D is lucky if D divides f, where f is the frequency of this number D in the new list. Obviously f must be greater than zero.

      The luckiest divisor is the divisor D that divides f where f is the maximum and D is the smallest one.

      Since Amr is too lazy to write a program that solves this problem, he decided to submit it to the PCPC chief judge to put it as a problem for the teams to write a solution to it. Can you write this program for Amr?

      Input Specification

      The first line contains a positive integer t <= 100, then follow t test cases. Each test case start with a line containing a single positive integer n <= 10000 number of divisors in Amr’s new list, then follows n positive integers a1, ai, …an (ai<= 100).

      Output Specification

      Your code should print an integer for each test case representing the luckiest divisor or -1 if there is no lucky divisor.

      Sample Input

      2

      5

      2 2 3 3 3

      7

      2 2 2 2 3 3 3

      Sample Output

      3

      2

       

       


      Added by:abdelkarim
      Date:2012-12-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:The First Palestinian Collegiate Programming Contest









      SPOJ Problem Set (classical)

      13098. Yet Another Conic Section Problem

      Problem code: CONIC

      ...

      The conic sections are the nondegenerate curves generated by the intersections of a plane with one or two nappes of a cone. For a plane perpendicular to the axis of the cone, a circle is produced. 

      For a plane that is not perpendicular to the axis and that intersects only a single nappe, the curve produced is either an ellipse or a parabola. The curve produced by a plane intersecting both nappes is a hyperbola. The conic sectin can been denoted as the general form form:

      ax^2+2bxy+cy^2+dx+ey+f = 0

      In this problem, your task is to test weather two conic sections are congruent in C^2 space. Two geometric object are called congruent, if, and only if, one can be transformed into the other by an isometry, i.e., a combination of translations, rotations and reflections.

      In this problem, your task is to test weather two conic sections are congruent in C^2 space.
      Two geometric object are called congruent, if, and only if, one can be transformed into the other by an isometry, i.e., a combination of translations, rotations and reflections.In this problem, your task is to test weather two conic sections are congruent in C^2 space. Two geometric object are called congruent, if, and only if, one can be transformed into the other by an isometry, i.e., a combination of translations, rotations and reflections.

      Input

      T (The first line is the case number, T <= 1000)

      (For each case ... )

      a1 b1 c1 d1 e1 f1 .. (six real number: the 1st conic section)

      a2 b2 c2 d2 e2 f2 .. (the 2nd one .. .)

       

       

      Output

      (For each case .. .)

      Y / N ( 'Y' for congruence and 'N' for not.

      Example

      Input:
      2
      2.00 0.00 1.00 0.00 0.00 2.00
      1.00 0.00 2.00 0.00 0.00 2.00
      1.00 0.00 1.00 0.00 0.00 -1.00
      1.00 0.00 1.00 2.00 0.00 0.00
      Output:
      Y
      Y

      Added by:xiaodao
      Date:2012-12-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      13105. DNA

      Problem code: MUTDNA

       

      Biologists have discovered a strange DNA molecule, best described as a sequence of N characters from 
      the set {A, B}. An unlikely sequence of mutations has resulted in a DNA strand consisting only of A‟s. 
      Biologists found that very odd, so they began studying the mutations in greater detail.
      They discovered two types of mutations. One type results in changing a single character of the 
      sequence (A → B or B → A). The second type changes a whole prefix of the sequence, specifically 
      replacing all characters in positions from 1 to K (for some K between 1 and N, inclusive) with the other 
      character (A with B, B with A).
      Compute the least possible number of mutations that could convert the starting molecule to its end 
      state (containing only A characters). Mutations can occur in any order

       

      Biologists have discovered a strange DNA molecule, best described as a sequence of N characters from 

      the set {A, B}. An unlikely sequence of mutations has resulted in a DNA strand consisting only of A's. 

      Biologists found that very odd, so they began studying the mutations in greater detail.

      They discovered two types of mutations. One type results in changing a single character of the 

      sequence (A → B or B → A). The second type changes a whole prefix of the sequence, specifically 

      replacing all characters in positions from 1 to K (for some K between 1 and N, inclusive) with the other 

      character (A with B, B with A).

      Compute the least possible number of mutations that could convert the starting molecule to its end 

      state (containing only A characters). Mutations can occur in any order

       

       

      Input

       

      The first line of input contains the positive integer N (1 ≤ N ≤ 1 000 000), the length of the molecule.

      The second line of input contains a string with N characters, with each character being either A or B. 

      This string represents the starting state of the molecule.

       

      Output

      The first and only line of output must contain the required minimum number of mutations.

      Example

      Input 1:
      4
      ABBA
      
      Output 1:
      2
      Input 2:
      5
      BBABB
      
      Output 2:
      2
      
      Input 3:
      12
      AAABBBAAABBB
      
      Output 3:
      4

      Added by:UNI Training
      Date:2012-12-31
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2011-2012 Contest #5









      SPOJ Problem Set (classical)

      13106. KOSARE

      Problem code: KOSARE

       

      Mirko found N boxes with various forgotten toys at his attic. There are M different toys, numbered 1 
      through M, but each of those can appear multiple times across various boxes.
      Mirko decided that he will choose some boxes in a way that there is at least one toy of each kind
      present, and throw the rest of the boxes away.
      Determine the number of ways in which Mirko can do this.

       

      Mirko found N boxes with various forgotten toys at his attic. There are M different toys, numbered 1 

      through M, but each of those can appear multiple times across various boxes.

      Mirko decided that he will choose some boxes in a way that there is at least one toy of each kind

      present, and throw the rest of the boxes away.

      Determine the number of ways in which Mirko can do this.

       

       

      Input

       

      The first line of input contains two integers N and M (1 ≤ N ≤ 1 000 000, 1 ≤ M ≤ 20).

      Each of the following N lines contains an integer Ki (0 ≤ Ki ≤ M) followed by Ki distinct integers from 

      interval [1, M], representing the toys in that box.

       

      Output

      The first and only line of output should contain the requested number of ways modulo 1 000 000 007.

      Example

      Input 1:
      3 3
      3 1 2 3
      3 1 2 3
      3 1 2 3
      
      Output 1:
      7
      
      Input 2:
      3 3
      1 1
      1 2
      1 3
      
      Output 2:
      1
      
      Input 3:
      4 5
      2 2 3
      2 1 2
      4 1 2 3 5
      4 1 2 4 5
      
      Output 3:
      6
      

      Added by:UNI Training
      Date:2012-12-31
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2011-2012 Contest #6









      SPOJ Problem Set (classical)

      13116. Dividing Xorland

      Problem code: PUCMM333



       

      Xorland is a beautiful Kingdom located in the northern part of the Hispaniola Island. You can picture it as a perfect n x n square. Incredibly, n^2 people live there, each in a perfect 1x1 square. They all have an integer spirit in the range [1, 10^6]. The King died recently and, as is custom, Xorland must be divided into three parts.


      Xorlandic people love to apply the Xor operation on their spirits, so it is normal to expect them to use it also to divide the land. Xorland must be divided by two parallel lines. These parallel lines must also be parallel to one side of the square. Each part will be non-empty. To divide the land, this is what they do:


      (1) Place two parallel lines inside the square.

      (2) Construct a non-empty subset of the spirits of the first part and call it A.

      (3) Construct a non-empty subset of the spirits of the second part and call it B.

      (4) Construct a non-empty subset of the spirits of the third part and call it C.

      (4) Apply the Xor operation on A, on B and on C.

      (5) Find the value of Xor(A) + Xor(B) + Xor(C) and call it SUM.

      (6) Eat and Drink joyfully for SUM days straight.


      Between us, Xorlandic people LOVE eating and drinking! That is why they want to find the partition that yields the greatest sum. Help them! Write a program that finds this number.


      Input

      The first line of input contains N (3 <= N <= 5), the length of the sides of the squared area. Then follow N lines, each bearing a spirit. Each spirit will be a positive integer in the range [1, 10^6].


      Output

      Output the greatest sum possible.


      Sample Cases


      Input

      3

      1 1 1

      2 2 2

      3 3 3


      Output

      9

      In this case, the optimal choice is to divide vertically. Column 1 is {1, 2, 3}; Column 2 is {1, 2, 3} and Column 3 is {1, 2, 3}. Taking A = {3}, B = {3} and C{3} we get 3 * Xor{3} = 9, the optimal answer. Note that other subsets may yield 9 as well.


      Added by:Olson Ortiz
      Date:2013-01-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Olimpiada de Programación PUCMM ACM-ISC 2013









      SPOJ Problem Set (classical)

      13117. White Hats

      Problem code: PUCMM334


      There is a number of people in a room (between 2 and 100), and each of them wears a hat which is either black or white. Every person counts the number of other people wearing white hats. You are given the number counted by each person. Print the total number of people wearing white hats, or -1 if count doesn't correspond to a valid situation.

      Input

      The first line is N, the number of persons.

      Then N space separaten integers follow, each one denoting the number of white hats each person sees.

      Output

      Print the total number of people wearing white hats, or -1 if count doesn't correspond to a valid situation.

      Example

      Input:                              Output:
      3 2
      2 1 1

      Input:
      Output:
      3 3
      2 2 2

      Input:
      Output:
      2 0
      0 0

      Input: Output:
      2 -1
      10 10

      Added by:Olson Ortiz
      Date:2013-01-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Olimpiada de Programación PUCMM ACM-ISC 2013









      SPOJ Problem Set (classical)

      13118. The Rook and The Rookette

      Problem code: PUCMM335



      Once upon a time, there was a noble rook called Danny who lived in a normal 8x8 chessboard. All squares lived in peace and Danny was a joyful rook, moving either vertically or horizontally across the board, never going off limits. Oh boy did he enjoy moving! He spent all days visiting the 64 squares and bringing flowers and other gifts to them. All squares loved Danny very much, even though they felt sorry for him because there was no Rookette for him to date.


      The King took notice of the squares’ gossiping and he did something very remarkable. He arranged Danny a date with María, a Rookette from another chessboard. So, María stepped in one of the squares and Danny went immediately after her. However, the King made sure it wasn’t easy for Danny. He told him:

      “Danny, I love you very much. We all do. What I am doing right now is because I love you.”

      Danny was perplexed, without a clue. “What do you mean, Oh righteous King?”

      Suddenly, the King arranged M bombs in M squares. “In life, you must work hard to achieve your dreams. I cannot just hand María over to you. You need to earn your right to date her.”

      “Oookkkk…” said Danny, in a doubtful tone.

      “I may also step in one of the squares. Go after her!”


      And off went Danny. Assume Danny is very desperate to meet her, so he will try to get to her in the shortest possible way. The King  wants to prolong Danny’s path (maybe to have him think thoroughly about becoming a man). The King needs to decide where he will step in, he has N empty squares to choose from.


      Write a program that outputs the length of the path should both Danny and the King act optimally. There will always be a path.


      Input

      There is a single test case per input file. The first 8 lines contain 8 characters each, and they represent the initial state of the chessboard. The lines are enumerated from 0 to 7 and so are the 8 characters of each line. The character at position (i, j)  can be one of the following:

      • ‘.’  : an empty square

      • ‘#’ : a bomb

      • ‘?’ : the princess

      • '$': Danny

      The following line contains N (0 <= N <= 10), representing the number of empty squares the King has to choose from. Then follow N lines. Each of these lines contain two integers Xi, Yi (0 <= Xi, Yi <= 7), the position of an empty square.


      Output

      Write a single line containing the length of the path Danny takes to reach María, if both Danny and the King act optimally.


      Sample Input

      $......?

      ########

      ########

      ########

      ########

      ########

      ########

      #######.

      1

      7 7


      Sample Output

      7



      Added by:Olson Ortiz
      Date:2013-01-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      13120. FizzBuzz Happy 2013

      Problem code: ADITYA13

      Having cleared the ACM ICPC online round you receive a job offer of teaching JAVA programming to High School Students of Byteland. You gladly take the job offer and after a few days of teaching you give the students a program to write. You ask them to write a FIZZBUZZ program. They are either too smart or too lazy. They argue that it is too difficult and callenge you to do better than that without using any english alphabets. You consult senior programmer Mitch who suggests you a way out of the problem. "Do it in BF," he says. Tjandra suggests you do it in Whitespace.

      Input

      Two space separated one digit integers A and B.Then a newline.Then a strings C of maximum length 5 followed by a newline. Then another string D of max length 5 followed by a newline. It is guaranteed that gcd(A,B)<A and gcd(A,B)<B. Also the strings comprise only alphanumeric characters

      Output

      For all numbers in the set [1,99] print C if the number is divisible by A, print D if divisible by D, print C concat D if divisible by both and the number (with preceding zeroes if required) if it divisible by neither A nor B.

      Example

      Input:
      2 3
      Happy
      2013
      
      Output:
      01
      
      Happy
      2013
      Happy
      05
      Happy2013
      07
      ..........and you get the idea
      Wishing all of you a HAPPY NEW YEAR 2013......:)

      Edit: 05-01-2013
      I am giving you all a link to mostafa_36a2's solution. You would be pleased....
      Download the encrypted text solution

      Added by:Aditya Pande
      Date:2013-01-01
      Time limit:2s-13s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:BF WSPC
      Resource:Own









      SPOJ Problem Set (classical)

      13150. Magic Sticks

      Problem code: STICKS

      We have N sticks are lined up in a queue with different distances between them , and each stick is leaning on the left stick (look at figure) .

      L : the length of the stick.

      D : the distance between the stick head point and the left one head point.

      We catch the first stick (that length L0) and keep it vertical.

      determine the total time that expected to fall down all sticks if the first stick moved away (assume that each stick's bottom head will not displaced , and when the stick reach ground it will vanish and the right one start to fall ).

      you will have V (linear velocity for the head point) at time = 1 second (from the stick start to fall , if we assume that stick will not stop and keeping same motion type).

      suppose that wight force has stable effect on the stick in dirction and value

       

      Input

      the first line : N , L0

      next N-1 Line : Lk , Dk , Vk(1)

      Output

      One number T (total time in millisecond).

      Example

      Input:
      2 8.75
      10 8.7 25000 Output: 2



      2 <= N <= 5000
      1 <= L <= 1000000
      1 <= V <= 1000000

      .

      Added by:omar alkattan
      Date:2013-01-04
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      13156. Tom and Jerry

      Problem code: MAY99_1

       

      Tom and Jerry is a favourite cartoon of many of us . One day Manku was sitting watching an episode of Tom and Jerry where he found that Tom and Jerry both entered a rectangular maze and Tom was after Jerry , but Jerry being the hero , returned safely.

      Manku then start making different scenarios and wondering that if Jerry moves optimally and Tom knows entire path that Jerry is expected to take, then will Jerry be able to escape out of the maze or not ??

      Moreover Manku added 1 rule to this that if Jerry moves from position A to position B , then at any cost he is not allowed to return from position B to position A.

      Jerry , if is at the escape positions of the maze, in the beginning , then he can't exit from that same position .
      Moreover he can't escape if he is caught by Tom at any position .

      Jerry and Tom can move up , down , left , right or wait on their position.

      If it is guaranteed that either Jerry would escape or Tom would catch him .
      All characters at row = 0 or row = m-1 or column = 0 or column = n-1 , which are '.' or 'J' or 'T' are escape positions.

      Input

      Each input file consist of only 1 test case.

      1st line of input contains 2 no's m and n , both integers are less than or equal to 100 , the size of the rectangular maze.

      Then m lines follows containing n characters each.
      . means an open space so that tom or jerry can move there
      # means a closed place
      T means starting position of Tom
      J means starting position of Jerry

      Output

      Output single line containing a character W and integer D
      where W is 'J' if Jerry can escape or else 'T'
      and D is the minimum time taken by Jerry to escape ( if W is 'J') or maximum time for which Jerry is alive ( if W is 'T')

      Example

      Input 1:
      
      4 4
      #..J
      #...
      #.T.
      ####

       Output 1:
      J 1

      Input 2:
      
      6 3
      ###
      #J#
      #.T
      ###
      ###
      #.#

       Output 2:
      T 2

      Input 3:
      
      7 7
      ......#
      .......
      .......
      ...J...
      ...T...
      .......
      #......

       Output 3: J 3

      Input 4:

      7 7
      #.....#
      #......
      #......
      J......
      #..T...
      #......
      #......

       Output 4: J 4

      Explanation

       

      In 1st Test case Jerry will move 1 step to its left and would escape.

      In 2nd Test case Jerry can't escape so he will remain at its position and will be caught after 2 moves.

      In 3rd Test case jerry will move 3 steps to its left and will escape.

      In 4th Test case jerry will move 1 step to its right and then 3 steps up to escape.

      Added by:Mayank Tuteja
      Date:2013-01-05
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:self problem









      SPOJ Problem Set (classical)

      13165. Totient in permutation (easy)

      Problem code: TIP1

      In number theory, Euler's totient (or PHI function), is an arithmetic function that counts the number of positive integers less than or equal to a positive integer N that are relatively prime to this number N.

      That is, if N is a positive integer, then PHI(N) is the number of integers K for which GCD(N, K) = 1 and 1 ≤ K ≤ N. We denote GCD the Greatest Common Divisor. For example, we have PHI(9)=6.

      Interestingly, PHI(87109)=79180, and it can be seen that 87109 is a permutation of 79180.

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are an integer M.

      Output

      For each given M, you have to print on a single line the value of N, for which 1 < N < M, PHI(N) is a permutation of N and the ratio N/PHI(N) produces a minimum. If there's several answers output the greatest, or if need, "No solution." without quotes.
      Leading zeros are not allowed for integers greater than 0.

      Example

      Input:
      3
      22
      222
      2222
      
      Output:
      21
      63
      291
      

      Explanations : For the first case, in the range ]1..22[, the lonely number n for witch phi(n) is in permutations(n) is 21, (we have phi(21)=12). So the answer is obviously 21.
      For the second case, in the range ]1..222[, there's two numbers n for witch phi(n) is in permutations(n), we have phi(21)=12 and phi(63)=36. But as 63/36 is equal to 21/12, we're taking the greater : 63.
      For the third case, in the range ]1..2222[, there's four numbers n for witch phi(n) is in permutations(n), phi(21)=12, phi(63)=36, phi(291)=192 and phi(502)=250. Within those solutions 291/192 is the minimum, we output 291.

      Constraints

      1 < T < 10^5
      1 < M < 10^7
      

      Code size limit is 10kB ; less than 500B of python3 code can get AC under 2s.
      After that you may try TIP2.
      @Speed addicts : my C code ran in 0.02s, and my fastest python3.2 code ran in 1.21s, (0.90s in py2.7)


      Added by:Francky
      Date:2013-01-06
      Time limit:3s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Extension of Project Euler n°###









      SPOJ Problem Set (classical)

      13166. Totient in permutation (medium)

      Problem code: TIP2

      In number theory, Euler's totient (or PHI function), is an arithmetic function that counts the number of positive integers less than or equal to a positive integer N that are relatively prime to this number N.

      That is, if N is a positive integer, then PHI(N) is the number of integers K for which GCD(N, K) = 1 and 1 ≤ K ≤ N. We denote GCD the Greatest Common Divisor. For example, we have PHI(9)=6.

      Interestingly, PHI(87109)=79180, and it can be seen that 87109 is a permutation of 79180.

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are an integer M.

      Output

      For each given M, you have to print on a single line the value of N, for which 1 < N < M, PHI(N) is a permutation of N and the ratio N/PHI(N) produces a minimum. If there's several answers output the greatest, or if need, "No solution." without quotes.
      Leading zeros are not allowed for integers greater than 0.

      Example

      Input:
      3
      22
      222
      2222
      
      Output:
      21
      63
      291
      

      Explanations : For the first case, in the range ]1..22[, the lonely number n for witch phi(n) is in permutations(n) is 21, (we have phi(21)=12). So the answer is obviously 21.
      For the second case, in the range ]1..222[, there's two numbers n for witch phi(n) is in permutations(n), we have phi(21)=12 and phi(63)=36. But as 63/36 is equal to 21/12, we're taking the greater : 63.
      For the third case, in the range ]1..2222[, there's four numbers n for witch phi(n) is in permutations(n), phi(21)=12, phi(63)=36, phi(291)=192 and phi(502)=250. Within those solutions 291/192 is the minimum, we output 291.

      Constraints

      1 < T < 10^2
      1 < M < 10^12
      

      Code size limit is 10kB ; the upper bound was set at 10^12 to make a (C/pascal/...)-solution easier to write. Constraints allow Python3 users to get AC under 3s (with a sub-optimal solution).
      If if you get TLE, you should try first TIP1.
      If it's too easy for you TIP3 is made for you ;-)


      Added by:Francky
      Date:2013-01-06
      Time limit:5s
      Source limit:10000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:TIP1 extension









      SPOJ Problem Set (classical)

      13167. Totient in permutation (hard)

      Problem code: TIP3


      In number theory, Euler's totient (or PHI function), is an arithmetic function that counts the number of positive integers less than or equal to a positive integer N that are relatively prime to this number N.

      That is, if N is a positive integer, then PHI(N) is the number of integers K for which GCD(N, K) = 1 and 1 ≤ K ≤ N. We denote GCD the Greatest Common Divisor. For example, we have PHI(9)=6.

      Interestingly, PHI(87109)=79180, and it can be seen that 87109 is a permutation of 79180.

      Input

      There is only one number M.

      Output

      For the given M, you have to print on a single line the value of N, for which 1 < N < M, PHI(N) is a permutation of N and the ratio N/PHI(N) produces a minimum. If there's several answers output the greatest, or if need, "No solution." without quotes.
      Leading zeros are not allowed for integers greater than 0.

      Example

      Input:
      22
      
      Output:
      21
      
      
      Input:
      222
      
      Output:
      63
      
      
      Input:
      2222
      
      Output:
      291
      

      Explanations : For the first case, in the range ]1..22[, the lonely number n for witch phi(n) is in permutations(n) is 21, (we have phi(21)=12). So the answer is obviously 21.
      For the second case, in the range ]1..222[, there's two numbers n for witch phi(n) is in permutations(n), we have phi(21)=12 and phi(63)=36. But as 63/36 is equal to 21/12, we're taking the greater : 63.
      For the third case, in the range ]1..2222[, there's four numbers n for witch phi(n) is in permutations(n), phi(21)=12, phi(63)=36, phi(291)=192 and phi(502)=250. Within those solutions 291/192 is the minimum, we output 291.

      Constraints

      1 < M < 10^27
      

      If you got TLE, you should consider before TIP2. Enjoy.
      Warning : don't try to investigate the input number, judge is strict and interactive ; test case is randomly changing, staying equivalent in difficulty. Please don't use spurious spaces and end your answer with '\n' ; e.g. "21\n" awaited for the sample.
      There is many ways to optimize the solution for this problem, to get AC here, you'll need to find many of them.
      Time limit allows python3 solutions.
      There is different judges, time is the sum of them.


      Added by:Francky
      Date:2013-01-06
      Time limit:20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:TIP2









      SPOJ Problem Set ()

      13223. The BrainFast Processing! Classical version

      Problem code: FAST_BF

      Warning: Only Brainf**k language is allowed.

      After I solve this problem in 0.00s using BF , I have an idea to set new BF problems, now here I come Wink

      The task is simple, given a <string>(1≤"length of string"≤1000) just check if the string is palindrome or not.

      The string contains character in range ASCII(32)≤char≤ASCII(126)

      Input

      The first line, there is an integer T(1≤T≤1000) denoting number of test cases then you should process only next T lines, each line is a <string> terminated by new line character ('\n') ASCII(10)

      Output

      For each test case:

      if <string> is palindrome, output: "<string>" is palindrome

      else, output: "<string>" is not palindrome

      remember to put '\n' after each test case

      Example

      Input:
      11
      abba
      abba 
       abba
       abba 
      Tjandra Satria Gunawan
      Tjandra Satria Gunawan nawanuG airtaS ardnajT
      
      ()
      ((
      kasur ini rusak
      Kasur ini rusak
      x
      Don't process this case because T is 11
      And also this problem use exact judge so be careful put space and '\n'
      Only brainf**k is allowed
      and soure limit is 1500 bytes
      Output:
      "abba" is palindrome
      "abba " is not palindrome
      " abba" is not palindrome
      " abba " is palindrome
      "Tjandra Satria Gunawan" is not palindrome
      "Tjandra Satria Gunawan nawanuG airtaS ardnajT" is palindrome
      "()" is not palindrome
      "((" is palindrome
      "kasur ini rusak" is palindrome
      "Kasur ini rusak" is not palindrome
      "x" is palindrome

       

      Time limit ~2x My fastest BF code

      If you TLE here, you may try this problem first.

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-01-10
      Time limit:100s
      Source limit:1500B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BF
      Resource:The Mirror of Galadriel Problem plus my own idea ;-)









      SPOJ Problem Set (classical)

      13303. Tic-tac-toe 3

      Problem code: OVOXO


      Bored to death working at the Byteland Office...your colleagues have resorted to game of crosses Xs and naughtd Os or Tic-tac-toe. One of them keeps on losing and is tired of the jokes. He plans to have an Android app in his phone to help him out. He is your good friend and seeks your assistance. "Treat at ANC is guaranteed", he says.

      He also is very frugal when it comes to memory usage. So please don't write a long if else chain...cause you have to do the task within 999 bytes

      Input

      An integer T - the number of test cases. (T<1000). T test cases follow.

      Each test case comprises 3 strings each separated by newline and containing exactly 3 characters(either 'X','O' or '_') per line. An empty line follows each test case. Each input position is guaranteed to be a valid tic tac toe position such that the game is still not over.

      Output

      For each test case print "WON" if it is a sure shot winning position. Else print "CONTINUE". Then output the game after having made your move. If more than one move are equally good try playing the move on the first empty spot.

      Example

      Input:

      2
      OOX
      OX_
      __X
      
      XX_
      XOO
      _O_
      
      

      Output:

      WON
      OOX
      OXX
      __X
      WON
      XXX
      XOO
      _O_
      

      Info

      1) iguaranteed always to be X's move (it is the standard) and whose move it currently is can be computed... 
      2) winning position is meant for the current player 
      3) winning in lesser number of moves is better and drawing is better than losing as in general AI 
      4) you need to print the board as it looks after making the best move 
      5) print WIN if the current player can win in the case when both players play optimally from here on... 
      __X

      Added by:Aditya Pande
      Date:2013-01-14
      Time limit:1s
      Source limit:999B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:TOE2









      SPOJ Problem Set (classical)

      13362. Median of sub-sequences

      Problem code: KMEDIAL


      Let a given sequence S (of length n) of positive integers be called x-medial (where x is a positive integer) if:

      1. n is odd, and the median of the sequence (the ((n+1)/2)th largest term) equals x. OR
      2. n is even, and both the central terms ( (n/2)th largest and (n/2+1)th largest) are equal to x.

      Given a sequence A (of length N) of positive integers and an integer k, find out how many of its sub-sequences are k-medial.

      A sub-sequence of A is any sequence {A[i], A[i+1], A[i+2]... , A[j]}, where 0 ≤ i ≤ j < N.

      Input

      The first line contains T (T≤15), the number of test cases.

      Each test case consists of 2 lines. The first line contains the numbers N (1≤N≤105) and k (1≤k≤109), seperated by a single space.

      The next line contains the sequence A (N terms, each ≤ 109,  seperated by single spaces between them).

      Output

      Output T lines, each containing a single integer, equal to the number of k-medial sub-sequences.

      Example

      Input:
      2
      3 5
      17 5 2
      5 2
      1 2 2 3 7
      Output:
      2
      7

      Added by:Anil Shanbhag
      Date:2013-01-15
      Time limit:6s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      13363. WIND VANE

      Problem code: WINDVANE


      Problem Statement:

      Wind vane is an instrument for showing the direction of the wind.

       

      Dream city is in the shape of a matrix of dimensions mxn. To monitor the direction of the wind in the city, wind vanes are placed in every unit cell of the city. According to the direction of the wind, these wind vanes turn themselves. Lets assume that there are only 4 directions North, East, West and South denoted by (‘N’,’E’,’W’,’S’). We know the initial direction of the wind vanes.

      We denote the direction of change of wind by 0 (clockwise) and 1 (anti-clockwise)

      Function “Change(x1,y1,x2,y2,direction)”, changes the direction of the vanes in the sub-matrix (from x1,y1 to x2,y2) in the specified ‘direction’

      (for example if the initial state of a cell is ‘N’ and the direction is clockwise, then the cell changes to ‘E’)

      The ‘Change’ may occur any time. We need to know the direction of the wind at any unit cell at any instant.

      Direction (x,y) should print the direction of the vane at the cell (x,y).

       

      Input:

      The first line of the input consists two integers m and n - the dimentions of the city. Then follows the description of the matrix which denotes the direction of the vanes. The next line contains an integer c, the number of commands to process. Each command can be either of the format "C x1 y1 x2 y2 d" or "D x y".

      Output:

      Process the commands and print whenever necessary.

       

      Input Constraints:

      1<=m<=1000

      1<=n<=1000

      each character in the matrix is one among {'N','E','W', and 'S'}

      1<=c<=10000

      1<=x1,y1,x2,y2,x,y<=1000

      d= 0(clockwise) or 1(anti-clockwise)

      x1<=x2 y1<=y2

       

      Sample Input:

      5 5
      ESWNE
      NWWWN
      EEESE
      SSWSN
      SNWEN
      5
      C 2 1 4 1 1
      D 3 1
      D 3 3
      C 2 1 5 2 0
      D 3 1

       

      Sample Output:

      N

      E

      E


      Added by:cegprakash
      Date:2013-01-15
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      13364. THE N WITTY FRIENDS

      Problem code: WITTY


      Problem Statement:

      N witty friends went for an outing trip. During the outing they have spent lot of money in lot of places. In some places, a friend (A) spends ‘M’ money for his friend (B).

      An expense is described by  "A spends M$ for B"

      A transaction is described by “X gives K$ to Y”

      You are given all the expenses made by the friends. The outing trip is ended and now you have to find the minimum transactions to be made by the friends to tally the expenses.

       

      Input:

      The first line consists of an integer t, the number of testcases. For each test case, the first line consists of an integer N, the number of expenses made by friends followed by N lines. Each line contains two strings A and B (A!=B) and an integer m, the money A spent for B.

       

      Output:

      For each test case, print the minimum number of transactions required to tally the expenses.

       

      Input Constraints:

      1<=t<=10000

      1<=N<=10

      A!=B

      Each character in A is either 'A' or 'B'

      Each character in B is either 'A' or 'B'

      1<= length of A,B <=2

      1<=m<=10000

       

      Sample Input:

       

      3

      1

      AA BB 10

      3

      A BB 100

      BB AA 100

      AA A 100

      4

      AB BA 100

      BA B 100

      AB B 100

      B A 200

       

      Sample Output:

      1

      0

      1

      Explanation of Testcases:

      Case 1: AA spent 10$ for BB. So one transaction "BB gives 10$ to AA" is needed to tally the expense.

      Case 2: A spent 100$ for BB, BB spent 100$ for AA and AA spent 100$ for A. In this case, no transactions are required as the expenses are already tallied.

      Note: Note that A can spend for B at many places.


      Added by:cegprakash
      Date:2013-01-15
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      13365. Move the boulder

      Problem code: BOULDER

      A huge boulder is somehow blocking a public square. The citizens, each one of them approaching from his/her street, decide to remove it. Each citizen can try to either push the boulder away from him, pull it towards him, or choose to do nothing. (note that the citizens cannot change their direction relative to the boulder). Obviously, they want to remove the boulder as quickly as possible - in other words, they want to maximise the magnitude of the net force they apply. Tell them what this maximum possible magnitude is.

      Input

      The first line contains T (1≤T≤15), the number of test cases.

      For each test case, the first line contains N (1 ≤ N ≤ 105), the number of citizens. Each of the next N lines contains four integers (seperated by single spaces) :

      • The first two integers (each ≤ 109) represent the x and y components (respectively) of the direction in which the citizen would push. If he pulls, it would be in the exactly opposite diretion. Note that this given "direction vector" does not necessarily have magnitude 1. However, its magnitude is indeed a meaningless quantity.
      • The next two integers Fpull and Fpush (1 ≤ Fpull, Fpush ≤ 105) represent the magnitude of the force the citizen applies while pulling and pushing, respectively.

      Output

      For each test case, output a single decimal number, correct to 6 digits after the decimal point, representing the maximum possible magnitude of resultant force.

      Example

      Input:
      2
      3
      1 0 5 3
      -3 0 12 6
      0 1 4 7
      1
      13 6 58 24
      Output:
      16.5529
      58

      Added by:Anil Shanbhag
      Date:2013-01-15
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      13367. EVEN COUNT

      Problem code: GEEKOUNT

      Problem Statement:

      Let f(x) be the product of digits of a number.

      Given L and R, find the number of values of 'i' such that L <= i <= R and f(i) is even.

       

      Input:

      The first line consists of an integer t, the number of test cases. For each test case, you are given the two integers L and R.

      Output:

      For each test case, print the number of values of 'i' such that L <= i <= R and f(i) is even.

       

      Input Constraints:

      1 <= t <= 100

      1   <=  L   <=  R   <=  1000000000

       

      Sample Input:

       

      2

      2 12

      4 23

       

      Sample Output:

       

      6

      12


      Added by:cegprakash
      Date:2013-01-15
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF
      Resource:problem setter: rkarthikeyan









      SPOJ Problem Set (classical)

      13376. The new President

      Problem code: PRESIDEN

      Finally, it is time to vote for a new president and you are really excited about that. You know that the final results may take weeks to be announced, while you can't really wait to see the results.

      Somehow you managed to get the preferences list for every voter (we don't care how you managed to get this piece of information!). Each voter sorted out all candidates starting by his most preferred candidate and ending with his least preferred one. When voting, a voter votes for the candidate who comes first in his preferences list. For example, if there are 5 candidates (numbered 1 to 5), and the preferences list for one voter is [3, 2, 5, 1, 4] and the current competing candidates in the voting process are candidates 2 and 4, the voter will vote for candidate number 2.

      Here are the rules for the election process:

      1. There are C candidates (numbered from 1 to C), and V voters (V is always an odd number).
      2. The election process consists of up to 2 rounds. All candidates compete in the the first round. If a candidate receives more than 50% of the votes, he wins, otherwise another round takes place, in which only the top 2 candidates compete for the presidency. The candidate who receives more votes than his opponent wins and becomes the new president.
      3. You can safely assume that the given preferences will never cause a situation in which the second and the third candidates from the first round receive the same number of votes.
      4. The voters' preferences are the same in both rounds, and each voter must vote exactly once in each round for a currently competing candidate according to his preferences.

      Given the preferences lists, you need to write a program to figure out which candidate will win and in which round.

      Input

      Your program will be tested on one or more test cases. The first line of the input will be a single integer T, the number of test cases (1$ \le$T$ \le$100). Followed by the test cases, the first line of a test case contains two integers C and V separated by a single space. C and V (1$ \le$CV$ \le$100)represent the number of candidates and voters respectively, followed by V lines each line contains C integers separated by a single space, representing the preferences list for a single voter (the first is his most preferable candidate while the last is his least preferable one). Each integer from 1 to C will appear exactly once in each line.

      Output

      For each test case, print on a single line two integers separated by a single space. The first integer is the ID of the winner candidate (a number from 1 to C), the second integer is cither 1 or 2 indicating whether this candidate will win in the first round or the second one respectively.

      Example

      Input:
      
      2 
      2 3
      2 1
      1 2
      2 1
      3 5
      1 2 3
      1 2 3
      2 1 3
      2 3 1 
      3 2 1
      Output:
      2 1
      2 2

      Added by:Kawmia Institutes
      Date:2013-01-17
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: BF CLPS CLOJ LISP sbcl LISP clisp D ERL FORT ICON ICK LUA NEM NODEJS CAML PRLG SCM guile SCM qobi SED ST TCL WSPC
      Resource:ACM ICPC 2012









      SPOJ Problem Set (classical)

      13381. Manku Word

      Problem code: MAY99_2

      Manku loves Codechef's Lucky Number and now he decided to start Manku words :)

      Manku words are those words which have only letters 'm','a','n','k','u'.

      Generally in english ,
      a comes before k, k comes before m and so on but in Manku's dictionary 'm' comes before 'a' , 'a' comes before 'n' , 'n' comes before 'k' , 'k' comes before 'u'.

      Thus according to manku

      1st manku word is m
      2nd manku word is a
      3rd manku word is n
      4th manku word is k
      5th manku word is u
      6th manku word is mm
      7th manku word is ma
         
      and so on ...       


      Your task is very simple
      For given value of n , write the nth manku word

      1<=n<=10^18

      Input


      First line of input contains an integer t (1<=t<=100)

      Each test case contains an integer n

      Output

      For every test case print the nth manku word on separate line

      Example

      Input:
      
      5
      10
      4
      16
      17
      31 Output:
      mu
      k
      nm
      na
      mmm
         

      Added by:Mayank Tuteja
      Date:2013-01-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:ADA C C++ 4.3.2 C++ 4.0.0-8 JAVA PAS fpc PERL PERL 6 PHP PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:similar to codechef's lucky number









      SPOJ Problem Set (classical)

      13382. Kindergarten Painting Competition

      Problem code: KINDERPC

       

      One of the most anxiously awaited occasions in any school is its annual day. Great excitement and hurried activities are visible all around. The prize-winners and those who are participating in the cultural programme are especially elated. 
      Raheem has volunteered to help organize the event, and he’s in charge of the prize distribution ceremony for the kindergarten painting competition. Before the prizes are announced, the participants will be brought in and seated in the front row. There are N participants, and their paintings have been ranked from 1 to N by the judges (1 being the best). However, since all the entries were amazing, the judges have decided that everyone deserves a prize. So, Raheem has arranged N seats in the front row.
      All was well until Raheem realized that if both the neighbours of a participant (i.e the participants sitting on the chairs adjacent to his/her’s) are ranked higher than him/her, then he/she will feel inferior and start crying (after all he/she is in kindergarten!). Raheem, being a puzzle-lover, wonders how many ways there are to seat the participants in the front row, so that none of them feel inferior. More importantly, Raheem also wants to find out what is the expected number of participants who will feel inferior if they are seated randomly, so that he can have that many people ready to take care of crying kindergarteners. 
      Notes :
      1. Two seatings are different if there is at least one chair which is occupied by different students in the two arrangements.
      2. “Seated randomly” means each arrangement is equally likely to be chosen.
      3. The participants sitting on the leftmost chair and the rightmost chair will never feel inferior, as they have only one neighbour.

      One of the most anxiously awaited occasions in any school is its annual day. Great excitement and hurried activities are visible all around. The prize-winners and those who are participating in the cultural programme are especially elated. 

      Raheem has volunteered to help organize the event, and he’s in charge of the prize distribution ceremony for the kindergarten painting competition. Before the prizes are announced, the participants will be brought in and seated in the front row. There are N participants, and their paintings have been ranked from 1 to N by the judges (1 being the best). However, since all the entries were amazing, the judges have decided that everyone deserves a prize. So, Raheem has arranged N seats in the front row.

      All was well until Raheem realized that if both the neighbours of a participant (i.e the participants sitting on the chairs adjacent to his/hers) are ranked higher than him/her, then he/she will feel inferior and start crying (after all he/she is in kindergarten!). Raheem, being a puzzle-lover, wonders how many ways there are to seat the participants in the front row, so that none of them feel inferior. More importantly, Raheem also wants to find out what is the expected number of participants who will feel inferior if they are seated randomly, so that he can have that many people ready to take care of crying kindergarteners. 

      Notes :

      1. Two seatings are different if there is at least one chair which is occupied by different students in the two arrangements.

      2. “Seated randomly” means each arrangement is equally likely to be chosen.

      3. The participants sitting on the leftmost chair and the rightmost chair will never feel inferior, as they have only one neighbour.

       

      Input

      The first line contains the number of test cases T. T lines follow, one for each test case. Each line contains an integer N, denoting the number of students.

       

      Output

      Output one line for each test case, containing two integers. 

      The first should be the number ways of seating the participants in the front row, so that none of them feel inferior. As this number can be very large, output it modulo 1000000007 (i.e. 10+ 7).

      The second should be the greatest integer less than or equal to the expected number of participants who will feel inferior if they are seated randomly.

       

      Constraints

      0 < T < 20

      0 < N < 10^9

       

      Example

      Input:
      2
      1
      3
      
      Output:
      1 0
      
      4 0
      Explanation:

      In the second test case, there are 2 arrangements in which 1 participant (the one ranked 3rd) feels inferior, namely 132 and 231. In the other 4 arrangements, namely 123, 213, 321 and 312, none of the participants feel inferior. The expected number of participants feeling inferior is 0*4/6 + 1*2/6 = 0.33.


      Added by:Anil Shanbhag
      Date:2013-01-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      13384. Nice Binary Trees

      Problem code: NICEBTRE


       

      For example, the following tree is nice,
      <nice-tree.jpg>
      but the following tree is not.
      <not-nice-tree.jpg>
      The leaves of a nice binary tree are labeled by the letter ‘l’, and other nodes are labeled by the letter ‘n’.
      Given the pre-order traversal of a nice binary tree, you are required to find the depth of the tree.
      Notes : 
      1. The depth of a tree is defined as the length of the longest path with one end at the root.
      2. The pre-order traversal of the tree in the first image above produces the string “nlnnlll”.

      Binary trees can sometimes be very difficult to work with. Fortunately, there is a class of trees with some really nice properties. A rooted binary tree is called “nice”, if every node is either a leaf, or has exactly two children.

      For example, the following tree is nice,

      nice tree

      but the following tree is not.

      not a nice binary tree

      The leaves of a nice binary tree are labeled by the letter ‘l’, and other nodes are labeled by the letter ‘n’.

      Given the pre-order traversal of a nice binary tree, you are required to find the depth of the tree.

      Notes

      1. The depth of a tree is defined as the length of the longest path with one end at the root.

      2. The pre-order traversal of the tree in the first image above produces the string “nlnnlll”.

       

      Input

      The first line contains the number of test cases T. T lines follow. Each line contains a string, which represents the pre-order traversal of a “nice” binary tree. Leaves are represented by the letter ‘l’ and other nodes by the letter ‘n’. The input is guaranteed to be the preorder traversal of a nice binary tree.

       

      Output

      Output one line for each test case, containing a single integer, the depth of tree.

       

      Constraints

      0 < T < 20

      Length of the input string in each test case is at most 10000.

       

      Example

      Input:
      3
      l
      nlnll
      nlnnlll
      
      
      Output:
      0
      2
      3
      

      Added by:Anil Shanbhag
      Date:2013-01-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13388. Easy Jug

      Problem code: MAY99_3

      One day Manku was very thirsty , so he decided to drink exactly z litres of water .
      However , in front of him, there is a well of infinite amount of water and 2 empty jugs of quantity x litres and y litres respectively.


      Now Manku can do the following operations to any jug

      1> Fill it completely from the well
      2> Empty it entirely
      3> Transfer as much water from Jug 1 to Jug 2 , till Jug 1 gets empty or Jug 2 is completely filled.

      Now since he has no measuring device so he will do these operations only to make any of the 2 jug having exactly z litres of water.

      Now Your task is given value of x,y,z , tell whether it is possible for Manku to drink water or not.

       

      Input

      First Line of Input contains t , no. of test cases. (t<=25)

      Then for each test case there are 3 no's x,y,z given in separate line 

      1<=x<=10^8

      1<=y<=10^8

      1<=z<=10^8

       

      Output

      For each test case output  "YES" if manku can drink exactly z litres of water else "NO".

      Example

      Input:
      5
      2 4 3
      2 5 1
      9 3 6
      3 8 7
      6 1 10


       Output: NO
      YES
      YES
      YES
      NO

      Explanation

      In Test case 1 Either Manku can have 2 or 4 litres of water so he cant drink 3 litres

      In Test case 2 Manku can have 1 litre water by doing the following operations

       -> Fill 2 litre Jug

      -> Transfer its water to 5 litre Jug

      -> Again Fill 2 litre Jug

      -> Again Transfer its entire water to 5 litre Jug
      Now 5 litre Jug will have total 4 litre water

      ->Again Fill 2 litre Jug

      -> Now transfer 1 litre water to 5 litre Jug

      because at present 5 litre Jug don't have space for more than 1 litre water
      Now the 2 litre Jug will have only 1 litre water left

      For Test case 3 we will transfer 3 litre water twice from 3 litre jug to 9 litre jug

      For test Case 4 , transfer 3 times water of 3 litre jug to 8 litre jug
      Ultimately 3 litre Jug has 1 litre water left and 8 litre Jug is full
      Now empty 8 litre jug and pour remaining 1 litre of 3 litre jug in it
      Now fill 3 litre jug fully twice and transfer its water to 8 litre jug

      Now 8 litre Jug will have 7 litre water

      For Test case 5, we cant have 10 litre of water in any jug

       


      Added by:Mayank Tuteja
      Date:2013-01-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      13398. Contest Hall Preparation

      Problem code: CONHONPR

      Before the ACM-ACPC regional contest, the site director and the volunteers were very busy preparing for the contest. One of their tasks is to assign a table for each team such that no two teams from
       the same university are adjacent to each other. The site director decided not to waste his time doing this task and asked the judges to do it. The judges thought this could be a good problem to be used in
       the contest problems set. As they were very busy preparing for the contest, the judges decided to solve part of the problem and ask the contestants to solve the rest.

      The judges will generate a number of layouts for the teams assignment to the tables and will ask the contestants to write a program to check whether each of these layouts is valid or not.

       If a layout is not valid the program should count how many different universities have at least two of their teams sitting adjacent to each other. ``Well, you may use those solutions for the next year's contest", 

      said by the chief judge Ahmed Aly to the site director.

      The contest hall can be represented as a 2D grid of N rows with M cells in each row. Each cell in the grid is either occupied by a team or empty. There could be up to 8 teams adjacent to a single team.

       A team may have less than 8 adjacent teams if it is seated next to a hall edge or some of its adjacent cells are empty.

      For example, in the layout shown in the following figure, team E has 7 adjacent teams, named A, B, C, D, F, G and H, while the adjacent teams to team A are B, D and E.

       

      \epsfbox{p6326.eps}

      Input

      Your program will be tested on one or more test cases. The first line of the input will be a single integer T, the number of test cases (1$ \le$T$ \le$100). Followed by the test cases, each one starts with a line containing 2 integers separated by a single space N and M (1$ \le$NM$ \le$100) representing the dimensions of the hall, followed by N lines each line contains M integers separated by a single space, representing the tables assignment in this row. Each integer represents the university ID of the team assigned to this table or `-1' if it is empty. All universities IDs are positive integers not greater than 100.

      Output

      For each test case, print on a single line integer, the number of different universities having at least two of their teams adjacent to each other.

      Sample Input

      3
      3 3
      1 2 3
      2 2 2 
      1 1 1
      3 3 
      1 2 3 
      3 -1 1 
      2 -1 2 
      3 3 
      1 2 3 
      -1 1 5 
      1 2 4

      Sample Output

      2 
      0 
      1

      Added by:Kawmia Institutes
      Date:2013-01-18
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ICPC 2012









      SPOJ Problem Set (classical)

      13399. Rachu

      Problem code: MAY99_4

      Rachu is very happy today beacause its his birthday :D and he has a bday party at home with 'r' friends.

      He went to market to purchase something to eat .(He is really fond of eating :P ).

      At the shop he found muffins at a very reasonable price (ohh!! he loves muffins ;) ).

      He bought 'n' muffins from the shop.

      After reaching home he is wondering that in how many ways  he can distribute these muffins between his friends .

      He shouldn't be rash so he would give atleast 1 muffin to each friend.

      For rest of the muffins left he can distribute it in any manner. He is still wondering the no. of ways in which he can distribute these muffins.

      Help him out by writing a code which calculates the no. of ways the muffins could be distributed and print "-1" (quotes for clarity) if its impossible for him to distribute the muffins.  

       Consider each muffin as similar. The no. of ways could go very large so output the reult after taking a mod with 10000007 .

      Input

      The input consists of 2 integers :
        n : The no. of muffins
        r : The no. of friends

      Output

      The required answer modulo 10000007

      Constraints

      1<= n,r <= 100

      Example

      Input:
      2 1
      
      Output:
      1
      Input:
      4 2
      
      Output:
      
      3

      Explanation

      In 1st case he has 2 muffins and called only 1 friend so he gave both the muffins to him .

      In 2nd case he 1st give 1 muffin each to both.
      Then he can give 0 muffin to 1st friend and 2 to the 2nd or 1 muffin to each or 2 muffins to 1st friend and 0 to the 2nd.

       


      Added by:Mayank Tuteja
      Date:2013-01-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Gunjit Agrawal









      SPOJ Problem Set (classical)

      13404. The Encrypted Password

      Problem code: ICPC12C


      Encrypting passwords is one of the most important problems nowadays, and you trust only the encryption algorithms which you invented, and you have just made a new encryption algorithm.

      Given a password which consists of only lower case English letters, your algorithm encrypts this password using the following 3 steps (in this given order):

      1. Swap two different characters of the given password (you can do this step zero or more times).
      2. Append zero or more lower case English letters at the beginning of the output of step one.
      3. Append zero or more lower case English letters to the end of the output of step two.

      And the encrypted password is the output of step three.

      You have just finished implementing the above algorithm and applied it on many passwords. Now you want to make sure that there are no bugs in your implementation, so you decided to write another program which validates the output of the encryption program. Given the encrypted password and the original password, your job is to check whether the encrypted password may be the result of applying your algorithm on the original password or not.

      Input

      Your program will be tested on one or more test cases. The first line of the input will be a single integer T, the number of test cases (1$ \le$T$ \le$100). Followed by the test cases, each test case is on two lines. The first line of each test case contains the encrypted password. The second line of each test case contains the original password. Both the encrypted password and the original password are at least 1 and at most 100,000 lower case English letters (from `a' to `z'), and the length of the original password is less than or equal the length of the encrypted password.

      Output

      For each test case, print on a single line one word, `YES' (without the quotes) if applying the algorithm on the original password may generate the encrypted password, otherwise print `NO' (without the quotes).

      Example

      Input:
      
      3
      abcdef
      ecd
      cde
      ecd
      abcdef
      fcd
      Output:
      YES
      YES
      NO

      Added by:Kawmia Institutes
      Date:2013-01-18
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM ACPC 2012









      SPOJ Problem Set (classical)

      13405. MayanCalendar

      Problem code: APCER


       Problem Statement:

      The Maya is a Mesoamerican civilization noted for its art, architecture, mathematics and astronomical systems. In the recent past their calendar system has been quite in the news because of the misinterpretation of their Long count calendar, which gave way for a popular belief that a cataclysm will take place on December 21, 2012. Many speculated it will mark the end of human civilization!

      But we now know it did not happen as we are still alive! Note this date, it falls on a Friday.Since human civilization may have ended on that day, we will call every Friday the 21st as a vulnerable day. Similarly we define a safe day which is not a vulnerable day. Your task is given two years M and N, you need to find how many safe days are there between any given years M and N (inclusive).

      To honor the Mayan civilization you should write the total number of safe days in Mayan Long Count notation. The Long Count calendar identifies a date by counting the number of days from the Mayan creation date. But instead of using a base-10 scheme like Western numbering, the Long Count days were tallied in a modified base-20 scheme. As a matter of fact December 21, 2012 is simply the day that the calendar will go to the next B'ak'tun. You do not need to bother about creation date but simply represent your answer in Long Count notation. See the below example and table for clarification:


      Days

      Place

      Long Count unit

      1

                                  0

      1 K'in

      20

                                  1

      1 Winal

      360

                                  2

      1 Tun

      7,200

                                  3

      1 K'atun

      144,000

                                  4

      1 B'ak'tun

      Table of Long Count units

      Check the full list here: http://en.wikipedia.org/wiki/Maya_calendar (not needed for this problem).

      Conversion:

      For this problem you can consider numbers in the Long Count to be represented in base 20 except for the Winal place which is to be taken in base 18. Below example will clarify how to convert your answer into Long Count Notation.

      For instance, if safe days comes out to be 1454 your output must be:  "0.0.4.0.14" (without quotes).    (1*14 + 20*0 + 360*4 + 7200*0 + 144000*0 = 1454)

      For 360 output must be "0.0.1.0.0"(without quotes).

      For 20 output must be “0.0.0.1.0” (without quotes).

      As you can see all the places are in base 10 except the 1st place which is base 18.


      Input Specification: First line of input contains 0<T<500, number of test cases on which your program will run. Followed by two integers M and N where  1901<=M, N<=2300, where M<=N, if M=N you need to tell for that particular year only.


      Output Specification: For every test case output: A single line containing the number of safe days between the year M and N(inclusive) in Long count notation explained above. It is guaranteed that the number of safe days could always be represented up to fourth place (B'ak'tun place) in the above given notation.

      "a.b.c.d.e" (without quotes) where    0<= a, b, c, e <20, 0<=d<18.

      Facts:

      1. Jan 1, 1901 was Tuesday.
      2. All calculations must be done following Gregorian calendar which is the current standard calendar in the world including ours.
      3. If you don't know how to calculate leap year see this link: <http://en.wikipedia.org/wiki/Leap_year>

      Sample Test cases:

      Input:

      3

      2011 2012

      2012 2012

      2000 2020

      Output:

      0.0.2.0.7

      0.0.1.0.4

      0.1.1.3.14


      Explanation:

      For case 1: there are 727 safe days which can be represented as 0.0.2.0.7

      There are 4 vulnerable days between: January 2011 to December 2012.

      These are: 21st January 2011, 21st October 2011, 21st September 2012 and 21st December 2012.

      Total number of days between: January 2011 to December 2012 are 731.

      Therefore the number of safe days are 731-4 = 727.

       

       

       


      Added by:Rishabh Baid
      Date:2013-01-18
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:http://www.spoj.com/CRESCENT/









      SPOJ Problem Set (classical)

      13419. Modular Fibonacci Period

      Problem code: PISANO

      Perhaps the first thing one notices when the Fibonacci sequence is reduced mod M is that it seems periodic.

      For example :
      F (mod 4) = 0 1 1 2 3 1 0 1 1 2 3 ...
      F (mod 5) = 0 1 1 2 3 0 3 3 1 4 0 4 4 3 2 0 2 2 4 1 0 1 1 2 3 ...

      We define K(M) the period of the Fibonacci sequence reduced mod M if it is periodic.
      We just saw that K(4) = 6 and K(5) = 20.

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are one integer M.

      Output

      For each test case, on a single line, print K(M), or "Not periodic." without quotes if need.

      Example

      Input:
      3
      4
      5
      6
      
      Output:
      6
      20
      24
      

      Constraints

      1 < T < 10^4
      1 < M < 10^12
      

      Added by:Francky
      Date:2013-01-20
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      13420. Fimodacci

      Problem code: FMODF

      After solving Fib-Factorization and ModFib-Period, you would probably be interested by solving this new task:
      Simply compute Fib(N) mod Fib(K), where Fib(N) denotes the Nth term of the Fibonacci sequence.
      (If N<2 Fib(N)=N, else Fib(N)=Fib(N-1)+F(N-2)).

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are two integers N, K.

      Output

      For each test case, on a single line, print Fib(N) mod Fib(K).

      Example

      Input:
      2
      5 5
      13 5
      
      
      Output:
      0
      3
      

      Constraints

      1 < T < 10^5
      1 < N < 10^18
      1 < K <= 10^3
      

      Added by:Francky
      Date:2013-01-20
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      13444. Counting Lucky Numbers

      Problem code: CNT_LUCK

      Find out how many numbers between a and b (inclusive) when represented as binary numbers have sum of digits lucky.

      A number is lucky if it's decimal representation contains digits 4 and 7 only.

      eg. 4, 7, 47 , 77 etc. where as  14 , 41 etc. are not.

      Note that 0 <= a <= b <= 10^19.

      Input

      T: no of test cases T<=10^5

      Next T lines have a and b in every line. a <= b

      Output

      for every test case output as described in problem statement

      Example

      Input:
      2
      15 15
      63 63
      
      Output:
      1
      0

      Added by:praveen123
      Date:2013-01-21
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:general









      SPOJ Problem Set (classical)

      13447. Crayon

      Problem code: CRAYON


      Background

      Mary love painting so much, but as we know she can't draw very well.
      There is no one appreciate her works, so she come up with a puzzle with herself.

      Mary love painting so much, but as we know she can't draw very well. There is no one appreciate her works, so she come up with a puzzle with herself....

      Description

      There are only one case in each input file, the first line is a integer N (N <= 1,000,00) denoted the total operations executed by Mary. Then following N lines, each line is one of the folling operations.

      • D L R: draw a segment [L, R], 1 <= L <= R <= 1,000,000,000
      • C I: clear the ith added segment. It’s guaranteed that the every added segment will be cleared only once.
      • Q L R: query the number of segment sharing at least a common point with interval [L, R]. 1 <= L <= R <= 1,000,000,000.

      Input

      n

      ( then following n operations ... )

      Output

      (for each query, print the result on a single line ... )

      Example

      Input:
      6
      D 1 3
      D 2 4
      Q 2 3
      D 2 4
      C 2
      Q 2 3
      
      Output:
      2
      2
      

      Added by:xiaodao
      Date:2013-01-23
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      13469. FOREVER ALONE

      Problem code: ALONE

      IAR and FA numbers

      Numbers can be classified as IAR numbers and FA numbers.

      Numbers in which all digits are equal to either adjacent digit are called In-A-Relationship numbers. For example: 11, 22, 111, 9922888 and 777788822 are IAR numbers.

      Numbers featuring lonely digits are called Forever-Alone (FA) numbers. For example: in 22122 digit 1 is alone and in 123 all digits are alone.

      Given K, your task is to find the Kth In-A-Relationship (IAR) number.

      Input

      The first line contains number of test cases T ( T <= 50 )

      Then T test cases follow.

      Each line contains one integer K (1 <= K <= 5*10^6)

      Output

      For each test case, print the Kth IAR number.

      Sample Input

      5

      1

      2

      3

      10

      12

      Sample output

      11

      22

      33

      111

      333

      Added by:cegprakash
      Date:2013-01-23
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF
      Resource:problem setter: rishi_kumar









      SPOJ Problem Set (classical)

      13500. Discord is at it again

      Problem code: PONY8


      Princess Celestia has allowed Discord to be released in order to reform him. Discord, of course, does not wish to be reformed. While loose, he secretly destroyed all of Twilight Sparkle's books on reforming spells. But only the books. The information is still there, locked behind his chaotic magic.

      His chaotic magic created what is known as Mega String. To create this string, start by writing down the numbers 1, 2, 3, ..., and so on, and do this without putting any space between the numbers or digits.

      So it would look like this: 12345678910111213141516....

      However, for some reason, at that time, chaos dislikes the number 5.

      So any number that contains 5 as a digit, anywhere, isn't included in the Mega String.

      So the real Mega String looks like this:

      1234678910111213141617...

      and much later it looks like this:

      .., 47, 48, 49, ...

      ...474849606162...

      The question Twilight Sparkle needs to answer is, what is the digit that is at index K in the Mega String? Make sure to answer quickly, or else the information hidden by the Mega String will surely be lost to Twilight Sparkle.

      The Mega String is 0-indexed.

      Input format:

      The first line is an integer T, which is the number of test cases to follow. The following T, line i+1 will contain an integer K_i.

      Output format:

      T lines are to be output, and on line i should be the digit at index K_i in the Mega String.
      Sample Input:
      5
      0
      1
      2
      3
      4
      
      Sample Output:
      1
      2
      3
      4
      6
      

      Limits:

      1 <= T <= 10^5 and 0 <= K_i <= 10^18
      Time: x5 my fastest Java solution.
      Warning: Big Input Files

      Added by:Alex Anderson
      Date:2013-01-25
      Time limit:4.25s-9.350s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:My own problem









      SPOJ Problem Set (classical)

      13508. Madotsuki Pattern

      Problem code: MDT1

      Madotsuki is the main character of the surreal adventure game Yumenikki. The poor girl ended her life after discard all of her properties that have been found in the dream. Every year there are some small celebrations among people. The most symbolic sign of Madotsuki is the pattern on her clothes ...


      subir imagenes

      (image taken from github.com/madotsuki)

      You have been given a n*m design. Each element is one of the following character '1', '0', '?'. You can freely choose each '?' to become '0' or '1', to maximizate the number madotsuki pattern in the design.

      which the madotsuki pattern is somethings like this:

      101

      010

      Remark

      010

      101

      is not a madotsuki pattern.

      Input

      (Multiply test cases, for each test case)

      n m ( n <= 1000, m <= 10)

      [n*m '0', '1' or '?']

      Output

      For each test case, output the maximum answer, and how many design can reach the answer in total. Since the answer can be very huge, you only need to output it after mod 1,000,000,007.

      Example

      Input:
      
      2 4
      2 4 ???? ???? 4 6 ?????? ?1010? ?0101? ??????
      Output:
      1 8
      6 4
      

      Added by:xiaodao
      Date:2013-01-25
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set ()

      13511. Determine the vismin value !

      Problem code: KOSPC13B

                     There are N students in a class. The teacher wants to test the acuity of the students' vision as well as mind in an entertaining way.She comes up with an idea.
                      The students were made to stand in a line and numbered from 1 to N, each carrying a board with a number K on it.The test is as follows : the teacher calls out a student X;the student can look at either sides and choose a student Y who carries a board with a number greater than or equal to the number on the board carried by X and calculates a value called as "vismin value". "vismin value" is defined as the product of the difference between the positions of X and Y and the smallest of the numbers on the boards carried by X and Y.If it is not possible to choose Y,"vismin value" will be 0. Now, the way the students are tested is how far the students maximise the "vismin value".For each student called, he/she answers with a "vismin value".If it is maximum, teacher says "Maximum".If there is a greater value possible, the teacher says the value which the student is running short of, to attain the maximum value.If the value said by the student is greater than the maximum value possible, the teacher says "Not possible".
      Consider yourself as the teacher and print the output accordingly.

      Input:

      The first line of the input consists of N,the number of students in the class.
      The second line consists of N space separated integers K representing the numbers on the boards carried by the respective students.
      Then, each line/query consists of a student number separated by the vismin value determined by the student.
      Input ends with both student number and vismin value equal to 0.

      Output:
      For each query, print what the teacher would have said.

      Constraints :

      1<=N<=100000
      1<=k<=10^9

      Number of queries <= 10000


      Input :
      5
      5 3 6 7 1
      1 13
      1 18
      1 15
      4 5
      5 4
      0 0
      Output :
      2
      Not possible
      Maximum
      Not possible
      Maximum


      Added by:Pandian
      Date:2013-01-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL
      Resource:Own problem









      SPOJ Problem Set (classical)

      13523. Card Meets (medium)

      Problem code: GUMATH2

      Guardian is very weak at maths but still to compete in a certain exam he has to get good grades in mathematics this time. In the first class of the semester the Prof. asked students to find the number of ways deck (having N cards) could be shuffled that exactly one card is at the same position as before, and the students who successfully do this will be awarded with good marks in mid terms. Help Guardian solve this problem.

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are one integer N.

      Output

      For each test case you have to output on a single line the number of ways possible meeting the Prof.'s requirements.
      As the answer can be a huge number, simply output it modulo 10000009.

      Example

      Input:
      1
      3
      
      Output:
      3
      

      Let's say the initial deck configuration was {1,2,3}, then three possible shuffles are {1,3,2}, {2,1,3}, {3,2,1}.

      Constraints

      1 < T < 10^4
      0 < N < 10^18
      

      @speed addicts : my C code ran in 0.08s, and my python3 code ran in 3.2s. (Total time)


      Added by:Francky
      Date:2013-01-26
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:









      SPOJ Problem Set (classical)

      13529. Special Graph

      Problem code: SPECIALG

       

      You are given a directed graph with N vertices. The special thing about the graph is that each vertex
      has at most one outgoing edge. Your task is to answer the following two types of queries:

       

      You are given a directed graph with N vertices. The special thing about the graph is that each vertex has at most one outgoing edge. Your task is to answer the following two types of queries

      1 a  delete the only edge outgoing from vertex a. It is guaranteed that the edge exists. 1<= a<= N

       

      2 a b  output the length of the shortest path from vertex a to vertex b, if the path exists. Otherwise

      output "-1" without quotes. 1<=a, b<= N

       

      Input

       

       

       

      First line of input contains a natural number N<=10^5  the number of vertices in the graph.

      The following line contains N integer numbers, i-th number is next[i] (0<= next[i]<= N), meaning that there

      is an edge from vertex i to vertex next[i]. If next[i] = 0, assume that there is no outgoing edge from vertex

      i.

      Third line contains a natural number M<=10^5  the number of queries.

      The following M lines contain a query each. Queries are given in the manner described above.

       

      Output

      On the i-th line output the answer for the i-th query of type 2 a b.

      Example

       

      Input:
      6
      3 3 4 5 6 4
      6
      2 1 6
      2 1 4
      2 1 2
      1 3
      2 1 6
      2 1 4
      
      Output:
      4
      2
      -1
      -1
      -1

      Added by:Ikhaduri
      Date:2013-01-27
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Izho 2013









      SPOJ Problem Set (classical)

      13545. Room Change

      Problem code: CHGROOM


      Problem Statement

      It's the end of the semester and best friends Anne and Marian have finally gotten permission from the hostel supervisor to swap rooms and become room mates. Both of them are extremely happy to hear this, but one problem still remains. Although Anne and Marian definitely want to be room mates, both of them are also very attached to their current rooms and neither of them wants to move out.

      After a lot of discussion regarding who should be the one to shift rooms, they decide to settle the matter in the following manner :

      Both Anne and Marian write down, independently, 2 positive integers k1 and k2. Then, the value q = ( k1 + k2 - 1 ) is written down on a piece of a paper. Anne is the first person to make a move. During each move, the current player writes down any integer number that is a non-trivial divisor of the last written number. The first person who can't make a move wins, and the other person is the one who needs to shift into the winner's room.

      Given that both players play optimally, output the name of the person who wins the game for a given value of q.

      NOTE : A number's divisor is said to be non-trivial if it is different from one and from the divided number itself.

       

      Input

      The input contains a single integer q ( 1 <= q <= 1013 ). 

      Output

      On a single line output "ANNE" if Anne wins. Else output "MARIAN". Note that the quotes are just for clarity, and that the output is case-sensitive.

       

      Example

      Input #1:
      6
       
      Output #1:
      MARIAN


      Input #2:

      30

      Output #2:
      ANNE


      Input #3:
      1

      Output #3:
      ANNE

      Explanation :

      Input #1 : 6 has exactly 2 non-trivial divisors - { 2, 3 }. But neither of these numbers have any non-trivial divisors. So no matter which one Anne writes down, Marian will win since she cannot make any move


      Input #2 : Since 6 is a non-trivial divisor of 30, Anne writes down 6. Now, as can be seen from input #1, no matter what move Marian makes, Anne will win.


      Input #3 : Since 1 has no non-trivial divisors, Anne wins.


      Added by:Gowri Sundaram
      Date:2013-01-28
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13577. Card Game

      Problem code: HC12

      John is playing a game with his friends. The game's rules are as follows: There is deck of N cards from which each person is dealt a hand of K cards. Each card has an integer value representing its strength. A hand's strength is determined by the value of the highest card in the hand. The person with the strongest hand wins the round. Bets are placed before each player reveals the strength of their hand.

      John needs your help to decide when to bet. He decides he wants to bet when the strength of his hand is higher than the average hand strength. Hence John wants to calculate the average strength of ALL possible sets of hands. John is very good at division, but he needs your help in calculating the sum of the strengths of all possible hands.

      Problem

      You are given an array a with N ≤ 10 000 different integer numbers and a number, K, where 1 ≤ K ≤ N. For all possible subsets of a of size K find the sum of their maximal elements modulo 1 000 000 007.

      Input

      The first line contains the number of test cases T, where 1 ≤ T ≤ 25

      Each case begins with a line containing integers N and K. The next line contains N space-separated numbers 0 ≤ a [i] ≤ 2 000 000 000, which describe the array a.

      Output

      For test case i, numbered from 1 to T, output "Case #i: ", followed by a single integer, the sum of maximal elements for all subsets of size K modulo 1 000 000 007.

      Example input

      5

      4 3

      3 6 2 8 

      5 2

      10 20 30 40 50 

      6 4

      0 1 2 3 5 8 

      2 2

      1069 1122 

      10 5

      10386 10257 10432 10087 10381 10035 10167 10206 10347 10088 

      Example output

      Case #1: 30

      Case #2: 400

      Case #3: 103

      Case #4: 1122

      Case #5: 2621483

       

       

      Example input
      5
      4 3
      3 6 2 8 
      5 2
      10 20 30 40 50 
      6 4
      0 1 2 3 5 8 
      2 2
      1069 1122 
      10 5
      10386 10257 10432 10087 10381 10035 10167 10206 10347 10088 
      Example output
      Case #1: 30
      Case #2: 400
      Case #3: 103
      Case #4: 1122
      Case #5: 2621483Example input
      5
      4 3
      3 6 2 8 
      5 2
      10 20 30 40 50 
      6 4
      0 1 2 3 5 8 
      2 2
      1069 1122 
      10 5
      10386 10257 10432 10087 10381 10035 10167 10206 10347 10088 


      Example output
      Case #1: 30
      Case #2: 400
      Case #3: 103
      Case #4: 1122
      Case #5: 2621483

       


      Added by:abdelkarim
      Date:2013-02-02
      Time limit:1.5s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Facebook Hacker Cup 2013 Round 1









      SPOJ Problem Set (classical)

      13588. One X LIS

      Problem code: ONEXLIS


      For a given sequence a[1], a[2], ... a[n], lets call a subsequence a[k1], ...a[ki]... a[km] (where 1<=ki<=n and ki<ki+1) as "one X increasing subsequence" if there is exactly one i between 1 and m-1 (inclusive) for which a[ki]>a[ki+1]. Given a sequence find the length of the longest "one X increasing subsequence".

      Input

      First line contains t, which denotes the number of test cases. 2*T lines follow. Each test case is described using 2 lines.

      First line of a test case contains an integer- n, which denotes the number of elements in the array.

      Second lines contains n integers, which represent a[i] 1<=i<=n.

      1<=t<=20

      1<=n<=100000

      1<=a[i]<=10^9

      Output

      For each test case, print one integer which represents the number of integers in the One X LIS. The output for each test case should be printed on a new line.

      Example

      Input:
      2
      5
      4 3 3 4 1
      5
      5 4 3 2 1

      Output: 4
      2

      Explanation:

      In the first test case, the Longest Increasing Subsequence is 3.3.4 whereas the longest One X Subsequence is 4.3.3.4 whose length is 4.

      In the second example, any two elements can be chosen to form the longest One X Subsequence, which gives us an answer of 2.


      Added by:TouristGuide
      Date:2013-02-03
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Bytecode 2013









      SPOJ Problem Set (classical)

      13591. Factor y Hell

      Problem code: FCTRHELL


      Factorial(N) in base B : The number of trailing zeros.

      Factorial(19) in base 9×10^0=9 can be written 725735500635080000, ending with 4 zeros.
      Factorial(43) in base 2×10^1=20 can be written 59HHHFECFCCEGH5G7I7A3A8G88F8CD8G000000000, ending with 9 zeros.
      What about working with serious constraints and tricky cases ?
      Factorial(N) will be a huge one, the base will be dummy too and have the special form : B×10^E.

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are three integers : N, B, E.

      Output

      For each test case, print the number of zeros at the end of Factorial(N) written in base B×10^E.

      Example

      Input:
      3
      19 9 0
      43 2 1
      10000 100 10
      
      Output:
      4
      9
      208
      

      Constraints

      1 <= T < 2000
      1 <= N < 10^1000
      1 <= B < 10^9
      0 <= E < 10^9
      

      Informations

      Don't worry about the 'special' base 1 (B=1 and E=0), it is absent from input.
      About distribution : random input (N : log-uniform, B : uniform, E : uniform) in their range. Some tricky cases are added.
      It is recommended to solve FACTBASE first, and find a way to solve FCTRL much faster than common solutions.
      Time limit is ×12 my best Python3 time, or ×1.2 my "basic" one.


      Added by:Francky
      Date:2013-02-03
      Time limit:6s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      13592. Expected Time to Love

      Problem code: PRLOVE


      Alice has a problem. She loves Bob but is unable to face up to him. So she decides to send a letter to Bob expressing her feelings. She wants to send it from her computer to Bob's computer through the interet.
      The internet consists of N computers, numbered from 1 to N. Alice's computer has the number 1 and Bob's computer has the number N. 
      Due to some faulty coding, the computers start behaving in unexpected ways. On recieving the file, computer i will forward it to computer j with probability P(i,j). The time taken to transfer the file from computer i to computer j is T(i,j).
      Find the expected time before Bob finds out about Alice's undying love for him.
      Note: Once the letter is recieved by Bob's computer, his computer will just deliver it to Bob and stop forwarding it.


      Alice has a problem. She loves Bob but is unable to face up to him. So she decides to send a letter to Bob expressing her feelings. She wants to send it from her computer to Bob's computer through the interet.


      The internet consists of N computers, numbered from 1 to N. Alice's computer has the number 1 and Bob's computer has the number N. 


      Due to some faulty coding, the computers start behaving in unexpected ways. On recieving the file, computer i will forward it to computer j with probability Pij. The time taken to transfer the file from computer i to computer j is Tij.


      Find the expected time before Bob finds out about Alice's undying love for him.


      Note: Once the letter is recieved by Bob's computer, his computer will just deliver it to Bob and stop forwarding it.



      Input


      First line contains T, the total test cases.

      Each test case looks  as follows:

      First line contains N, the total number of computers in the network.

      The next N lines contain N numbers each. The j'th number on the i'th line is the value Pij in percents.

      The next N lines contain N numbers each. The j'th number on the i'th line is the value Tij.


      Output


      Output a single line with a real number - The expected time of the transfer.

      Your output will be considered correct if each number has an absolute or

      relative error less than 10-6.


      Constraints:

      N <= 100

      T <= 5

      For all i, Pi1 + Pi2 + ..... + PiN = 100

      PNN = 100

      For all i,j, 0 <= Tij <= 10000


      You can safely assume that from every computer, the probability of eventually reaching Bob's computer is greater than 0.




      Example

      Sample Input:
      
      2
      4
      0 50 50 0
      0 0 0 100
      0 0 0 100
      0 0 0 100
      
      0 2 10 0
      0 0 0 0
      0 0 0 0
      0 0 0 0
      2
      99 1
      0 100
      10 2
      0 0
      
      Sample Output:
      6.000000
      992.000000

      Added by:Aditya Muraletharan
      Date:2013-02-03
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BASH C C++ 4.3.2 C++ 4.0.0-8 FORT HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n RUBY SCALA WSPC
      Resource:ByteCode '13









      SPOJ Problem Set (classical)

      13595. A STANDARD PROBLEM

      Problem code: ASTDPROB


       

      In a super standard problem you are given a table of size NxM, (N rows and M columns), filled 
      only with 0's and 1's. In such a super standard problem you are very likely to be asked: what is the 
      biggest rectangle (a rectangle with the maximum possible area) in this table that only contains 0's? 
      Fortunately, nobody likes super standard problems. This is why we would modify this super 
      standard problem into a standard one by asking for  a maximum rectangle of zeroes, fit between a 
      defined couple of rows: r1 (upper row) and r2 (lower row). Parts of the given row boundaries can take 
      part in the solution found, but no element above the upper row or below the lower one is allowed. What
      is the area of the range found? Write a program standard to answer several questions of that kind for 
      a given table. 

       In a super standard problem you are given a table of size NxM, (N rows and M columns), filled only with 0's and 1's. In such a super standard problem you are very likely to be asked: what is the biggest rectangle (a rectangle with the maximum possible area) in this table that only contains 0's? 

       Fortunately, nobody likes super standard problems. This is why we would modify this super standard problem into a standard one by asking for  a maximum rectangle of zeroes, fit between a defined couple of rows: r1 (upper row) and r2 (lower row). Parts of the given row boundaries can take part in the solution found, but no element above the upper row or below the lower one is allowed. What is the area of the range found? Write a program standard to answer several questions of that kind for a given table. 

      Input

       

       The first line of the standard input contains the table size: two space separated positive integers N and M. Each of the next N lines contains M space separated numbers (0 or 1). In the next line there is one positive integer Q: the number of boundary couples of rows. The next Q lines contain two space separated positive integers each: an upper and a lower row (r1, r2) (1 ≤ r1 ≤ r2 ≤ N), between which you have to find a solution of the problem. 

       

      Constraints 

      1 ≤ N, M ≤ 1000 

      1 ≤ Q  ≤ 106

       

       

      Output

       

       The output consists of Q lines. In each of them you have to output one integer – the answer of the corresponding input query: the area of the biggest rectangle you can fit between the given row boundaries.  

       

      Example

      Input:
      3 4 
      0 1 0 0 
      1 0 0 0 
      0 0 0 0 
      3 
      1 2 
      2 3 
      1 3
      
      Output:
      4 
      6 
      6

      Added by:igarash1
      Date:2013-02-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:INTERNATIONAL TOURNAMENT IN INFORMATICS. November 25-27, 2011, Shumen, Bulgaria.









      SPOJ Problem Set (classical)

      13621. Security

      Problem code: HC12II

      ou are designing a new encryption system that works in the following way:

      For server-client communication you need a key k, composed of m sections, each of length l, and the key consists only of lowercase characters in the set {a, b, c, d, e, f}. The server has a key k1 and the client has a key k2 where:

      • k1 = f(k). f is a function that receives a key and replace some random letters by ? indicating that those characters can be any lowercase letter of the set described before.
      • k2 = f(g(k)). g is a function that takes a key and produces a random permutation of its m sections. And f is the function defined above.

      For example: let m = 3, l = 2

      • f('abacbc') = '?ba??c'
      • g('abacbc') = 'acbcab' (each section was moved one place to the left).

      Your task is given k1 and k2, find key k. If there are several solutions, print the lexicographically smallest key. And if there is no solution at all, print "IMPOSSIBLE" (without the quotes).

      Input

      The first line has a single integer T, which corresponds to the number of test cases. T test cases follows: the first line of the test case corresponds to the integer m, the second line contains the string k1 and the third line contains the string k2.

      Output

      For test case i, numbered from 1 to T, output "Case #i: ", followed by the lexicographically smallest key or "IMPOSSIBLE".

      Example

       

      Input:

      5

      2

      abcd

      c?ab

      3

      ab?c?c

      ac?c??

      3

      ab?c?c

      aabbdd

      2

      aa

      bb

      2

      abcd

      cdab

      Output:

      Case #1: abcd

      Case #2: abacac

      Case #3: IMPOSSIBLE

      Case #4: IMPOSSIBLE

      Case #5: abcd

      Constraints :

      T <= 20

      0 < |k1| <= 100

      0 < m <= 50

      |k2| = |k1|

      It is guaranteed that m is always a divisor of |k1|

      k1 and k2 consist of {a, b, c, d, e, f, ?}

       

      Input:
      aabbdd
      2
      k1 and k2 consist of {a, b, c, d, e, f, ?}

      Added by:abdelkarim
      Date:2013-02-05
      Time limit:3s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Facebook Hacker Cup 2013 Round 1









      SPOJ Problem Set (classical)

      13622. Dead Pixels

      Problem code: HC12III

      John's friend Peter purchases a new high resolution monitor with dimension W * H where W is the number of pixels in each row (i.e. width) and H is the number of pixels in each column (i.e. height).

      However, there are N dead pixels on the monitor. The i-th dead pixel is located at (x[i], y[i]). (0, 0) is the top-left pixel and (W - 1, H - 1) is the bottom-right pixel. The locations of the dead pixels could be generated by 6 given integers XYabc and d by the following rules. If 2 pixels are at the same location, they are considered the same. It is possible that there are less than N distinct dead pixels.

       

      x[0] = X
      y[0] = Y
      x[i] = (x[i - 1] * a + y[i - 1] * b + 1) % W (for 0 < i < N)
      y[i] = (x[i - 1] * c + y[i - 1] * d + 1) % H  (for 0 < i < N)

       


      x[0] = X

      y[0] = Y

      x[i] = (x[i - 1] * a + y[i - 1] * b + 1) % W (for 0 < i < N)

      y[i] = (x[i - 1] * c + y[i - 1] * d + 1) % H  (for 0 < i < N)

       

       

      Peter connects his monitor to his computer and opens an image with dimension P (width) * Q (height). How many unique positions can the image be placed so that it can be displayed perfectly (i.e. all pixels of the picture are shown on the monitor)? The image cannot be rotated.

                                                                                           Input

      The first line contains an integer T, which is the number of test cases. Then T test cases follow. Each test case contains 11 integers WHPQNXY,abcd.

      Output

      For each of the test cases numbered in order from 1 to T, output "Case #", followed by the case number (with 1 being the first test case), followed by ": ", followed by an integer which is the number of different possible positions for the poster.

      Example

      Input:

      5

      4 4 2 2 1 0 2 1 2 3 4

      4 4 1 1 3 1 1 2 2 2 2

      6 10 3 2 2 0 0 5 4 3 2

      16 18 5 1 5 10 8 21 27 29 87

      14 15 12 4 4 3 5 84 74 53 68

      Output:

      Case #1: 7

      Case #2: 15

      Case #3: 32

      Case #4: 197

      Case #5: 16

       

      Constraints

      1 ≤ T ≤ 20

      1 ≤ W, H ≤ 40 000

      1 ≤ P ≤ W

      1 ≤ Q ≤ H

      1 ≤ N ≤ min(1 000 000, W * H)

      1 ≤ a, b, c, d ≤ 100

      0 ≤ X < W

      0 ≤ Y < H

       


      Added by:abdelkarim
      Date:2013-02-05
      Time limit:37s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Facebook Hacker Cup 2013 Round 1









      SPOJ Problem Set (classical)

      13626. Charu and Coin Distribution

      Problem code: CBANK


      One day Charu went to deposit his pocket money in the Bank .
      But there was one problem that he wanted to deposit exactly "N" rupees ,and he has coins of 0.25,0.50,1.0,
      and 2.0 rupees; and number of coins of each type are "4*N"; So he wants to know how many ways are there
      such that he can deposit exactly "N" rupees in bank using any number of coins of each type.
      As Charu is poor in counting he wants your help ,Given input "N"
      give the number of ways of depositing "N" rupees using coins of 0.25,0.50,1.0,and 2.0 rupees. Since the answer can be really large, output the remainder when the answer is divided by 1000000007.

      Input

      First line will be t ,test cases
      T<=10000;
      The next t lines ,each line contains N
      N <=1e9

      Output

      The output should contain one line per testcase, representing the answer to the given problem.

      Example

      Input:
      2
      1
      2

      Output: 4
      10

      Explanation :
      In first case {.25,.25,.25,.25} ,{.50,.25,.25} ,{1}, {.50,.50}

      Added by:TouristGuide
      Date:2013-02-06
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Bytecode 2013









      SPOJ Problem Set (classical)

      13630. BATMAN1

      Problem code: BAT1

       

      " Lucius Fox: This conversation used to end with an unusual request. 
        Bruce Wayne: I'm retired. 
        Lucius Fox: Well let me show you some stuff anyway. Just for old time's sake. "
      Eight years after Harvey Dent's death, the Dent Act allowed eradication of organized crime . BATMAN has disappeared . Wayne enterprises is unprofitable after Bruce discontinued his fusion reactor project .  A masked man called Bane who was trained under Ra's al Ghul captures Gordon .  Bane attacks the Gotham Stock Exchange,  using Bruce's fingerprints in a transaction that bankrupts Wayne .
      Now that gotham city was heading into deep deep trouble , Its time for BATMAN to return .
      However , since the company no longer belongs to Bruce Wayne , Mr. Wayne has very little funds to spend on buying his weaponaries.
      Mr Fox head him to the place where all weapons are stored .  
      Now these weapons come in batches properly sealed for safety .Each of these batches will have an unbounded number of weapons of different types . To buy these weapons Wayne initially need to pay the price for opening the seal . Then each of these weapons have a cost and a power rating associated with it .  Mr Wayne needs to spend wisely on it to maximize the power rating using  limited amount of money.
      People of Gotham , he needs your help for choosing his weaponaries .

       

      " Lucius Fox: This conversation used to end with an unusual request.
        Bruce Wayne: I'm retired.
        Lucius Fox: Well let me show you some stuff anyway. Just for old time's sake.
      "

       

      Eight years after Harvey Dent's death, the Dent Act allowed eradication of organized crime . BATMAN has disappeared . Wayne enterprises is unprofitable after Bruce discontinued his fusion reactor project .  A masked man called Bane who was trained under Ra's al Ghul captures Gordon . Bane attacks the Gotham Stock Exchange, using Bruce's fingerprints in a transaction that bankrupts Wayne .

      Now that gotham city was heading into deep deep trouble , Its time for BATMAN to return .

      However , since the company no longer belongs to Bruce Wayne , Mr. Wayne has very little funds to spend on buying his weaponaries. Mr Fox head him to the place where all weapons are stored .  

      Now these weapons come in batches properly sealed for safety .Each of these batches will have an unbounded number of weapons of different types . To buy these weapons Wayne initially need to pay the price for opening the seal . Then each of these weapons have a cost and a power rating associated with it .  Mr Wayne needs to spend wisely on it to maximize the power rating using  limited amount of money.

      People of Gotham , he needs your help for choosing his weaponaries .

       

      "Lucius Fox : It has a long uninteresting name. I just took to calling it... The Bat, and yes, Mr. Wayne, it does come in black."

      Input

       

      t , number of testcases
      integers n m k,
      n: no of batches , m:  no of weaponaries per batch , k : Money wayne can spend on weaponaries 

      n intergers giving cost of opening the ith batch
      n*m numbers denoting cost of jth object from ith batch
      n*m numbers denoting the rating oj jth object from ith batch

       

      Output

      The maximum power rating Wayne could afford 

       

      Constraints :
      1<= n,m <=20
      k <= 1000 
      cost[i] <=20 , rating[i] <=100 

       

      Example

      Input:
      
      1
      2 4 20
      3 4 
      3 2 3 2
      3 2 3 5
      3 2 3 2
      4 5 6 5
      Output:
      40

      Added by:Romal Thoppilan
      Date:2013-02-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      13631. BATMAN2

      Problem code: BAT2

       

      " Alfred: I'll get this to Mr. Fox, but no more. I've sewn you up, I've set your bones, but I won't bury you. I've buried enough members of the Wayne family.  "

       

      " Alfred: I'll get this to Mr. Fox, but no more. I've sewn you up, I've set your bones, but I won't bury you. I've buried enough members of the Wayne family.  "

      After being promised the software to erase her criminal record, Catwoman agrees to take Batman to Bane. They manage to defeat all of BANE's men but ended up heading into a MAZE trap . BANE would call this maze as the LIS MAZE . He would hide himself in one of the rooms .Each of these rooms have a number(tag) associated with it. The speciality of the maze is that once you enter any room it will only lead you to rooms with a higher tag in the direction you move . BATMAN and Catwoman decide to move in opposite directions trying their luck to maximize the number of rooms they search . (They can start with any room , need not be the same)

      " Catwoman : Never steal from someone you can't outrun, kid.

       

      Input

       

      t , number of testcases
      n , number of rooms
      n integers  giving the tag associated with the rooms

       

      Output

       

      The maximum number of rooms searched.

       

      Constraints : 

      1 < = n  < = 100

       

       

      Example

      Input:
      
      1
      6
      5 3 4 6 1 2
      Output:
      
      5

      Added by:Romal Thoppilan
      Date:2013-02-06
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      13643. BATMAN3

      Problem code: BAT3

       

      "
      Bruce Wayne: I do fear death. I fear dying in here while my city burns. 
      Blind Prisoner: Then make the climb.
      Bruce Wayne: How?
      Blind Prisoner: As the child did. Without the rope. Then fear will find you again.
      "

       

      " Bruce Wayne: I do fear death. I fear dying in here while my city burns.
       Blind Prisoner: Then make the climb.
       Bruce Wayne: How?
       Blind Prisoner: As the child did. Without the rope. Then fear will find you again. "

       


      The Epic fight between BANE and BATMAN saw BATMAN on the losing side .Bane delivers a crippling blow to Batman's back, then takes him to a foreign, well-like prison where escape is virtually impossible .

      The prison as we know is a place from where no man ever escaped , except for the child of Ra's al Ghul himself . 

      The heroics of BATMAN saw him escape the prison , however after the prison came the Valleys . To reach the city , He needed to cross these valleys . Meanwhile , BANE's army has surrounded the city and trapped all the policemen underground . Each of these peaks contain exactly one policeman held captive by Bane's men. Since, BATMAN needs to build his own army , he decides to free some of the policemen on his way . 

      Also BATMAN needed to save his energy before his battle with Bane ,so he decided to take only downhill (strictly) jumps .Detective John Blake ( now called as ROBIN ) is standing in one of these peaks with a mini-BAT . This will allow BATMAN to take a maximum one jump uphill ahead . BATMAN can choose to flee ROBIN and use the BAT or rather cross over without his help .

      The task in hand is to maximize the army strength to face BANE as BATMAN crosses over.
      (BATMAN can take his first jump on any of these peaks)

       

      " Bane : So, you came back to die with your city. 
         Batman : No. I came back to stop you


      Input

       

      t , number of testcases
      n : number of peaks ,  m : (zero based)index of the peak where ROBIN is standing
      n intergers denoting the height of the peaks   

       

      Output

       

      The maximum strength of the army

       

      Constraints :

      1<=n<=1000

       

       

      Example

      Input:
      
      1
      6 4
      6 3 5 2 4 5
      Output:
      4

      Added by:Romal Thoppilan
      Date:2013-02-06
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      13646. BATMAN4

      Problem code: BAT4

       

      "
      Batman: A hero can be anyone. 
      Even a man doing something as simple and reassuring as putting a coat around a little boy's shoulder to let him know that the world hadn't ended. 
      "

      " Batman: A hero can be anyone. Even a man doing something as simple and reassuring as putting a coat around a little boy's shoulder to let him know that the world hadn't ended. "

       

      THE BOMB IS TRIGGERED !! , IT WOULD BLOW OFF IN A FEW MINUTES !!
      BATMAN resorts to his BAT and decides to head towards the ocean with the bomb . 
      However in front of him lies a huge grid of tall buildings . Starting from the top-leftmost grid he needs to move to the bottom right-most grid to reach the ocean . Since the fuel of BAT has nearly exhausted , BATMAN decides to chose a path where the maximum up distance travelled at a time is minimized .   However , each movement of the BAT up or down the building takes one unit of time . (Horizontal movements can be made in no time) . The clock keeps ticking , So BATMAN decides to choose a path reaching the destination minimizing the maximum up distance and with as much time left as possible. 
      Every Hero Has a Journey. Every Journey Has an End !

       

      " CatWoman : You dont owe these people anymore . You've given them everything 
        BatMan : Not everything , Not Yet . " 

       

      NOTES :

      BatMan requires to take the first jump on (1,1)
      Print NO is no time is left
      minimum max up-distance is the first priority.

      Input

      t , number of testcases
      n,T denoting the size of the grid , T time left.
      n rows and n colums denoting the heigths of the buildingOutput

      If BATMAN could reach the destination,
      print "YES" , the maximum up distance travelled and the maximum time left with BATMAN 

      If he could not reach the destination within time print "NO" 

      Constraints 

      1 <= n <= 20

      1 <= t <= 100

      Example

      Input:
      
      1
      3 40
      2 4 3
      4 5 3
      2 4 6
      Output:
      YES : 2 32

      Added by:Romal Thoppilan
      Date:2013-02-06
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      13647. Tjandra 19th birthday (EASY)

      Problem code: TJANDRAS

      This day (7 February 2013) is my 19th birthday Laughing So, I want to celebrate it on SPOJ by making this EASY puzzle problem.

      This game/puzzle is about matches, given n matches, your task is to arrange the matches (not necessarily all) such that number of rectangle (any size) is maximum.

      Input

      First line there is an integer T100 then T lines follow, each line contain an integer n<1.000.000.000.

      Output

      For each test case, output required answer (maximum number of rectangles)

      Example

      Input:
      5
      3
      4
      8
      12
      15
      Output:
      0
      1
      3
      9
      12

      Explanation

      -->First test case: No rectangle can be formed with only 3 matches

      -->Second test case: Only one rectangle can be formed with 4 mathes

      -->Third test case:

      there are max 3 rectangles (2 size 1x1, 1 size 2x1) can be formed with number of matches<=8, here is one of the mathes formation:

      Case 3

      -->Fourth test case:

      there are max 9 rectangles (4 size 1x1, 2 size 2x1, 2 size 1x2, 1 size 2x2) can be formed with number of matches <=12, here is one of the formation:

      case 4

      -->Fifth test case:

      there are max 12 rectangles (5 size 1x1, 3 size 2x1, 1 size 3x1, 2 size 1x2, 1 size 2x2) can be formed with number of matches <=15, here is one of the formation:

      case 5

      Information

      Time limit≈150x my program speed (also TL=my age now Wink), Enjoy this birthday party game, I set this problem such that semi naive solution will pass..

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-02-07
      Time limit:19s
      Source limit:19000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Just Watch This Video! I Uploaded it 1 year ago









      SPOJ Problem Set (classical)

      13651. Check

      Problem code: KNGCHECK


      Chess is a two-player strategy board game played on a chessboard, a square checkered game board with 64 squares arranged in an eight-by-eight grid. It is one of the world's most popular games, played by millions of people worldwide at home, in clubs, online, by correspondence, and in tournaments. Each player begins the game with 16 pieces: one king, one queen, two rooks, two knights, two bishops, and eight pawns. Each of the six piece types moves differently. Pieces are used to attack and capture the opponent's pieces, with the objective to 'checkmate' the opponent's king by placing it under an inescapable threat of capture. In addition to checkmate, the game can be won by the voluntary resignation of the opponent, which typically occurs when too much material is lost, or if checkmate appears unavoidable. A game may also result in a draw in several ways, where neither player wins. The course of the game is divided into three phases: opening, middle game, and endgame. Source Wikipedia

      To simplify this problem you will only deal with Kings, Knights and Pawns of the Black and the White Players. Assume that the White Player starts at the lower half of the board and the Black Player starts at the upper half. Given the state of the board, your task is to determine whether the black king is checked or not. For Clarity a 'Check' occurs when the King's square can be attacked by any of the opponent's pieces for his next move, and note that in this problem we will ignore the consequences which will follow, we don’t even care whose turn is now but only consider the board state (out of chess rules).

      The Knight moves like an "L", it moves from cell (r1, c1) to cell (r2, c2) if and only if (r1 - r2)2 + (c1-c2)2 = 5 (8 possible moves).

      The King can move only one move in its four main directions and its four diagonals (8 possible moves).

      The Pawn attacks only one move diagonally and only to the oppenent direction (2 possible moves).

      This problem is NOT following all chess rules, for example in real chess third case in the sample is INVALID, so please assume that the given board is always valid, just check the black king state.

       

      Input

      You are given an 8x8 Board with Chess Pieces denoted as following: BK = Black King, WK = White King, BH = Black Knight, WH = White Knight, BP = Black Pawn, WP = White Pawn. We ensure that there is one and only one Black King in the Chess Board. Blank fields are denoted by “-”. Cases are seperated by blank lines.

      Output

      You should output “Check” if a Check exists or “Not Check” if no check exists. Follow the output format described in the sample tests.

      Example

      Input:
      3
      - - - - - - - -
      - - - - - - - -
      - - - - - - - -
      - BH - - - - - -
      - - - BK - - - -
      - - WP - - - - -
      - - - - - - - -
      - - - - - - - -
      
      - - - - - - - -
      BH - - BH - - - -
      - - - - - - - -
      - - - - - - - -
      - - - BK - - - -
      - - - - - - - -
      - WP - - - - WH -
      - - - WK - - - -
      
      - - - - - - - -
      - - - - - - - -
      - - - - - - - -
      - - - - - - - -
      - - - BK - - - -
      - - - WK - - - -
      - - - - - - WH -
      - - - - - - - -
      
      - WP - - - - WH -
      Output: Case #1: Check Case #2: Not Check Case #3: Check

      Added by:Sharaf
      Date:2013-02-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:2013 acmASCIS Level 1 Contest









      SPOJ Problem Set (classical)

      13683. Transitive Closure

      Problem code: TRANCLS

      In mathematics, a set S is transitive if whenever an element a is related to an element b, and b is in turn related to an element c, then a is also related to c. In other words, any set of pairs is transitive if and only if you have (a,b) and (b,c) then you also must have (a,c). Check this example: S = { (1,2),(2,3),(3,4),(2,4) }. Is set S is transitive relation ? No, Because you have (1,2) and (2,3) but you don’t have (1,3) If we add (1,3) will it be transitive ? (( S = { (1,2),(2,3),(3,4),(2,4),(1,3) } )) No, Because you have (1,3) and (3,4) but you don’t have (1,4) If we add (1,4) will it be transitive ? (( S = { (1, 2),(2,3),(3,4),(2,4),(1,3),(1,4) } )) Yes, Now the set S is now transitive after we added 2 pairs { (1,3),(1,4) } These pairs called transitive closure (which means the minimal pairs that convert set S into a transitive set ). Your task is given the set S you have to output the minimal pairs have to be added to make the set S transitive.

      Input

      The first line of input is the number of test cases T where (0<T<=100), Each test case you'll be given the number of pairs in the set N where  (0<N<=100), followed by N pairs (a, b) where (0<=a,b<N).

      Output

      For each test case print "Case_#i:_X" where "i" is the case number, "X" is the minimal number of pairs have to be added to make the set transitive and "_" is a white space. Each test case should be in a separate line.

      Example

      Input:
      
      3
      4
      1 2
      2 3
      2 4
      2
      1 2
      2 1
      1 2
      3 4 0 1 1 2 2 3 1 3 2 0 1 1 0 1 0 0 Output:
      Case #1: 2
      Case #2: 2
      Case #3: 0
      

      Added by:Sharaf
      Date:2013-02-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:2013 acmASCIS Level 1 Contest









      SPOJ Problem Set (classical)

      13686. finding maximum possible number

      Problem code: MAX_NUM

      Given a number n, Find out what max possible number you can make by deleting exactly k digits.

      T : no of test cases <= 10^3

      1 <= no of digits in n <= 10^5. (n might contain leading zeros)

      0 <= k <= n

      if value of n is equal to k. then just print a new line.

      Input

      T: no of test cases

      T line follow

      every line has

      n , k

      Output

      max possible number

      Example

      Input:
      2
      1223 2
      8756 2
      Output:
      23
      87
      Explanation:

      Note that left to right order should be maintained. As in the example given answer is 23 not 32.


      Added by:praveen123
      Date:2013-02-09
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:general









      SPOJ Problem Set (classical)

      13707. SHAHBAG

      Problem code: SHAHBG

      They say "History repeats itself" and this is what happening in Bangladesh on Feb 2013.  Mass people fought the war in 1971 and now they are rising again to fight war criminals who betrayed the country. In "Shahbag" you can hear the voice of people wanting justice.

      Shabag protest

       

      If you go to shahbag you can see many human chains. For this problem we imagine a straight line going through middle of shahbag. Each position of the line is marked from 1 to 20000.

       

      People are forming human chains along the line. Initially every position is empty. When someone stands in ith  position he holds hand of people who are standing in his left and right(if there any) and join there group. If there are no people beside him, he forms a new group.

      When a new people come your job is to mark his position and count currently how many groups are there in shahbag.

      For example suppose:
         a man came first and stood in postion 2. Currently there are only 1 group.
         then another man stood in position 4. Currently there are 2 groups.
         another man stood in position 3. Now there are only 1 group.

      And yes, people wont leave until they get justice, so no need to worry about that.mi

      Input:

      There will be a single case. First line will contain an integer Q which denotes number of people. Next line will contain Q(1<=Q<=20000) integers pi which denotes position of i-th people that joined the chain. Each pi will be distinct and at most 20000.

      Output:

      For each pi print number of groups currently in shahbag. In last line print the string "Justice". Dont print any extra spaces.

       

      Sample Input:

      6
      2 4 3 6 7 5

       

      Sample output:

      1
      2
      1
      2
      2
      1
      Justice

       

      Note:

      This problem is based on true event. You can find the details here.

      Alternate writer: Rashedul Hasan Rijul


      Added by:Shafaet
      Date:2013-02-11
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      13738. Happy Valentine Day (Valentine Maze Game)

      Problem code: A_W_S_N

      Happy Valentine Day!

      Valentine Maze

      Picture Source: http://www.printactivities.com/Mazes/Shape_Mazes/Heart_Maze.html

      In this valentine day, Tjandra Satria Gunawan (TSG) have a mission to date with A** W****** S****** N******(AWSN), Before TSG meet AWSN, TSG want to collect all the chocolate in entire land/maze then share all the chocolate with AWSN later, but AWSN doesn't like to wait, so TSG must collect all chocolate as fast as possible before meet AWSN. Please help TSG to complete this mission. Given a map size m×n (1<m,n≤100), and the map:

      '#' denoting wall (TSG can't walk to this area)

      '.' denotning road (TSG can walk to this area)

      'C' denoting chocolate (also walkable area, appear less than 10 times on the map)

      'T' denoting TSG (also walkable area, only appear once on the map)

      'W' denoting AWSN (also walkable area, only appear once on the map)

      Tjandra can move up, down, left or right, and cost one unit of time every movement.

      Input

      The first line of input, there's one integer T (T≤30) denoting number of test case, then T case(s) follow,

      For each test case:

      --> First line contains two integers m and n denoting size of map

      --> next m line(s) contains n characters that's the map description.

      Output

      For each test case, output minimum of tme required to complete this mission, if it's impossible to complete this mission, output "Mission Failed!" without quotes.

      Example

      Input:
      8
      3 3
      T..
      ...
      ..W
      3 6
      ######
      #T..W#
      ######
      3 6
      ######
      #T#.W#
      ######
      3 6
      ##C###
      #T..W#
      ######
      3 6
      C#C###
      .T..W#
      ######
      5 10
      ##########
      #T.#.C#..#
      #..#..#..#
      #..W..#..#
      ##########
      5 10
      ##########
      #T.#.C#.C#
      #..#..#..#
      #..W..#..#
      ##########
      5 10
      ##########
      #C.#.C#.C#
      #..#..#..#
      #..T..W..#
      ##########
      Output:
      4
      3
      Mission Failed!
      5
      9
      12
      Mission Failed!
      23

       

       

      Time Limit ≈ 5*(My Program (Semi Bruteforce) Speed)

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-02-14
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:My Love (A_W_S_N) \(^_^)/ I love her since 2008 (when I was studying at EKASMA High School) until present ;-)









      SPOJ Problem Set ()

      13745. Crack the Safe

      Problem code: SAFECRAC

      Johnny (not little anymore) is a super agent .He is been following up on leads against the world’s worst terrorists. He got a intel that a terrorist is staying at an expensive hotel. Only thing that stops LJ is the secure door in the room entrance.

      The secure door had a lock which resembled this,

      1

      2

      3

      4

      5

      6

      7

      8

      9

      0

      Enter

      The enter key cannot be a part of the pass-code

      When Johnny did some spy work on it, he found out that every pair of neighbouring digits in the pass code is adjacent on the keypad. Adjacent means that the digits share a common edge.

      Now he wants to know how many different possibilities are there for the pass code so that he can bring a computer accordingly to hack the lock.

      Input:

      Input begins with single integer ‘T’ denoting number of test cases and T lines follow. Each line contains the number ‘N’ denoting the length of the pass code.

      Output:

      For each test case T, output the number of different possibilities in a new line. Since the answer can be huge output the number mod 1000000007


      Constraints:
      1 <= T <= 1,000

      1 <= N <= 100,000


      Sample input:
      2
      3
      25

      Sample output:
      74
      478325846


       


      Added by:J.A.R.V.I.S.
      Date:2013-02-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      13753. Amazing Prime Sequence

      Problem code: APS

      Bablu is very fond of Series and Sequences...

      After studying Fibonacci Series in Class IX, he was impressed and he designed his own sequence as follows...

      a[0] = a[1] = 0 

      For n > 1, a[n] = a[n - 1] + f(n), where f(n) is smallest prime factor of n.

      He is also very fond of programming and thus made a small program to find a[n], but since he is in Class IX, he is not very good at programming. So, he asks you for help. Your task is to find a[n] for the above sequence....

      Input

      Your code will be checked for multiple Test Cases.

      First Line of Input contains T (<= 100), the number of Test Cases.

      Next T lines contain a single number N. (1 < N < 10^7).

      Output

      Single line containing a[n] i.e. nth number of the sequence for each test case.

      Example

      Input:
      3
      2
      3
      4
      
      Output:
      2
      
      5
      7

      Added by:c[R]@zY f[R]0G
      Date:2013-02-14
      Time limit:1s
      Source limit:5000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13768. An Experiment by Penny

      Problem code: CRAN01

      Penny started studying in a community college. However she did not tell Leonard about this because she did not want Leonard helping her at every point in her studies. This went well until the professor ordered her to perform an advanced experiment. In this experiment she was given an advanced microbiological specimen. This specimen is placed in an n X m size grid which is divided into 1 X 1 cells.

      It expands according to following rules.

      If at time t, the specimen occupies  (x ,y), then at time t+1 it can expand to at most any two cells out of (x+1,y), (x-1,y), (x,y+1), (x,y-1).

      For example if at t = 0 sec if the specimen occupies (4, 5), then at time t = 1 sec, the state of the grid can be any of the following

      1. specimen at (4,5), (5,5) and (3,5).

      2. specimen at (4,5), (5,5) and (4,6).

      3. specimen at (4,5), (5,5) and (3,4).

      4. specimen at (4,5), (3,5) and (4,6).

      5. specimen at (4,5), (3,5) and (4,4).

      6. specimen at (4,5), (4,6) and (4,4).

      Note- At t= 2 sec, it can expand from all the points that the specimen occupied at t= 1.

      The professor asks penny to find the minimum time it takes for the specimen to fill the entire grid.

      Since penny is not so smart at math and she can't ask Leonard to help her, she turns to you for help and to find the solution to above problem.

       

      Input

      T - The number of test cases.

      n m - number of row and columns in the grid.

      x y - coordinate of the initial position of the specimen.

       

      Output

      The minimum time in seconds it takes for specimen to fill in the entire grid.

       

      Constraints

      1 <= T <= 50

      1 <= n, m <= 500

      1 <= x <= n

      1 <= y <= m

       

      Example

      Input:
      2
      1 1
      1 1
      10 10
      6 4 Output: 0
      11

      Added by:CSI
      Date:2013-02-16
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13769. Roommate Agreement

      Problem code: CRAN02

      Leonard was always sickened by how Sheldon considered himself better than him. To decide once and for all who is better among them they decided to ask each other a puzzle. Sheldon pointed out that according to Roommate Agreement Sheldon will ask first. Leonard seeing an opportunity decided that the winner will get to rewrite the Roommate Agreement.

      Sheldon thought for a moment then agreed to the terms thinking that Leonard will never be able to answer right. For Leonard, Sheldon thought of a puzzle which is as follows. He gave Leonard n numbers, which can be both positive and negative. Leonard had to find the number of continuous sequence of numbers such that their sum is zero.

       For example if the sequence is- 5, 2, -2, 5, -5, 9

      There are 3 such sequences

      2, -2

      5, -5

      2, -2, 5, -5

      Since this is a golden opportunity for Leonard to rewrite the Roommate Agreement and get rid of Sheldon's ridiculous clauses, he can't afford to lose. So he turns to you for help. Don't let him down.

       

      Input

      First line contains T - number of test cases

      Second line contains n - the number of elements in a particular test case.

      Next line contain n elements, ai  (1<=i<= n) separated by spaces.

       

      Output

      The number of such sequences whose sum if zero.

       

      Constraints

      1<=t<=5

      1<=n<=10^6

      -10<= ai <= 10

       

      Example

      Input:
      

      2

      4

      0 1 -1 0

      6

      5 2 -2 5 -5 9

      Output:

      6
      3

      Added by:CSI
      Date:2013-02-16
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set ()

      13780. Audition

      Problem code: CRAN04

      Penny is a terrible waitress and even worse actress, however recently she applied for a role in an upcoming TV series. Even though she thought she had no chance, she was called for an audition. She was very happy about it until she found out that her character in this new series will be a studious, high IQ girl named Megan. Producer told her that to get the role of Megan she had to prove that her mind can handle a bit of mathematics and reasoning. If she passed the test then she will be given the role of Megan. The test was as follow.

      The people (Boys and Girls) who came for audition are standing in a line in a random order. Producer has to select exactly K boys for the show. So he asks Penny to tell how many ways can he select two numbers i and j such that the number of boys standing between these (including I and j) indexes is exactly K.

      Penny desperately needs this role. Everybody knows that Penny is not a very smart and requests you to help her.

       

      Input

      First line contains T – The number of test cases.

      Next line contains space separated N and K.

      N – The total number of boys and girls who came to audition.

      K – The number of the boys who must be there between each (i, j) pair.

      Next line contains a non-empty string consisting of '1' and '0'.

      1 represents Boy.

      0 represents Girl.

       

      Output

      The number of (i, j) pairs such that the number of boys between index i and j, both inclusive is equal to K.

       

      Constraints

      1<=T<=10

      1<=N<=10^6

      0<=K<=10^6

       

      Example

      Input:
      

      3

      4 1

      0101

      5 2

      01010

      5 4

      01010

      Output: 6
      4
      0

      Added by:CSI
      Date:2013-02-16
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: AWK CLOJ ERL F# GO JS NODEJS PERL 6 PYTH 3.2.3 n SCALA SED TCL









      SPOJ Problem Set (classical)

      13799. Naive Loki

      Problem code: NAIVELOK


      Loki has succeeded in his devilish scheme and opened the portal to Asgard to summon his army to earth.
      To protect earth from this predicament, Iron Man must find a way to close this portal. He notices that the passcode on the portal is a palindromic string S. Also no character in this string occurs more than 2 times. Iron man can remove any number of characters from this string. Genius that he is, he deduces that the portal will close whenever the string is a non-palindrome. But that is too easy for him. So he waits and wonders how many different ways there are to achieve this. Two ways are considered different if there exists an i such that character at index i is removed in one way and not removed in another.

      INPUT :
      The first line of input contains a single line T, which represents the number of test cases. Then T lines will follow, and each contains a palindromic string S .

      OUTPUT:
      Print required answer for each test case in a new line. Since the number can be large print it Modulo 1000000007.

      CONSTRAINTS
      1<= T <=1000
      1<= |S| <= 100 ,where |S| represents the length of the string S.
      The string S is case sensitive, and will contain only characters in the range [a-z], [A-Z], [0-9].
      There would be at most two positions in S which will contain same character .
      Memory Limit : 32MB
      Time Limit : 1second
      EXAMPLE

      INPUT:

      2
      AA
      b99b

      OUTPUT:
      0
      6

      EXPLANATION :
      In the first sample case there is no way in which string can be converted to non-palindrome .
      In the second sample case there are 6 ways to convert string to non-palindromic namely ,
      i) Remove 1st character : 99b
      ii) Remove 1st, 2nd characters : 9b
      iii) Remove 1st, 3rd characters : 9b
      iv) Remove 2nd, 4th characters : b9
      v) Remove 3rd, 4th characters : b9
      vi) Remove 4th character : b99


      Added by:smit hinsu
      Date:2013-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:CodeCraft 13 , own problem









      SPOJ Problem Set (classical)

      13801. Dexter Rank

      Problem code: DEXTER

      Dexter just participated in a coding contest and is now waiting for judge to give final result . He is very bored of waiting every time for result and now wants to find his expected rank based on current scoreboard and chances of failure for problems. Formally there are M problems in the contest and there are N coders in the contest. Dexter knows that coder i has submitted problem j with penalty of penalty[i][j] . Dexter knows that problem j will pass with probability prob[j] ( this also applies for Dexter himself also :) ) . This is independent for each coder and problem. Now Dexter wants to know what would be his expected rank after system test.

      Note: Coders are ranked based on number of correct solution, then total penalty for correct solutions. If there is tie even after that, all coders with same problems and penalty are given same rank.

      Example : After system test if scoreboard is like this :

      Coder 1 : 300  -1     -1             Score : 1  Penalty : 300
      Coder 2 : 100  -1     200          Score : 2  Penalty : 300
      Coder 3 : -1     300  -1             Score : 1  Penalty : 300
      Coder 4 : -1     -1     400          Score : 1  Penalty : 400

      Ranks would be : 2 1 2 4

      INPUT :
      The first line of input contains a single line T , which represents the number of test cases. F
      For each test case first line contains two space separated integers N and M .
      Then Next N lines contains M integers , j’th integer on i’th is penalty[i][j] which means penalty for ith coder on problem j , if he submitted j’th problem, otherwise it is -1 .
      Dexter is first coder in the list .
      Then next line contains M space separated integers, where ith integer denotes probability of passing problem i in system test, if submitted.


      OUTPUT:
      Print the expected rank of the Dexter after system test with exactly 4 decimal places.

      CONSTRAINTS
      1 <= T <= 16
      2 <= N <= 256
      1 <= M <= 12
      1 <= penalty[i][j] <= 1000000 or penalty[i][j] = -1
      0 <= prob[i] <= 100

          
      EXAMPLE

      INPUT:

      3
      2 1
      100
      150
      50
      2 2
      -1 -1
      10 -1
      0 100
      3 2
      100 200
      -1 199
      99 -1
      50 50


      OUTPUT:
      1.2500
      1.0000
      1.6250


      EXPLANATION :
      For sample case 1 , Dexter would have first rank if his solution passes or coder-2’s solution fails system test which has probability 0.75 , otherwise he would have rank 2
      answer = 1*0.75 + 0.25*2 = 1.2500

      For sample case 2 , All coders would be on rank 1 with 0 problem solved and 0 penalty in all cases , so answer = 1.0000


      Added by:smit hinsu
      Date:2013-02-18
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:CodeCraft 13 , own problem









      SPOJ Problem Set (classical)

      13805. X-MEN

      Problem code: XMEN

      Dr. Charles Xavier is trying to check the correlation between the DNA samples of Magneto and Wolverine. Both the DNAs are of length N, and can be described by using all integers between 1 to N exactly once. The correlation between two DNAs is defined as the Longest Common Subsequence of both the DNAs.
      Help Dr. Xavier find the correlation between the two DNAs.

      Input :

      First line of input contains number of Test Cases T.
      ach test case starts with an integer N, size of DNA.
      Next two lines contains N integers each, first line depicting the sequence of Magneto's DNA and second line depicting Wolverine's DNA.

      Output :

      For each test case print one integer, the correlation between the two DNAs.

      Sample Input :

      2
      2
      1 2
      2 1
      3
      1 2 3
      1 3 2
      

      Sample Output :

      1
      2
      

      Constraints :

      1 ≤ T ≤ 10
      1 ≤ N ≤ 100000


      Added by:smit hinsu
      Date:2013-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:CodeCraft 13 , Author : Nadeem Moidu









      SPOJ Problem Set (classical)

      13806. Chaos In Arkham

      Problem code: CHAOS_CC

      Mayhem has struck Arkham Asylum!
      Both Bane and Joker are running free in Arkham and rescuing other prisoners. The prison of Arkham consists of N cells in a row. To decide who is superior, they play the following game: Both take turns alternately, and in each turn a player can open any one cell of the prison. They define a block of 3 consecutive open prison cells as a "crime hole". The first one to create a "crime hole" wins and is declared as the Ultimate Villain of Gotham. Joker plays first.
      As we know Bruce Wayne always keeps track of his enemies. In this situation he needs a program to decide who will emerge as the Ultimate Villain if both play optimally.

      INPUT:

      First line of input contains number of Test Cases T, followed by T lines. On each line you are given a single integer N, depicting the number of enemy camps.

      OUTPUT:

      For each N, print "Bane" if Bane wins, else print "Joker". (Quotes for clarity)

      CONSTRAINTS

      1 <= T <= 3333
      3 <= N <= 3333

      Example

      Input:

      3
      3
      5
      6

      Output:

      Joker
      Joker
      Bane

      Explanation:

      Let us denote the open cells by 'o' and closed cells by '-'.
      Case one: Initially all cells are closed(---), if Joker opens first cell configuration is (o--). Bane can either open second cell leading to configuration (oo-) or third cell (o-o). In both cases Joker wins.
      Case two: Joker wins by opening the 3rd cell i.e. configuration (--o--).


      Added by:smit hinsu
      Date:2013-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:CodeCraft 13 , Author : Nikhil Goyal









      SPOJ Problem Set (classical)

      13807. Rage Drug

      Problem code: RDRUG

      Dr. Banner (a.k.a. The Hulk) is synthesizing a drug that will help him control his rage. There are a total of N atoms of various atomic masses.
      Banner knows that to create a bond between two atoms the energy required is equal to the sum of the atomic masses of the two atoms.
      Currently some of the atoms are connected to one another forming compounds.
      Banner wants to join all separate atoms and compounds into a single compound by creating chemical bonds. Each atom can form at max one more bond. Help Dr. Banner to find out the minimum energy required to synthesize his drug.

      INPUT

      Input starts with an integer T, the number of test cases. Each test case starts with a line containing integers N, M denoting the number of atoms and the number of bonds already formed respectively. M lines contain 2 integers i and j denoting a chemical bond between the ith and the jth atom. The next N lines contains one integer each where the integer on ith line denotes the atomic mass of the ith atom.

      OUTPUT

      Print T lines, where the ith line is the answer to the ith test case. If it is not possible to link the atoms print -1;
      PS: If you mislead Dr. Banner, he might lose his temper and SMASH you to bits.

      CONSTRAINTS

      1 <= T <= 12
      1 <= N <= 100000
      1 <= AtomicMass <= 10000
      1 <= M <= 10^6 (1000000)
      1 <= i, j <= N

      Sample Input:

      2
      6 6
      1 2
      2 3
      1 3
      4 5
      5 6
      4 6
      1
      3
      5
      2
      4
      6
      4 0
      1
      2
      3   
      4
      
      
      

      Sample Output:

      3
      -1


      Added by:smit hinsu
      Date:2013-02-18
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:CodeCraft 13 , Author : Jay Pandya









      SPOJ Problem Set (classical)

      13808. Colors

      Problem code: COLOR_CC


      Given a Bipartite graph with N nodes, you have to colour each node in a way such that no two adjacent nodes have the same colour . Each node is allowed to choose colour from a subset of colours. print the possible number of ways.
      You are given a symmetric matrix i.e. matrix[i][j] is always equal to matrix[j][i]
      if matrix[i][j]=='Y' then nodes i and j are connected by an edge matrix[i][j]=='N' then nodes i and j are not connected

      Input

      T -number of test cases ( N test cases follow )

      N -number of nodes in graph . N lines corresponding to matrix

      N line follows : each line contains xi -- total colours ith node can take , followed by i colours

      Output

      Print the possible number of ways to colour the graph


      T would be less than 20
      0<= N <= 13
      size of matrix will be N*N
      each element of matrix would be either 'Y' or 'N'
      number of colours a node can take would be greater then equal to 0 and less than equal to 8 colour number would be less than 100000

      Example

      Input

      1

      4

      NYNN

      YNNN

      NNNY

      NNYN

      3 1 2 3

      2 4 5

      3 4 5 6

      3 1 2 3

       

      Output

      54


      Added by:smit hinsu
      Date:2013-02-18
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:CodeCraft 13 , Author : Shubhanshu Agarwal









      SPOJ Problem Set (classical)

      13809. ISRANK

      Problem code: ISRANK

      There are N schools, with i th school having Si students. There is a inter-school programming contest IPC in which all the schools participate. As IPC is a very prestigious event, the schools conduct a test run within themselves. They assign a predicted rank for students within the school for all students, based on the rank they got in the test run. Let Pij be the predicted rank of j th student of i th school. The predicted rank will be unique within the school, i.e. formally:

      It should be noted that students of different schools may have the same predicted rank.

      At the end of IPC, the IPC committee has given each school the result card containing the marks of all students of that school. Let Mij represent the actual marks obtained by the j th student of i th school. IPC follows a strict rule of giving unique marks to all students taking part in IPC, i.e. formally:


      You are to design a system, which will efficiently answer queries of the following form:
      L - the number of schools to be considered
      A1 A2 A3 .... AL - the list of schools
      P1 P2 - The range of predicted ranks
      K - desired rank
      You are to answer - among all the students who attended the given list of schools and with predicted ranks between P1 and P2 both inclusive, the marks of the student with K th highest marks. (The first highest marks would the the maximum marks, and second would be the next and so on)

       

      Input

      First line contains a single integer N, the number of schools.
      The next line contains N space separated integers Si.
      The next N lines, the i th line contains Si space separated integers, j th of which is denoting Pij.
      The next N lines, the i th line contains Si space separated integers, j th of which is denoting Mij.
      The next line contains a single integer Q, denoting the number of queries.
      Whats follows are Q sets of queries. Each query is structured as follows.
      First line of the query is L, the list of schools.
      Followed by L integers denoting the 1 based indices of schools.
      Next are P1 and P2, the range of ranks we are interested in.
      Next is the integer K.

       

       

      Output

      For each query on a separate line print a single integer answering the query. If answer is not possible print -1

       

       

      Constraints

      1 ≤ N ≤ 10
      1 ≤ Si ≤ 10000
      1 ≤ PijSi
      1 ≤ Mij ≤ 1000000000
      1 ≤ Q ≤ 10000
      1 ≤ P1 ≤ P2 ≤ max(S[i])
      1 ≤ K ≤ sum of all S[i]

       

      Sample Input

      4
      1 3 4 1 
      1 
      1 2 3 
      2 3 1 4 
      1 
      28 
      20 11 8 
      6 18 22 26 
      7 
      4
      1
      2 
      3 3
      1
      1
      2 
      3 3
      1
      3
      1 3 4 
      4 4
      1
      4
      1 2 3 4 
      4 4
      4
      

      Sample Output

      8
      8
      26
      -1
      


      Added by:smit hinsu
      Date:2013-02-18
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:CodeCraft 13 , Author : Kaushik Iska









      SPOJ Problem Set (classical)

      13815. India in Box

      Problem code: INBOX


      India in Box

       

      There is a well-known challenge in India. The challenge is as follows:

       

      A merchant had some boxes. The boxes had weight and cost. He wants to give K boxes to one guy and the rest to other guy. Each guy has an average that is calculated by taking (Sum of Weights) / (Sum of Costs) of this guy. He wants to know what the smallest possible sum of the averages of the two guys he can achieve by making the distribution of the boxes.

       

      Your task is to solve the challenge.

       

      Input

       

      The input contains several test cases. A test case begins with a line containing two integers N and K (1 <= K < N <= 100) representing the total number of boxes and the value of K, respectively. The next N lines contains two integers each, wi and ci (1 <= wi, ci <= 50), indicating the weight and cost of the ith box, respectively.

      The last test case is followed by a line containing a single 0.

       

      Output

       

      For each test case, print a line containing a single value, the smallest possible sum of the averages, accurate to 5 decimal places.

       

      Example

       

      Input

      Output

      8 4

      2 1

      3 2

      4 3

      5 4

      6 5

      7 6

      8 7

      10 8

      0 0

      2.49845

       


      Added by:Mateus Dantas [ UFCG ]
      Date:2013-02-19
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Mateus Dantas









      SPOJ Problem Set (classical)

      13816. Pheversos Game

      Problem code: PGAME


      Pheverso's Game

       

      Matheus Pheverso is a well-known rogue, as everyone knows he used to be very mean with the couple in love, Danilo Ghyei and Raphael Boboleta. But now he's trying to change into being a better person. In order to do that, he will call some friends over to play his newest game and throw a game party next year.

      The game “Pheverso's Game” is played in rounds by two contestants in which each one must pick one cell from a MxN board, add its number to the group's total score and then throw it away. Also, in order to avoid cheating, each cell is previously chosen and no one is allowed to choose a cell if it isn't at the beginning or at the end of some row. You also have to notice that when one cell is dropped, the row from where the cell has been taken gets a new configuration, resulting in a new beginning or a new end.

      Pheverso was playing that game with some friends and realized it's way too easy, so he decided to choose some rows and block their beginnings. When a row is blocked, a group is only able to choose a cell from the end of this row.

      The goal of the game for each contestant is to hoard as much as they can, so the winner of the game is the one who holds the maximum amount of points in the end of the game. The game finishes when there are no remaining cells.

      Assuming that they both plays optimally and given the N, M dimensions, the initial state of the board, the rows that are blocked, which player wins the game and what's the score of the winner.

       

      Input

      The input contains several test cases. A test case begins with a line containing integers N (1 N 1000), M (1 M 1000) and K (0 K < N), where N, M stands for the board dimensions and K for the total number of rows blocked. On the second line there are K integers, the rows that are blocked. Then follow N lines, each containing M integers representing the initial state of the board.

      Every number in the board is a 32 bit signed integer. The last test case is followed by a line containing three zeros.

       Output

      For each test case, print a line containing first” (without the quotes) if the first player will win the game or “second” (without the quotes) if the second player will win the game, followed by an integer representing the amount achieved by the winner when both of them plays optimally. The game always have a winner.  

      Example

      Input

      Output

      2 2 2

      1 2

      500 10

      3 10

      3 3 2

      1 3

      0 1 2

      3 7 4

      0 0 9

      0 0 0

      second 503

      first 17

       

      Explanation:

       

      First Case – At first the two rows are blocked, so both players aren't able to choose either cell A[1][1] = 500 or A[2][1] = 3. Thus, the first player isn't able to grab the cell A[1][2] either, cause he would unlock to his opponent the greatest piece in the board, A[1][1] = 500. So he choose the cell A[2][2] = 10. Afterward his opponent grabs the cell A[2][1] = 3, force the first player to choose A[1][2] and set free the greatest piece in the board, therefore the second player is the winner achieving 503 total points (A[1][1] + A[2][1]) against 20 from the first player.

       

      Second Case – The game is as follows:

      * firstPlayer: 9

      * secondPlayer: 2

      * firstPlayer: 1

      * secondPlayer: 3

      * firstPlayer: 7

      * secondPlayer: 4

       

      firstPlayer: 17 (Winner)

      secondPlayer: 9

       

      Remember, both contestants plays optimally.

       


      Added by:Mateus Dantas [ UFCG ]
      Date:2013-02-19
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13826. The Grandslam of Grandslams!

      Problem code: WIMB


      Problem:

      My boss hates me. He hates me to the extent where he plans meetings which clash with a Wimbledon match, almost all the time. Now, to give myself some inner peace, I decided to play well - while also trying to at least pray, that the matches I want to watch stretch enough for me to watch when I get back home.

      But hey, wait! I may have a shot here! At Wimbledon, matches are played only at day light, so maybe if players were not ready to give up easily on each point, then the match will extend until sunset - just for my convenience!

      So what I need to know is how long on average a game between two players will last, and to help me feel better you should write a computer program to determine that!

       

       

      The result of a tennis match is determined by the number of “sets” each player wins, the first player to win three sets wins the match. Accordingly, all possible match results are 3-0, 3-1 and 3-2. The result of each set is determined by the number of “games” in the set each player wins, the first player to win six or more games with two or more game difference from the opponent wins the set, however if the result of a set (including the last set) leveled at 6-6 then a tie-break game is played to determine the set winner, Accordingly all possible set results are 6-0, 6-1, 6-2, 6-3, 6-4, 7-5 and 7-6 using a tie breaker game!

      During each game (including tie-break), one player has the serve, this means that this player must start the play for all points of the game by hitting the ball, serving the ball is considered a big advantage. Assume that the serve starts at the first player and then alternates after each game till the end. Given the probability of winning a game on serve for each player against his opponent, and assuming that each game lasts for five minutes, calculate the expected duration of the match.

       

       

      Input:

       

      The first line of input contains an integer T, the number of test cases. The first line of each test case contains the first and last names of the first player, followed by an integer (0 <= A <= 100) where A/100 is the probability that the first player wins a game on his serve against the second player. The second line contains the first and last names of the second player, followed by an integer (0 <= B <= 100) where B/100 is the probability that the second player wins a game on his serve against the first player.

       

      Output:

      For each test case, print the duration of the match in minutes rounded to six decimal digits.

       

      Sample Input:

      2

      Pete Sampras 50

      Rafael Nadal 50

      Roger Federer 100

      Arjit Srivastava 0

       

      Sample Output:

      199.281006

      90.000000

       

      How?

      In the second test case, I don’t stand a chance against Pete! He always wins all games on his serve (probability 100/100) and he also always wins all games on my serve (as I win with probability 0/100), so he always wins the match with three straight sets (6-0, 6-0, 6-0), a total of 18 games played, each lasting five minutes for a total of 90 minutes match.


      Added by:Why so Rush?
      Date:2013-02-19
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LCPC









      SPOJ Problem Set (classical)

      13829. Tjandra 19th birthday present (HARD)

      Problem code: TJANDRA2


      The 07 February 2013 was Tjandra's 19th birthday, I want to make a present to him and all other great SPOJ solvers by the way. So I set this HARD puzzle problem extension of the yet good TJANDRAS.

      Warning : To solve the 'easy' task, you need a O(N^0.5) algorithm, but to solve this 'harder' task, you need something around O(N^0.34), so it's not about optimization tricks!!!
      Time limit = 6.666× my Python3 timing.
      Please note that I checked my data with my 'semi-brute-force'-O(N^0.5)-Python3-solution and it took me 16 hours.

      Don't forget to have fun with that problem!

      The Game

      This game/puzzle is about matches, given N matches, your task is to arrange the matches (not necessarily all) such that the number of rectangles (any size) is maximum.

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are one integer N.

      Output

      For each test case, on a single line, print the required answer (maximum number of rectangles).

      Example

      Input:
      5
      3
      4
      8
      12
      15
      987654321123456789
      
      Output:
      0
      1
      3
      9
      12
      60966316127114768913148159571503206
      

      Constraints

      1 < T ≤ 100
      1 < N ≤ 10^18
      

      The T numbers N are uniform-randomly chosen in the range.

      Explanations

      First test case:
      No rectangle can be formed with only 3 matches.

      Second test case:
      Only one rectangle can be formed with 4 matches.

      Third test case:
      There are max 3 rectangles.
      (2 size 1x1, 1 size 2x1) can be formed with number of matches ≤ 8, here is one of the matches formation:
      Case 3 - Fig

      Fourth test case:
      There are max 9 rectangles.
      (4 size 1x1, 2 size 2x1, 2 size 1x2, 1 size 2x2) can be formed with number of matches ≤ 12, here is one of the formation:
      Case 4 - Fig

      Fifth test case:
      there are max 12 rectangles.
      (5 size 1x1, 3 size 2x1, 1 size 3x1, 2 size 1x2, 1 size 2x2) can be formed with number of matches ≤ 15, here is one of the formation:
      Case 5 - Fig

      Sixth test case:
      You have to figure by yourself how to compute that in the required time.


      Added by:Francky
      Date:2013-02-19
      Time limit:19s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:









      SPOJ Problem Set (classical)

      13833. Super Borboletas World

      Problem code: SBW



       Super Borboleta World

      The input/output were broken, I've fixed it and rejudged all submissions. 

       

      Raphaell is a well-known programmer who created the biggest game development company in the world, BGM (Boboleta's GameMaker). As recently one of its game – S.B.W (Super Borboleta's World) - has became very popular, Raphaell decided to make an online version of S.B.W's game. In order to do this he'll expose the source code and the mechanism of that game so anyone is able to improve it.

      At first the game is made of three main operations in which the user is able to call as much as necessary. As the game is composed by K arrays of lists where each list has at most N integers on it, the three operations can be described in the following way:

      - Operation <2> <x> <y>: Insert the integer <y> to the end of the <x>-th list.

      - Operation <1> <x> <y>: Clean every list whose index lie on the range between <x> and <y> (inclusive).

      - Operation <0> <x> <y>: In each list between <x> and <y> calculate all the possible consecutive XOR sum's, where XOR stands for the operation Exclusive OR, and return the maximum value of all possible XOR sum's.

      Raphaell has access to the original pseudocode which is given bellow:

       

      m <- array( array() )
      
      def insert(x,y):
              insert y to m[x]
      
      def clear(x,y):
              for i<-x to y:
                      clear m[i]
      
      def max_xor(x,y):
              best <- 0
              for i<-0 to sizeOf m[x]:
                      sum_xor <- 0
                      for j<-i to sizeOf m[x]:
                              sum_xor <- sum_xor (xor) m[x][j]
                              best <- max(best,sum_xor)
              if x < y:
                      best <- max(best, max_xor(x+1,y))
              return best

      This implementation was efficient to the offline version of the game. However, as the online version may receive a thousands of players at once, it's necessary many optimizations to run the game properly. Even though his friend has already tried really hard to figure a way to improve the performance, he hasn't got any good results till now. 

      Input

      The input contains several test cases. A test case begins with a line containing an integer Q (1 Q 10^5), where Q represents the number of operations that are going to be performed. Then follow Q lines, each containing an operation. All the operations are as described above:

      - 0 x y: In each list between x and y calculate all the possible consecutive XOR sum's and return the maximum possible value.

      - 1 x y: Clean every list whose index lie on the range between x and y inclusive.

      - 2 x y: Insert the integer y to the end of the x-th list.

      Both x and y in every operation will never exceed 10^14. The last test case is followed by a line containing a single 0.

      Output

       

      For each query <0> <x> <y> print a line containing a single integer representing the maximum possible XOR as described above.

       

      Example

      Input

      Output

      14

      2 2 1

      2 2 2

      2 2 1

      2 2 1

      2 2 2

      2 3 1

      2 3 2

      2 3 7

      0 1 2

      0 2 3

      1 3 3

      0 1 3

      1 1 3

      0 1 3

      0

      3

      7

      3

      0

       


      Added by:Mateus Dantas [ UFCG ]
      Date:2013-02-19
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13838. Mosty! Find Gn

      Problem code: M_SEQ


      Omar want to examine Mostafa in math , Mostafa asked to give G(n) that defined as :

      G(n) = sqrt( F(n) - ( (n-1)^2 * F(n-1) / n^2 ) + 1/n^2  )

      while :

       

      F(n) = 8 + (   ((n-2)^2 )*(F(n-2)) /n^2  )

       

      Mostafa need your help to find G(n) ( n : givin integer)

      assume that : F(1) = 8 , F(2) = 8;

      Input

      T number of test cases in the first line , T line follow with an integer n .

      Output

      Print G(n) for each test case with 8 decimal digits after the point ( 0 < G(n) < 3)

      Example

      Input:
      3
      5
      7
      42

      Output:
      2.20000000
      2.14285714
      2.02380952
      T < 10^4
      2 < n < 10^9

      Added by:omar alkattan
      Date:2013-02-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      13868. Roads of NITT

      Problem code: NITTROAD


      The Institute of NITT believes in frugality. So when they made the plan for interconnecting the N hostels, they decided to construct as few bidirectional roads as possible. The hostels are interconnected with roads in such a way that every pair of hostels is connected by exactly one path.
      Moreover, they were so frugal that they used low quality tar in making the roads. As a result, the roads start to crack and cannot be used anymore.
      Now Alpa has a set of queries. At the time of each query, he knows the roads that are un-usable. He wants to find the number of pairs of hostels that are disconnected, i.e, the number of pairs (x,y) such that 1 <= x < y <= N and there exists no path between hostels x and y.
      Help him find the result for each query.


      The Institute of NITT believes in frugality. So when they made the plan for interconnecting the N hostels, they decided to construct as few bidirectional roads as possible. The hostels are interconnected with roads in such a way that every pair of hostels is connected by exactly one path.


      Moreover, they were so frugal that they used low quality tar in making the roads. As a result, the roads start to crack and cannot be used anymore.


      Now Alpa has a set of queries. At the time of each query, he knows the roads that are un-usable. He wants to find the number of pairs of hostels that are disconnected, i.e, the number of pairs (x,y) such that 1 <= x < y <= N and there exists no path between hostels x and y.


      Help him find the result for each query.


      Constraints:


      Test cases <= 5

      No. of hostels, N <= 20000

      No. of queries, Q <= 20000



      Input


      First line contains t, the total test cases.

      Each test case looks  as follows:

      First line contains N, total number of hostels.

      Next N - 1 lines contain two integers x and y, indicating that there is a road  between x and y. (1 <= x < y <= N). The roads are numbered from 1 to N - 1.

      Next line contains Q, total number of queries.

      Next Q lines contain the Q queries.

      Each query may be of the following two forms:

      R x - Remove the road numbered x. It is guaranteed that this road existsand hasn't already been removed.

      Q - Output the total number of pairs (x, y) such that 1 <= x < y <= N and there exists no path between hostels x and y.


      Output

      For each test case,

      Output a line for each query with the required value.

      Print a blank line after each test case.

       

      Example

      Input:
      2
      
      3
      1 2
      1 3
      5
      Q
      R 1
      Q
      R 2
      Q
      
      4
      1 2
      1 3
      1 4
      7
      Q
      R 1
      Q
      R 2
      Q
      R 3
      Q
      
      Output:
      0
      2
      3
      
      0
      3
      5
      6

       




      Added by:Aditya Muraletharan
      Date:2013-02-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:That would be me.









      SPOJ Problem Set (classical)

      13875. Knifes Are Fun

      Problem code: JOKER1


       

      " Guns are too quick. You can't savor all the little emotions. You see, in their last moments, people show you who they really 
      are. So in a way, I know your friends better than you ever did. Would you like to know which of them were cowards?"
      Joker has many knifes, and he wants to assign a distinct integer to each knife so he can easily identify them. The i-th knife 
      can have an integer between 1 and maxNumber[i], inclusive.
      Return the number of ways he can assign numbers to his knifes, modulo 1,000,000,007. If it's impossible to assign distinct 
      integers to the knifes, print 0.

       

      "Do you know, why I use a knife? Guns are too quick. You can't savor all the little emotions. You see, in their last moments, people show you who they really are. So in a way, I know your friends better than you ever did. Would you like to know which of them were cowards?"


      Joker has many knifes, and he wants to assign a distinct integer to each knife so he can easily identify them. The i-th knife can have an integer between 1 and maxNumber[i], inclusive.

      Return the number of ways he can assign numbers to his knifes, modulo 1,000,000,007. If it's impossible to assign distinct integers to the knifes, print 0.

       

       

      Input

       

      The first line contains the number of test cases T (1<=T<=666)

      Each test case has 2 lines - 1st line denotes number of knifes ,N (1<=N<=66) Joker has and the 2nd line denotes the numbers {maxNumber[0]....maxNumber[N-1]} Joker has.

      1<=maxNumber[i]<=3000

       

      Output

       

      Print the number of ways Joker can assign numbers to his knifes, modulo 1,000,000,007. If it's impossible to assign distinct integers to the knifes, print 0.In last line print the string "KILL BATMAN\n".Dont print any extra spaces.

       

      Example

      Input:
      3
      1
      7
      2
      5 8
      3
      2 1 2
      
      Output:
      7
      35
      0
      KILL BATMAN
      
      Explanation :
      Test case 1 : Joker can assign any number between 1 and 7, inclusive, to the only knife.
      Test case 2 : Joker wants you too think !
      Test case 3 : (1,1,1) (1,1,2) (2,1,1) (2,1,2) are the possible combinations . As the numbering of knifes is not unique so the output is 0.

      Added by:Rajarshi Sarkar
      Date:2013-02-23
      Time limit:0.5s
      Source limit:5000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13881. FUN WITH LETTERS

      Problem code: FUNNUMS


             Mr. Bean’s uncle gifted him 15 English letter toys from 'a' to 'o'. As Mr. Bean is a joker, no one was willing to play with him. So he sat on the floor and arranged these toys in ascending order i.e. “abcdefghijklmno”. Then he figured out the next greatest word in lexicographic order that can be formed by rearranging the toys is “abcdefghijklmon”. Now he is learning programming and wants to write a program to solve the following problem: Given all the words that can be formed by rearranging letters form the given word S, find the N-th greater word in lexicographic order. You can safely assume that such a word always exists.


      Input Specification:

      The first line contains a natural number T denoting the number of test cases. Next T lines contain the description of T test cases, each with string S and value N.

      Output Specification:

      For each test case print the answer in a separate line.

      Input Constraints:

       

      1<=t<=1000

      2<=S.length()<=15

      'a'<=S[i]<='a'+S.length()-1

      All letters in S are unique.

       

      Sample Input:

      3

      abdc 2

      adcb 3

      badc 7

      Sample Output:

      acdb

      bcad

      cbad


      Added by:cegprakash
      Date:2013-02-24
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13882. THE WITTY BOY

      Problem code: WITTYBOY


      The television at the boy's home contains the channels from 1 to n inclusive. The father wanted to avoid his son to watch some channels in the Television. You are given k unique channels that are banned by the father.
      For example assume that the TV contains 25 channels and the father bans the channels 15, 17 and 18 and you are currently at channel 16. If you press the 'down' button in the remote,  you will move to channel 14 and if you press the 'up' button in the remote, you will move to channel 19. Also if you press up button from channel 25 you will move to channel 1 and if you press down button from channel 1 you will move to channel 25.
      There are 13 buttons in the remote as shown in the figure.


      To move to a channel you can press the digits of the channel or you can use Up/Down/Previous buttons. The previous button will take you to the immediately previous channel you watched. (The previous button does not take effect until you have moved to some other channel after the first one.)

      The remote control responds to delays. So you can take the button presses "1" and "9" either as a way to go to channel 1 and then to channel 9, or to channel 19 directly.

      You are given the sequence of channels that the boy wanted to watch. Find the minimum number of remote button presses required by the boy. It's not necessary to watch the given channels consecutively, but it is necessary to watch them in the order specified. (In other words, the given sequence must be a subsequence of the optimal channel series the boy chooses to watch.)

      To watch the first channel in the sequence, you must press the digits of the channel.


      Input:

      The first line consists of and integer t, the number of test cases. Each test case consists of 4 lines. The first line consists of 2 integers n and k, the number of channels in the remote and the number of channels blocked. The next line consists of k unique integers - the id of the blocked channels. The next line consists of an integer m the number of channels the boy wants to watch followed by a line with m integers - the channel id's of the channels that the boy wants to watch.

      Output:

      For each test case print the minimum number of remote button clicks required.

      Input Constraints:

      1<=t<=100

      1<=k<n<=1000

      1<=m<=1000

      ChannelToWatch[i] != ChannelToWatch[i-1]

      ChannelToWatch[any] != BannedChannel[any]


      Sample Input:

      3

      5 0

       

      5

      1 2 3 4 5

      500 0

       

      4

      140 160 139 160

      5 2

      2 4

      5

      1 3 5 3 5

      Sample Output:

      Case #1: 5

      Case #2: 9

      Case #3: 5

       

      Note: Suppose you are currently at channel 6 and press up button twice you will move to channel 8. Now if you click on previous button, you will move to channel 7 and not channel 6.

      Exlanation of Case #2:

      The moves are "1", "4", "0", "down", "1", "6", "0", "previous", "previous"

       

      Congrats and thanks to Mitch Schwartz for solving this problem first and for helping on setting test cases for this problem.


      Added by:cegprakash
      Date:2013-02-24
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      13884. FLING1

      Problem code: FLING1


      Fling! is a popular puzzle game created by the well-known developers at CandyCane LLC.

      The premise of the game is simple. You are given a certain number of balls on the screen to start. The goal is to fling one into another in order to knock the other off the screen. The puzzle is considered solved if you can do so while leaving only one ball remaining on the screen. Some might read this and think that it might not be too difficult, but the game gets challenging quickly. The problem is that you cannot fling two balls that are adjacent (i.e. next to) each other.

      The first ball you choose can fling the 2nd ball if and only if..
          1) The two balls exist in same row or same column
          2) The two balls are not adjacent
          3) There is no other ball in between the two balls

      If there exist a 3rd ball after the 2nd ball in the same line of action, the 2nd ball takes the position just before the third ball, pushes the 3rd ball and the 3rd ball gets flinged. (This continues till a ball gets knocked off the screen. Note that 2nd ball and 3rd ball can be adjacent).


      Given a Fling! puzzle, just print "Yes" if it is a valid puzzle(solvable) or "No" otherwise.

      For better understanding of gameplay you may have a look at this video. (optional)

       

      Input:


      The first line of the input consists of an integer t, the number of test cases. For each test case, the first line consists of two integers m and n, the number of rows and columns of the puzzle. Then follows the description of the board. A[i][j] is '.' if the cell is empty or 'B' if the cell has a ball.

      Output:

      For each test case print "Yes" if the puzzle is valid or "No" otherwise. (case-sensitive).

      Input Constraints:

      1<=t<=100

      1<=m,n<=10

      You can assume that the number of balls in the board is approximately equal to ( m x n ) /10

      Sample Input:

      4

      5 5

      ..... 

      .....

      ..B..

      .....

      .B..B

      5 4

      ....

      B...

      B...

      ....

      B...

      3 4

      BB..

      ....

      .B..

      1 1

      B

      Sample Output:

      Yes

      Yes

      No 

      Yes


      Added by:cegprakash
      Date:2013-02-24
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      13886. BLOCK_D SOLVER

      Problem code: BLOCK_D


      You are given a board of order mxn full of coloured blocks.



      At each move, you have to select a block of any colour which has atleast one of it's immediate neighbours of same colour. If you select a block, all the connected blocks(not just the immediate neighbours) of same colour gets destroyed. A block is connected to all the blocks that share an edge with it. Any block will fall directly down if there is no block immediately below it. If a complete column becomes empty, you must either push all the columns to it's left once in the right side or push all the columns to it's right once in the left side(These pushes are not considered as a moves. At each move, you will destroy more than one block).


      You will win the game if the remaining number of blocks becomes zero after making  the moves. Find the minimum number of moves to win the game. If it is impossible to win the game, print -1.

      For better understanding of gameplay you may have a look at this video. (optional)

      Input:

      The first line consists of an integer t, the number of test cases. For each test case the first line consists of two integers m, n the number of rows and columns respectively followed by the matrix representing the coloured blocks. Colour[i][j] contains any character between 'a' and 'e' inclusive.

      Output:

      For each test case print the minimum number of moves to win the game. If it is impossible to win, print -1.


      Input Constraints:

      1<=t<=10

      1<=m,n<=10

      'a'<=Colour[i][j]<='e'

      Sample Input:

      2

      5 5

      aaaba

      aaaba

      aaaba

      aaaba

      aaaba

      5 5

      bbbbb

      baabb

      bbbab

      bbbaa

      aabab

      Sample Output:

      2

      3


      Added by:cegprakash
      Date:2013-02-24
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      13895. Party Time

      Problem code: PARTYTIM

       

      In a n-storey resort a grand party is arranged in the nth floor of the building and two magical elevators A and B are stationed at the ground floor (zero th floor). 
      There are people waiting in all floors from to 0 to n-1 for attending the party. These two magical elevators are used for getting these people to the party. These elevators can be moved from one floor to any other floor. The time it takes to move any elevator from i th floor to j th floor is abs(j - i) time units.
      Also there is a cost associated with moving the elevator from i th floor to j th floor. 
      If the elevator A moves from floor i to floor j with x people, then cost equals A[i] ^ A[j] ^ x, where '^' is the bitwise XOR operator. Similarly for the elevator B, it is B[i] ^ B[j] ^ x. However, if the number of people in the elevator changes at any instant (say floor k) to y, then new cost is A[i] ^ A[k] ^ x + A[k] ^ A[j] ^ y (see notes).
      People who are inside the elevator can be made to get down from it at any floor that it stops. It takes zero time for people to get into or out of the elevator. 
      All persons who are waiting have to be taken to the nth floor. As the party is going to start immediately the resort manager wants everyone to be there in the party in the least time possible. It is your job to control these elevators in such a way that everyone is there in the party in the least time possible and also minimize the cost of controlling these elevators.
      Notes:
      1. The objective is to get all the people waiting in floors 0, 1....n - 1 to floor n.
      2. The elevators can move up or down.
      3. It takes zero time for the elevator to stop at any floor and for people to get down or get into the elevator.
      4. If Lift A carries 5 persons from 2nd floor to 6th floor, cost = A[2] ^ A[6] ^ 5
      5. If 1 more person enters Lift A on the 4th floor, the cost will be (A[2] ^ A[4] ^ 5) + (A[4] ^ A[6] ^ 6)
      Constraints:
       1 <= n <= 30;
       The sum of people waiting in all floors won't exceed 1000 and there is atleast one person waiting in every floor from 0 to n-1.
       All values of the array A and B are non-negative numbers lesser than or equal to 1000.
      Input:
      First Line consists of an integer denoting the number of test cases(atmost 10).
      Every test case will be of the following form.
      First line contains n the number of floors in the building.
      Second line contains n+1 integers: A[0], A[1].....A[n].
      Third line contains n+1 integers: B[0], B[1]......B[n].
      Fourth line contains n integers: The number of persons waiting in each floor from 0 to n - 1.
      Output:
      For every test case output one integer on a new line: the minimum cost for operating the elevators and ensuring that all people reach the n'th floor.
      Example
      Sample Input:
      2
      2
      0 1 3
      0 1 5
      2 1
      4
      1 3 5 7 9
      2 4 6 8 10
      1 2 3 4
      Sample Output:
      1
      18
      Explanation:
      In the first test case, 
      1. Lift A carries 1 person from 0th floor to 1st floor. Cost = A[0] ^ A[1] ^ 1 = 0
      2. Lift B carries 1 person from 0th floor to 1st floor. Cost = B[0] ^ B[1] ^ 1 = 0
      3. The person waiting in 1st floor and person from Lift A both move to Lift B. Lift B carries 3 people from 1st floor to 2nd floor. Cost = B[1] ^ B[2] ^ 3 = 1
      4. All persons have reached the party in 2 time units and incurring a cost of 1.

       

      In a n-storey resort a grand party is arranged in the nth floor of the building and two magical elevators A and B are stationed at the ground floor (zero th floor). 

      There are people waiting in all floors from to 0 to n-1 for attending the party. These two magical elevators are used for getting these people to the party. These elevators can be moved from one floor to any other floor. The time it takes to move any elevator from i th floor to j th floor is abs(j - i) time units.

      Also there is a cost associated with moving the elevator from i th floor to j th floor. 

      If the elevator A moves from floor i to floor j with x people, then cost equals A[i] ^ A[j] ^ x, where '^' is the bitwise XOR operator. Similarly for the elevator B, it is B[i] ^ B[j] ^ x. However, if the lift stops on the k'th floor and 'a' people get on the elevator and 'b' people get off the elevator, to make a new count of 'y' people, then new cost is (A[i] ^ A[k] ^ x) + (A[k] ^ A[j] ^ y). (see notes).

       

      People who are inside the elevator can be made to get down from it at any floor that it stops. It takes zero time for people to get into or out of the elevator. 

       

      All persons who are waiting have to be taken to the nth floor. As the party is going to start immediately the resort manager wants everyone to be there in the party in the least time possible. It is your job to control these elevators in such a way that everyone is there in the party in the least time possible and also minimize the cost of controlling these elevators.

       

      Notes:

      1. The objective is to get all the people waiting in floors 0, 1....n - 1 to floor n.

      2. The elevators can move up or down.

      3. It takes zero time for the elevator to stop at any floor and for people to get down or get into the elevator.

      4. If Lift A carries 5 persons from 2nd floor to 6th floor, cost = A[2] ^ A[6] ^ 5

      5. If 1 more person enters Lift A on the 4th floor, the cost will be (A[2] ^ A[4] ^ 5) + (A[4] ^ A[6] ^ 6)

       

      Constraints:

       1 <= n <= 30;

       The sum of people waiting in all floors won't exceed 1000 and there is atleast one person waiting in every floor from 0 to n-1.

       All values of the array A and B are non-negative numbers lesser than or equal to 1000.

       

      Input:

      First Line consists of an integer denoting the number of test cases(atmost 10).

      Every test case will be of the following form.

      First line contains n the number of floors in the building.

      Second line contains n+1 integers: A[0], A[1].....A[n].

      Third line contains n+1 integers: B[0], B[1]......B[n].

      Fourth line contains n integers: The number of persons waiting in each floor from 0 to n - 1.

       

      Output:

      For every test case output one integer on a new line: the minimum cost for operating the elevators and ensuring that all people reach the n'th floor

      .

      Example

      Sample Input:

      2

      2

      0 1 3

      0 1 5

      2 1

      4

      1 3 5 7 9

      2 4 6 8 10

      1 2 3 4

       

      Sample Output:

      1

      16

       

      Explanation:

      In the first test case, 

      1. Lift A carries 1 person from 0th floor to 1st floor. Cost = A[0] ^ A[1] ^ 1 = 0

      2. Lift B carries 1 person from 0th floor to 1st floor. Cost = B[0] ^ B[1] ^ 1 = 0

      3. The person waiting in 1st floor and person from Lift A both move to Lift B. Lift B carries 3 people from 1st floor to 2nd floor. Cost = B[1] ^ B[2] ^ 3 = 1

      4. All persons have reached the party in 2 time units and incurring a cost of 1.

       

       


      Added by:Ranjith Mudalaiyar
      Date:2013-02-25
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ByteCode '13









      SPOJ Problem Set (classical)

      13913. Real Mangoes for Ranjith

      Problem code: MANGOES

      Ranjith is very fond of mangoes.

      One fine sunny day, he goes to market to get some mangoes. In the market place, he finds N boxes (indexed from 1 to N), filled with mangoes kept infront of him.

      Each box indexed i is denoted by bi and contains exactly i mangoes.

      No of mangoes in bi = mi = i.  

      Let ti denotes the type of mangoes in box bi (ti is either "real" or "fake"). He can choose any box bi (i<=N-2), but he doesn't know if the box contains "real" mangoes or "fake" mangoes i.e. type of box bi.

      The type of mangoes in bi depends on the number of mangoes in boxes bi,bi+1, bi+2   i.e. {mi, mi+1, mi+2}. Mangoes in box bi are "real" if for each pair of numbers taken from set {mi, mi+1, mi+2}, Greatest common divisor(GCD) equals 1. Otherwise, "fake". Note that ti is not defined for i = N-1 and i = N and assumed to be "fake". 

      Given N, Ranjith wants to know the total number of "real" mangoes he will get from all boxes. As Ranjith cannot count beyond N, output the result modulo N. 

      Input

      Test File starts with number of test cases - T;

      T lines follows, each containing N, number of boxes.

      Output

      Output T lines Number of "real" mangoes Ranjith gets (modulo N) in each one of the T cases.

      Constraints : 2 < N <= 10^8 T <= 10000

      Example

      Input:

      2

      9

      5

      Output:

      7

      4


      Added by:Gopal Rander
      Date:2013-02-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Bytecode '13









      SPOJ Problem Set (classical)

      13917. EXPLORE TIME

      Problem code: MEETUP

      "ab us ke shahar main Thaharein ki kuuch kar jaayein.
      'Faraz' aao sitaare safar ke dekhate hain"


      Faraz is playing a computer game. The game consists of several levels. You can advance from one level to another. The levels are designed i such a way that it is not possible to come back to a level that you have already visited once. There are multiple starting levels. He can start at any level which has no preceding level and has atleast one other level which he can reach from it.He can end at any level that has no level after it, which means there are multiple end levels. It takes certain amount of time to reach level j from i. However he can explore the level ‘i’ for how much ever time he wants to(explore time should be an integer), but any transition of level (i->j) should take no more than time X.

      Simply put, if he reaches level i at time Ti, he has to reach level j (for a (i->j)transition) within time Ti + X. He won’t spend any time exploring the last level.
      He has to go to Himalayas for meditation in time T, but at the the same time he wants to explore each level he goes to, as much as possible. He also wants to spend equal amount of time exploring each level. Find the maximum amount of time he can spend exploring in each level.


      Input format:

      n - number of nodes
      a b c - parameters for generating the graph.
      n lines will follow denoting the elements of m.
      ith integer denotes the number of levels you can reach from the level i-1 ( 0 based ie. the levels are numbered from 0 to n-1).
      (the number of levels that can be reached from the (n-1)th level will be zero).
      ith level goes to
      j=(a * i * i + b * i + c + k * k)%(n-i-1)+i+1 and
      weight=(a * (i+1) * (j+1)+b * (i+1) * (j+1)+c)%1000000 for k=0 to mi-1
      X T - maximum time you can spend in a level and maximum time he can play the game

      Output format:

      Maximum amount of time he can spend in exploring each level or "It cannot be done" if not possible.


      Constraints:

      n,a,b,c <= 10 ^ 6
      summation of the number of levels that can be reached from each level<= 10 ^ 6
      1 <= time for any move <= 10 ^ 6
      1 <= T <= 10 ^ 6
      1 <= X <= 10 ^ 6

      EXAMPLE:

      Input:

      1
      8 5 10
      0
      39 11

      Output:

      It cannot be done

      Input:

      4
      10 9 10
      5 0 5 0
      15048 8996

      Output:

      8948


      Added by:TouristGuide
      Date:2013-02-27
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13918. String Queries

      Problem code: STRINGQ


       

      Consider a string S, consisting of lowercase alphabets.
      You are given a list of queries, each of which belong to one of the following two types:
      1) Q a b: Returns the number of ways of rearranging the alphabets in the substring [a,b] such that for each substring X in the resulting string A, Reverse(X) is also present in A. Reverse(X) prints the string X in reverse.
      2) U a b: Sorts the substring [a,b] lexicographically.
      Thus, given the string S and a list of queries, print the answer for each query of type 1. Since the answer can be huge, print the result modulo 106109099.
      Finally, output the string S, with the updations made, if any.
      Note: Two ways of rearranging the alphabets are considered different if, for two resulting strings A, B you can find an index i such that A[i] != B[i].

       

      Consider a string S, consisting of lowercase alphabets.

      You are given a list of queries, each of which belong to one of the following two types:

      1) Q a b: Returns the number of ways of rearranging the alphabets in the substring [a,b] such that for each substring X in the resulting string A, Reverse(X) is also present in A. Reverse(X) reverses the string X.

      2) U a b: Sorts the substring [a,b] lexicographically.

       

      Thus, given the string S and a list of queries, print the answer for each query of type 1. Since the answer can be huge, print the result modulo 106109099.

      Finally, output the string S, with the updations made, if any.

      Note: Two ways of rearranging the alphabets are considered different if, for two resulting strings A, B you can find an index i such that A[i] != B[i].

       

       

      Input

       

         First line contains T, the number of test cases.

         For each test case, first line contains S, the input string.

         Next line contains N, the number of queries. Each of the next N lines contains a string of the form "X a b" where X is one of {"Q","U"} and a and b are positive integers such that    1<=a<=b<=|S|.

       

      Output

       

         For each test case, print X+1 lines, where X is the number of queries of type Q.

         For each query of type Q, print one number which is the answer to the query.

         (X+1)th line for each test case, should contain the updated string S.

       

       

      Constraints:

         1 <= T <= 10

         1 <= |S| <= 50000

         1 <= N <= 2000

       

      Example

      Input:
      2
      nittirichy
      3
      Q 2 5
      U 1 4
      Q 1 5
      shabba
      5
      Q 2 3
      Q 2 6
      U 1 4
      Q 2 5
      Q 1 6
      
      Output:
      
      2
      2
      inttirichy
      0
      2
      0
      0
      abhsba

      Added by:TouristGuide
      Date:2013-02-27
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ByteCode '13









      SPOJ Problem Set (classical)

      13925. ZEROES IN RANGE V2

      Problem code: RANGZER2

      You are given two integers a and b. Find the number of zeroes in the digits of all the numbers in the range [a,b] inclusive.

      Input:

      The first line consists of an integer t, the number of test cases. For each test case you will be given two integers a and b (a<=b).


      Output:

      For each test case print the required answer.

       

      Input Constraints:

      1<=t<=1000

      1<=a<=b<=10^9


      Sample Input:

      2

      1 10

      1 100


      Sample Output:

      1

      11


      Added by:cegprakash
      Date:2013-02-27
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      13926. Flipping Slipping of grids

      Problem code: GRIDFLIP

       

      Given two grids of characters , consists of characters from 'a' to 'z' only. we name two grids 'A' and 'B'.
      Now , we need to find the lexicographically largest triplet <i,j,k> 
      Given that : 
      f(A,i,j,k)=B , 0<=j<k<n and 1<=i<=n-2 (where 'n*n' is the size of grid)
      (i.e. function 'f' operated on matrix 'A' with 'i' , 'j' and 'k' parametrs gives matrix 'B'.
      Description of function 'f' : 
      f(M,i,j,k) : function operated on matrix 'M' does following operations in the given order.
      1) Take rows from index '0' to 'i' of the given grid M and flip it, i.e.
      for( each column Ci ) reverse(A[0..i][Ci])
       
      2) Take colums from index '0' to 'j' of the grid and flip it, i.e. 
      for( each row Ri ) reverse(A[Ri][0..j])
      3) Take colums from index 'k' to 'n-1' of the grid and flip it, i.e.
      for( each row Rj ) reverse(A[Rj][k...n-1]
      4) Remove columns indexed '0' to 'j' and concatenate on the right of the grid in the same order, making new grid.

      Given two grids of characters , consists of characters from 'a' to 'z' only. we name two grids 'A' and 'B'.

      Now , we need to find the lexicographically largest triplet <i,j,k>   ( Assuming that one such solution does always exists )

      Given that : 

      f(A,i,j,k)=B , 0<=j<k<n and 1<=i<=n-2 (where 'n*n' is the size of grids)

      (i.e. function 'f' operated on matrix 'A' with 'i' , 'j' and 'k' parametrs gives matrix 'B'.

       

      Description of function 'f' : 

      f(M,i,j,k) : function operated on matrix 'M' does following operations in the given order.

       

      1) Take rows from index '0' to 'i' of the given grid M and flip it, i.e.

      for( each column Ci ) reverse(A[0..i][Ci])

       

      2) Take colums from index '0' to 'j' of the grid and flip it, i.e. 

      for( each row Ri ) reverse(A[Ri][0..j])

       

      3) Take colums from index 'k' to 'n-1' of the grid and flip it, i.e.

      for( each row Rj ) reverse(A[Rj][k...n-1]

       

      4) Remove columns indexed '0' to 'j' and concatenate on the right of the grid in the same order, making new grid.

       

      Input

      First line contains one integer 'n' (n*n is size of grid)

      Following n lines (i.e. line numbers 2 to n+1 ) containes strings each of size 'n' for grid 'A'.

      Following n lines (i.e. line numbers n+2 to 2n+1) containes strings each of size 'n' for grid 'B'.

      Constraints:

      1) 5<=n<=1000 

      2) String contains only lower case alphabets

       

      Output

      Three integers (space separated) in one line representing i , j and k respectively (lexicographically largest solution).

      Example

      Input:
      5
      ooscz
      hkaea
      nnzth
      khdlf
      rejtf
      fldhk
      htznn
      aeakh
      zcsoo
      ftjer
      
      Output:
      3 3 4
      

      Added by:parth dandiwala
      Date:2013-02-27
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:BYTECODE 13









      SPOJ Problem Set (classical)

      13940. Fibonacci vs Polynomial (HARD)

      Problem code: PIBO2

      Define a sequence Pib(n) as following

      • Pib(0) = 1
      • Pib(1) = 1
      • otherwise, Pib(n) = Pib(n-1) + Pib(n-2) + P(n)

      Here P is a polynomial.

      Given n and P, find Pib(n) modulo 1,111,111,111.

      Maybe you should solve PIBO before this task, it has lower constraints.

      Input

       First line of input contains two integer n and d (0 ≤ n ≤ 109, 0 ≤ d ≤ 10000), d is the degree of polynomial.

      The second line contains d+1 integers c0,c1 … cd, represent the coefficient of the polynomial (Thus P(x) can be written as Σcixi). 0 ≤ ci < 1,111,111,111 and cd ≠ 0 unless d = 0.

       

      Output

      A single integer represents the answer.

      Example

      Input:
      10 0
      0
      
      Output:
      89
      
      Input:
      10 0
      1
      
      Output:
      177
      
      Input:
      100 1
      1 1
      
      Output:
      343742333
      

      Added by:Michael Kharitonov
      Date:2013-02-28
      Time limit:0.100s-10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13941. The AMSCO cipher

      Problem code: AMSCO1

      Due to A.M.SCOtt in the 19th century, it's an incomplete columnar transposition cipher
      with alternating single letters and digraphs. The first entry must be a digraph.
      In both even and odd periods the first column and the first row always alternate:

      4 1 3 2 5
      IN C OM P LE
      T EC O LU M
      NA R WI T HA
      L TE R NA T
      IN G SI N GL
      E LE T TE R
      SA N DD I GR
      A PH S    

       

       

       

       

       

       

       

       

       

      Input

      N lines (N<1000)
      Each line of the input contains the numeric key (permutation order of the columns)
      and a plaintext. Plaintext letters are in [A-Z] only with no punctuation.
      The keylength max is 9 and the length of the plaintext is limited to 250.
      The last line ends with EOF.

      Output

      Output consist of exactly N lines of ciphertexts with letters in [A-Z] with no spaces.

      Example

      Input:
      
      41325 INCOMPLETECOLUMNARWITHALTERNATINGSINGLELETTERSANDDIGRAPHS Output:

       CECRTEGLENPHPLUTNANTEIOMOWIRSITDDSINTNALINESAALEMHATGLRGR

      Added by:legrand
      Date:2013-02-28
      Time limit:0.5s-1s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:ADA AWK BASH C C++ 4.3.2 C++ 4.0.0-8 C99 strict FORT GO HASK JAVA CAML PAS fpc PAS gpc PERL PIKE PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n RUBY
      Resource:classical ciphers









      SPOJ Problem Set (classical)

      13945. GHALIBS CHALLENGE

      Problem code: GHALIBC

      "har ek baat pe kehte ho tum ke 'too kya hai?'
      tumheen kaho ke yeh andaaz-e-guftgoo kya hai?"

      Ghalib was a great poet and was very higly regarded by the emperor. Some of the nobles did not like this, so concocted a plan to reduce his influence on the emperor. They gave him a challenge, he could be given n bags of marbles. The first bag has 1 marble, second bag has 2 marbles and so on. Each of the marble has a unique radius between 1 and i, where i is the number of the bag. Ghalib has to tell the number of ways arranging these marbles. (The marbles in each of the bag have to be arranged separately and the number of ways summed up for all the bags).

      Ghalib complained to the king that this task is too difficult. So the king tried to help him a bit. (n+1) will only be divisible by a single prime - p (i.e. (n+1)=p^a) and he has to only find ways of rearranging those bags of marbles whose size is equal to r mod(p-1) and (p+1)/2<=r<=p-1. Also he doesnt need to count any arrangement of marbles containing a subsequence of 3 marbles with increasing length.
      Ghalib still finds this task too difficult and is asking for your help. Since the answer can be very big, output the remainder when the answer is divided by p*p.

      Input

      1<=t<=10 :-  the number of test cases

      followed by t llines of

      r p a :- as given in the question

      (p+1)/2<=r<=p-1

      5<=p<=1000

      1<=a<=10^8

      Output

      A single number representing the required answer

      Example

      Input:
      2
      5 7 2
      5 7 1 Output:
      42
      42

      Added by:TouristGuide
      Date:2013-02-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Bytecode 2013









      SPOJ Problem Set (classical)

      13948. Disjoint Subtrees

      Problem code: KAYKAY


      Given a tree -  A connected and acyclic graph with n vertices.
      Each node in the tree has a value associated with it. 
      Given a set of vertices S, value(S) = sum of values of all vertices in set S.
      Your task is to select two components A and B such that:
      1. A and B are disjoint (they have no vertex in common)
      2. A has k1 vertices; i.e, | A | = k1
      3. B has k2 vertices; i.e, | B | = k2
      4. value(A) - value(B) is maximized.
      If it is not possible to select two such components, print -1.
      Constraints:
      n <= 500
      k1, k2 <= n
      Input:
      First line contains t, total test cases.
      Each test case is as follows:
      First line contains three integers: n, k1 and k2.
      Next line contains n integers, the values of the n nodes; -100000 <= value <= 100000
      Next n - 1 lines contain 2 integers a and b, indicating that there is an edge between a and b. 0 <= a < b < n
      Output:
      For each test case, print one line containing an integer = | value(A) - value(B) |.
      Sample Input:
      2
      7 3 3
      0 1 -1 2 3 -2 -3
      1 2
      1 3
      2 4
      2 5
      3 6
      3 7
      3 2 2
      1 2 3
      0 1
      0 2
      Sample Output:
      12
      -

      The CSE Department of NIT Trichy is not particularly reknowned for its eye-candy. Noticing this, Paarth decides to distribute some candies throughout the department. The department consists of n rooms. There are corridors connecting certain pairs of rooms. Being very frugal, the corridors are designed in such a way that every pair of rooms are connected by exactly one path. Now Alpa and Syed are let loose in the department and they want to collect as many candies as possible. Alpa has hired you to help him maximize the difference between the number of candies obtained by him and Syed based on the constraint that he shall never enter any room that is visited by Syed.

       

      More formally, you are given a tree -  A connected and acyclic graph with n vertices.

      Each vertex in the tree has a value associated with it (the number of candies). Note that the number of candies may be negative as well (bullies waiting to snatch your candies away) 

      Given a set of vertices S, value(S) = sum of values of all vertices in set S.

      Your task is to select two sets of vertices A and B such that:

      1. A and B are disjoint (they have no vertex in common)

      2. Every vertex in A is connected to every other vertex in A through some path; 

      3. Every vertex in B is connected to every other vertex in B through some path; 

      4. A has k1 vertices; i.e, | A | = k1

      5. B has k2 vertices; i.e, | B | = k2

      6. value(A) - value(B) is maximized.

       

      If it is not possible to select two such components, print -1.


      Constraints:

      2 <= n <= 200

      0 < k1, k2 <= n

      Values of all vertices are between -10 ^ 5 and 10 ^ 5


      Input:

      First line contains t, total test cases.

       Each test case is as follows:

      First line contains three integers: n, k1 and k2.

      Next line contains n integers, the values of the n vertices.

      Next n - 1 lines contain 2 integers a and b,

      indicating that there is an edge between vertices a and b; 0 <= a < b < n


      Output:

      For each test case, print one line containing an integer = value(A) - value(B) .


      Sample Input:

      2

      7 3 3

      0 1 -1 2 3 -2 -3

      0 1

      0 2

      1 3

      1 4

      2 5

      2 6


      3 2 2

      1 2 3

      0 1

      0 2


      Sample Output:

      12

      -1


      Explanation:

      In the first case, A = { 1, 3, 4}; B = {2, 5, 6}.


      Added by:Aditya Muraletharan
      Date:2013-03-01
      Time limit:0.5s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Bytecode '13









      SPOJ Problem Set (classical)

      13953. Divide Polygon (HARD)

      Problem code: DTPOLY2


      This is hard version of DTPOLY

      Determine the number of ways to cut a convex polygon with N vertices if the only cuts allowed are from vertex to vertex, each cut divides exactly one polygon into exactly two polygons, and you must end up with exactly K polygons. Consider each vertex distinct. For example, there are three ways to cut a square - the two diagonals and not cutting at all - but only two ways to cut it to form 2 polygons, and only one way to cut it to form 1 polygon. The order of cuts does not matter. Since the number of ways is very large, you should return the number taken modulo M.

      • Input contains several test cases, i-th line consists of 3 integers: Ni (4 ≤ Ni, ΣNi ≤ 108), Ki (1 ≤ K≤ N- 2) and Mi (1 < M < 260), all pairs (Ni, Ki) are different.
      • On the i-th line print the number of different ways to cut the polygon with Ni vertices into Ki pieces modulo Mi.

      Example

      Input

      4 2
      6 3
      10000000 2
      10000000 9999998
      4 2 100
      6 3 100
      10000000 2 1000000007
      10000000 5000000 1000000014000000049

      Output

      2
      21
      984650007
      780127215155143528

      Added by:Michael Kharitonov
      Date:2013-03-01
      Time limit:6s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      13977. Thousands ByteMan March

      Problem code: TMB

      Leo invited all his friends to a giant meeting for peace in byteland. All people came in bus which were all full.
      Last year, they were only 4 people : A, B, C, D. As Leo likes structured things, he thought to form groups.
      All the ways to form homogeneous teams were :

      {{A,B,C,D}} : one team of 4 (one way),
      {{A}, {B}, {C}, {D}} : four 'teams' of 1 (one way more),
      {{A,B}, {C,D}} or {{A,C}, {B,D}} or {{A,D}, {B,C}} : two teams of 2 (3 ways more).
      

      for a total of 5 ways. But this year many people are awaited.

      Input

      The input begins with the number T of test cases in a single line.
      In each of the next T lines there are two integers : N, K.
      N is the quantity of bus that came to the meeting.
      K is the common capacity of each bus.

      Output

      For each test case, your task is to calculate the number of ways people can form homogeneous teams.
      The answer can be a big number and could not fit in a 64bit container.

      Example

      Input:
      3
      2 2
      1 6
      2 3
      
      Output:
      5
      27
      27
      

      Explanations

      With lower letters, here are 27 ways for 2×3 people.

      {{a,c,e},{b,d,f}},{{a,c,d},{b,e,f}},{{a,b},{c,e},{d,f}},{{a,f},{b,e},{c,d}},
      {{a,b,f},{c,d,e}},{{a,c},{b,f},{d,e}},{{a,e},{b,f},{c,d}},{{a,b},{c,d},{e,f}},
      {{a,e},{b,d},{c,f}},{{a,e,f},{b,c,d}},{{a,b,e},{c,d,f}},{{a,d,e},{b,c,f}},
      {{a,d},{b,e},{c,f}},{{a,d},{b,c},{e,f}},{{a,d},{b,f},{c,e}},
      {{a,c,f},{b,d,e}},{{a,b,c},{d,e,f}},{{a},{b},{c},{d},{e},{f}},
      {{a,b,c,d,e,f}},{{a,c},{b,d},{e,f}},{{a,c},{b,e},{d,f}},{{a,b},{c,f},{d,e}},
      {{a,f},{b,d},{c,e}},{{a,f},{b,c},{d,e}},{{a,e},{b,c},{d,f}},
      {{a,d,f},{b,c,e}},{{a,b,d},{c,e,f}}

      Constraints

      0 < T ≤ 100
      0 < K ≤ 100
      0 < N ≤ 100
      

      Uniform-random input in the range. Basic 1/6kB Python3 code can get AC under 8s, around 3s using PIKE (quite my first PIKE code), and I got TLE with Python2.7 with that basic code.


      Added by:Francky
      Date:2013-03-03
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      13978. Billion ByteMan March

      Problem code: BBM

      Warning:

      Source code size limit is 2048B (half is enougth) and time limit could not allow all language to get AC ; I got AC in 1.5s with language C. The main difficulty of the problem is to manage efficiently the given precomputed values and the memory available, in the given time. Have fun ;-)

      The March

      Leo invited all his friends to a giant meeting for peace in byteland. All people came in bus which were all full.
      Last year, they were thousands of people. As Leo like structured things, he thought to form groups.
      Two years ago, all the ways to form homogeneous team with the 4 people (A,B,C,D) were :

      {{A,B,C,D}} : one team of 4 (one way),
      {{A}, {B}, {C}, {D}} : four 'teams' of 1 (one way more),
      {{A,B}, {C,D}} or {{A,C}, {B,D}} or {{A,D}, {B,C}} : two teams of 2 (3 ways more).
      

      for a total of 5 ways. But this year many more people are awaited.
      As the answer should not fit in a 64-bit container, you should give your answer modulo M7=1000000007.

      Input

      The input starts with 2^12 useful precomputed values: factorial(i) MOD M7 for i in [0 ; 2^30[ with a step of 2^18, each one on one line.
      The input continues with the number T of test cases in a single line.
      In each of the next T lines there are two integers : N, K.
      N is the quantity of bus that came to the meeting.
      K is the common capacity of each bus.

      Output

      For each test case, your task is to calculate the number of ways people can form homogeneous teams.

      Example

      Input:
      1            <--- 0! mod M7
      639926614    <--- (2^18)! mod M7
      [...]        ( 4093 lines more)
      0            <--- (2^30 - 2^18)! mod M7
      3
      2 2
      1 6
      2 3
      
      Output:
      5
      27
      27
      

      Constraints

      0 < T ≤ 300
      0 < K ≤ 30000
      0 < N ≤ 30000
      

      Uniform-random input in the range.


      Added by:Francky
      Date:2013-03-03
      Time limit:5s
      Source limit:2048B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      13980. Sudoku goblin

      Problem code: SUDOGOB


      A sudoku goblin has read your book with sudoku problems. He has erased or added some numbers from settings. Your task is to write a program that can detect modified settings.

      For every sudoku setting you have to count number of possible solutions and in the case that it is equal to 1 print

      the unique solution.

      Input

      There is a number T of the test cases on the first line folowed by T sudoku tables separated by one empty line. One sudoku table consists of 9 lines of 9 numbers 0-9 separated by one space. Zero in the table marks the empty field.

      Output

      For every test case, one line with number of possible solutions optionally followed by solved sudoku in the same format as on the input.

      Example

       

      Input:
      3
      3 0 6 0 0 2 5 0 0
      0 0 0 0 3 8 0 0 0
      7 0 8 0 1 6 0 9 0
      0 0 7 0 0 3 8 6 0
      8 2 0 0 7 0 0 4 5
      0 6 3 1 0 0 9 0 0
      0 7 0 3 5 0 6 0 2
      0 0 0 8 2 0 0 0 0
      0 0 2 9 0 0 7 0 4

      3 0 6 0 0 2 5 0 3
      0 0 0 0 3 8 0 0 0
      7 0 8 0 1 6 0 9 0
      0 0 7 0 0 3 8 6 0
      8 2 0 0 7 0 0 4 5
      0 6 3 1 0 0 9 0 0
      0 7 0 3 5 0 6 0 2
      0 0 0 8 2 0 0 0 0
      0 0 2 9 0 0 7 0 4

      3 0 6 0 0 2 0 0 0
      0 0 0 0 3 8 0 0 0
      7 0 8 0 1 6 0 9 0
      0 0 7 0 0 3 8 6 0
      8 2 0 0 7 0 0 4 5
      0 6 3 1 0 0 9 0 0
      0 7 0 3 5 0 6 0 2
      0 0 0 8 2 0 0 0 0
      0 0 2 9 0 0 7 0 4

       Output: 1
      3 1 6 4 9 2 5 7 8
      2 9 5 7 3 8 4 1 6
      7 4 8 5 1 6 2 9 3
      9 5 7 2 4 3 8 6 1
      8 2 1 6 7 9 3 4 5
      4 6 3 1 8 5 9 2 7
      1 7 9 3 5 4 6 8 2
      6 3 4 8 2 7 1 5 9
      5 8 2 9 6 1 7 3 4
      0
      2

      Added by:Jan Brezina
      Date:2013-03-04
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF WSPC









      SPOJ Problem Set (classical)

      13989. Helping Susy

      Problem code: SUSY


      Susy is a beautiful and smart student. She is an expert  solving puzzle games, specially mazes, and such talent has given her several prizes from various competitions, where her speed and skills are tested.

      Right now, she is participating in an special puzzle contests, and her jealous rival, Angelica, is participating too.

      At this moment, they are in a tie, and in order to break this tie the judges have prepared a special round with a special game. The rules of this game are the following:

      -The game consists of a table with walls, like a maze. Also, there are some special objects, the Magic Stones. To win the game, the player must take all the stones present in the table.

      -There are four valid movements: Up, Down, Left and Right. Nevertheless, once the player choose a movement from his current position, he cannot stop moving in that direction until he crash with a wall in the maze. Obviously, the player cannot leave the table, so the limits of the table are considered walls too.

      -As there can be many solutions, the judges want the optimal one, which mean the least number of moves.

      This is not problem for Susy, but Angelica is having a really bad time with this game. Jealously, Angelica secretly took Susy's solution and cut it in many pieces (She is not very intelligent. She could copy the solution instead but her anger blinded her).

      Time is running out, and Susy doesn't have the time required to solve the puzzle again. Fortunately, the participants can ask a friend to help with just one puzzle, and she knows something the judges don't, your programming skills.

      Now, she is calling you! Write a program to solve the maze with the least moves possible! Help Susy!

       

      Input

       

      The input begins with two integer numbers, R and C, the number of rows and columns of the table respectively.

      Next, there will be R lines with C characters each, representing the maze. Each maze will contain only following characters:
      "." - free space,
      "#" - wall,
      "S" - initial position of the player,
      "*" - magic stone.

       

      Output

       

      The output consists of 2 lines. The first must contain one only number S. S is the optimal solution of the game.

      The next line consists of S strings separated with a "-". These strings are "Up", "Down", "Left" and "Right". The full string represents the movements done in the optimal solution.

      If there is more than one optimal solution, you must print the lexicographically smallest one.

       

      Example

      Input:
      5 6
      *S....
      ....#.
      .##...
      **....
      .#.*#.
      
      
      Output:
      7
      Down-Right-Down-Left-Up-Left-Up
      Constraints:
      2<=(r,c)<=20
      There will be no more than 13 magic stones in the maze.
      NOTE:
      There will always be a solution for the given maze.

      Added by:Samuel Nacache
      Date:2013-03-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem (based on a real game)









      SPOJ Problem Set (classical)

      13990. Web islands

      Problem code: WEBISL


      For a given set of web pages, we want to find largest subsets such that from every page in a subset you can follow links to any other page in the same subset.

      Input

      On the first line, there are two numbers, number of the pages N, and total number of links M. Pages are numbered from 0 up to N-1. On lines 2 up to M+1, there are two numbers per line. The first is the source page and the second is the target page of a link.

      Output

      On N lines there is a component ID for every single page. The componet ID is the smallest page index on the component.

      Example

      Input:
      3 3
      0 1
      1 0
      1 2

      Output: 0
      0
      2

      Added by:Jan Brezina
      Date:2013-03-04
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14031. Spring Primality

      Problem code: VPL1_AA


      Dickie was playing with his friend some day in the spring season, he bought some cards, each card contains a number, that can be a prime or not. The game that Dickie plays consists to count what is the longest segment of contiguous cards that contains a prime, by instance, if the cards are: 2 5 8 14 11 15, the longest contiguous segment will be of length 2 as the cards 2,5 are primes, while the 11 is automatically discarded as it is isolated.

      Nevertheless, Dickie’s friends are evil and they challenged him to do another task, that goes as follows, for every card that is not a prime, you substract every of its prime factors to the prime count of the factor and for every card that is a prime, you will add a unit to its prime count, i.e.: 2 5 8 14 11 15, primes=2,5,11, 8=2*2*2, 14=2*7, 15=3*5, so, prime count [2] = 1- 3-1, prime count [5] = 1-1 prime count [11] = 1. There is no consideration for the other numbers.

      After doing this, Dickie will count another time the longest contiguous segment, however, if the prime count is less or equal than zero, you can’t count that prime card. Help Dickie to find the longest contiguous segment of cards according to his rules, and the longest contiguous segment of cards according to his friends rules.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow

      the descriptions of T test cases.

      The first line of each case will contain a number N , then, in the next line, N numbers will follow.

       

      Output

      For each test case you should print the string "Scenario #i: " where i represents the test case you are analyzing (starting from 1), followed by the longest segment of contiguous prime cards, then, a single space, a "greater than-sign" and another single space will follows and after that, the segment of contiguous cards according to the rules proposed by Dickie’s friends.

       

       

      INPUT

      OUTPUT

      3

      7

      7 9 11 2 5 7 6

      3

      2 3 4

      5

      8 16 32 64 7

      Scenario #1: 4 > 2

      Scenario #2: 2 > 1

      Scenario #3: 1 > 1

       

      Constraints - Subtask 1 (20%)

      1 ≤ T ≤ 100

      1 ≤ N ≤ 100

      2 ≤ Ni ≤ 1000

      Constraints - Subtask 2 (30%)

      1 ≤ T ≤ 10

      1 ≤ N ≤ 1000

      2 ≤ Ni ≤ 100000

      Constraints - Subtask 3 (50%)

      1≤T ≤5

      1 ≤ N ≤ 100000

      2 ≤ Ni ≤ 10000000 

       


      Added by:Venezuelan Programming League
      Date:2013-03-08
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14032. Summer Game

      Problem code: VPL1_AB

      Beto, Dickie, Luis, Maxx, Charlie and Ricky like to play some wicked games in the summer. These games can easily be found in any social network. They like to play by drinking some strange liquid they call ”Aquameister” that can make you dizzy if you drink too much! Beto is tired of losing everytime they play, but Charlie is the most capable to resist these games. That’s why Beto asked for your help! He wants to make Charlie feel dizzy before he does! The game consists on winning (clearly), and is given by a large row. He starts from position 1. For each row you must drink one small cup of Aquameister. If you repeat the same movement of dice he threw in his last turn, he drink again, for simplicity, we define the "same movement" with the same dies that Beto threw the last turn, by instance, if Beto threw (2,1,2), then Beto can throw (1,2,2), however, Beto may not throw the same (2,1,2), and so on for each roll. This goes on until Beto reach the position N. Being the last position, if  Beto pass out, he lose the game and will drink twice and start again. However, for the sake of Beto, if he goes out he drinks twice and stops drinking.

      Beto wants to know how many different ways he can end the game perfectly (that is arriving to the N position in the game) starting from the position 1. As this number can be very big, we ask you to output the answer modulo 1,000,000,007

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow the descriptions of T test cases.

      Each case contains two integers N and D, being the size of the row and the number of dies you will throw per round (The dice is a six-sided dice).

      Output

      For each input case you must print the string "Scenario #i:" where i is the case you are analyzing (starting from 1) then, the answer to the question described above.

       

       

      INPUT

      OUTPUT

      3

      3 1

      4 1

      6 1

      Scenario #1: 1

      Scenario #2: 3

      Scenario #3: 7

      Constraints - Subtask 1 (10%)

      • 1 ≤ T ≤ 50

      • 1≤N ≤5

      • 1≤D≤2

      Constraints - Subtask 2 (30%)

      • 1 ≤ T ≤ 100

      • 1 ≤ N ≤ 100

      • D=1

      Constraints - Subtask 3 (60%)

      • 1 ≤ T ≤ 50

      • 1 ≤ N ≤ 100

      • 1≤D≤3 

       


      Added by:Venezuelan Programming League
      Date:2013-03-08
      Time limit:4s-8s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14033. Late Summer Searching

      Problem code: VPL1_AC


      Summer is late! Summer is late! For a very important date! The VPL programming contest is about to start and Summer is nowhere to be found. Without Summer, you cannot have a contest based on seasons, so you have to find her quickly!

      A system of antennas is placed on the top of the tallest buildings. You can use them to try to detect Summer's position, so you can finally go and get her. However, the antennas are very sensitive to noise, so unless every antenna is visible from every other antenna, the system will not work. Every antenna has an interference radius R, that will block the visibility between two other antennas if their signal passes through it.

      Even if the system works, using it is very energy-consuming and quite expensive. Given the positions of the antennas, the cost of using the system is equal to the minimal possible area that encloses every antenna (along with their lines of sight with every other antenna). For simplicity, you can suppose that the physical radius of each antenna is negligible.

      You are located in the VPL headquarters building (which has its own antenna), where every other building with an antenna has a position relative to yours. Knowing these positions, and the interference radius for the antennas, your job is to decide whether the system can work or not. And if it can, what will be the cost (in terms of the minimal area covered).

       

      INPUT DETAILS:

      The first line of the input will contain a single integer T, which is the number of test cases that follow. Each test case will begin with a line containing two integers N (the number of antennas) and R (Radius of interference of the antennas). N-1 lines follow, each one containing two integers Xi and Yi, being the relative position of the i-th building with respect to VPL headquarters (which is assumed to be placed at position (0, 0)).

      OUTPUT DETAILS:

      The output of your program should consist of T lines, one for each test case. For each of these test cases you should output a single number, representing the minimum area covered by the system, (Rounded to two decimal places). If the system cannot be used, you should output only the text "NO CONTEST" (quotes for clarity).

       

      INPUT

      OUTPUT

      2

      4 1

      2 0

      2 2

      0 2

      5 1

      2 0

      2 2

      0 2

      1 1

      4.00

      NO CONTEST

       GENERAL CONSTRAINTS:

      1 < T < 100

      1 < R < 10

      -500 < Xi, Yi < 500

      CONSTRAINTS - SUBTASK 1 (20%):

      N = 3

      CONSTRAINTS - SUBTASK 2 (80%):

      3 < N < 100


      Added by:Venezuelan Programming League
      Date:2013-03-08
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14034. Autumn Leaves

      Problem code: VPL1_AD

      Autumn is a particular season, because it’s the season when all leaves fall down. Sometimes, the leaves fall in places that are not convenient, such as the ants garden. Andy the ant was playing one day at his garden when Autumn season started. All leaves started to fall down on Andy’s garden, Andy ran to his house and when the leaves stopped falling he went out. He realized that there were not only leaves but sticks on his garden. It is proved that an ant can carry at most ten times his weight, but a stick is much more than that, so Andy decided to clean the leaves and leave the sticks. This, of course, is a problem, because Andy can only jump over K sticks. Andy is very lazy, so he wants the better way to remove all leaves of his garden, but he doesn’t know how to figure out that, so he ask for your help in order to know that path. Andy always start at point (0,0) (his house), and he doesn’t need to come back to his house, so the last leave is the last point on his path, but he has visit at least one time each leave. For simplicity, leaves will be indexed from 1 to N , and Andy’s house will be assumed as point 0. Please note that Andy, like all ants, can’t break his walk line, so he can’t go around any stick, he can only jump over them.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow the descriptions of T test cases.

      Each test case starts with 3 integers, N , M and K, these are the number of leaves, the number of sticks and the total number of sticks that andy can jump on his path. N lines will follow, each one with 2 integers, Xi and Yi , separated by spaces, indicating the position of the leaf i on Andy’s garden. Then M lines will follow, each one with 4 integers, X1i , Y1i , X2i and Y2i , separated by spaces, indicating the position of the start and ending point of stick i on Andy’s garden.

       

      Output

      For each input case you must print the string "Scenario #i: " where i represents the test case you are analyzing (starting from 1), followed by the minimum distance that Andy have to walk in order to clean the leaves of his garden. Then one line with Andy’s path, if there are more than one path that has the minimal distance, print the less one lexicographically ordered. If there exist no path then you should print "-1".

       

       

      INPUT

      OUTPUT

      2

      6 3 1

      1 6

      2 2

      5 1

      5 5

      5 9

      10 2

      2 5 4 3

      3 7 8 7

      6 0 8 3

      4 3 2

      -2 -2

      2 2

      5 -1

      6 6

      0 3 1 0

      -2 -5 5 2

      0 5 7 0

      Scenario #1: 26.044

      0 2 3 6 4 1 5

      Scenario #2: -1

       

      Constraints - Subtask 1 (10%)

       1 ≤ T , N, K ≤ 4

       M =0

       -1000 ≤ Xi , Yi ≤ 1000

       -1000 ≤ X1i , Y1i , X2i , Y2i ≤ 1000

      Constraints - Subtask 2 (15%)

       1 ≤ T , N , K ≤ 10

       M =0

       -1000 ≤ Xi , Yi ≤ 1000

       -1000 ≤ X1i , Y1i , X2i , Y2i ≤ 1000

      Constraints - Subtask 3 (25%)

       1 ≤ T , N, M, K ≤ 4

       -1000 ≤ Xi , Yi ≤ 1000

       -1000 ≤ X1i , Y1i , X2i , Y2i ≤ 1000

      Constraints - Subtask 4 (50%)

       1 ≤ T , N , M , K ≤ 10

       -1000 ≤ Xi , Yi ≤ 1000

       -1000 ≤ X1i , Y1i , X2i , Y2i ≤ 1000 

       


      Added by:Venezuelan Programming League
      Date:2013-03-08
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14035. Winter Crush

      Problem code: VPL1_AE


      Winter is a sad season, specially if you have nobody to share your time with. Valentine’s day is coming and Dickie is crushed for Elizabeth, but she has already friendzoned him with the classic “You’re my best friend” and other silly phrases used by girls in order to keep the “friend” neutralized but at the same time, keep him close.

      Nevertheless, Dickie ain’t gonna to take any more stools. He’s thinking about an ultimate move to gain Elizabeth heart! He has called this ”No more stools operation!”, and will take place on Valentine’s day. He hasn’t clearly decided what to do, because that heavily depends on Elizabeth’s position on Valentine’s day. Even so, Dickie has been smart enough to figured out a way to know Elizabeth’s position in terms of probability based on the time elapsed from the beginning of the day.

      As Elizabeth’s “best friend”, Dickie knows her preferences and tastes. He knows that if she’s at a given position x, she will move to any adjacent position y with a probability pxy depending on the joy attained going there and the amount of snow on the path. The joy jxy is being measured in joysons and the snow sxy by centimeters, and the choice will be taken by the relation jxy /sxy . Some properties shall hold:

      • The set of all positions is to be named V

      For any given x ∈ V , the set of all positions y ∈ V adjacent to x is to be named Ex. A position y is to be called adyacent if there is a path from x to y. Paths are bidirectional, so jxy/sxy = jyx/syx.

      • ∀x ∈ V ∧ ∀y ∈ Ex :

      Dickie has some places in mind where he can find Elizabeth, but he’s aware that she could depart that morning from either her house or any of hers friends’ houses, so he wants to know which is the position with the highest probability to find Elizabeth given an elapsed time and the position she’s departing. Dickie wants to evaluate several possible scenarios, so a query will be formed by a time Ti and several possible initial positions Pi.


      Input

      The first line contains an integer C, which specifies the number of test cases. Then, will follow

      the descriptions of C test cases.


      Each case will start with two integers, N and M , denoting the number of positions and the number of paths respectively. Next M will describe each of the paths between positions with four integers x, y, jxy , sxy , with the significance given above in the statement. All position indexes are 0-based. The line M +1 will contain an integer Q denoting the number of Dickie’s queries. Each query will start with two integers, Ti and qi denoting the elapsed time and the number Elizabeth’s possible starting positions. Next qi lines will contain an integer will represent Elizabeth’s starting positions Pi.

      Output

      For each test case you should print the string "Scenario #i:" where i represents the test case you are analyzing (starting from 1), followed by a blank line. For each query Qi in the input, you must output a line with qi integers representing the position with the highest probability to find Elizabeth given the elapsed time Ti and the starting position Pi of her. If there are several positions with the highest probability, print the smallest one. If there are no positions with higher probability than 0, print -1.

       

       

      INPUT

      OUTPUT

      2

      3 3

      0 1 10 2

      0 2 1 8

      1 2 100 1

      2

      1 1 0

      2 1 0

      4 5

      0 1 10 2

      1 3 2 3

      0 2 4 8

      2 1 1 10

      2 3 1 1

      2

      2 1 2

      10 2 0 3

      Scenario #1:

      1

      2


      Scenario #2:

      1

      0 0

      Global constraints

      • 0 < jxy , sxy ≤ 100

      • 0 ≤ M ≤ (N*(N-1))/2


      Constraints - Subtask 1 (30%)

      • 1 ≤ C ≤ 50

      • 1 ≤ N ≤ 20

      • 0 ≤ |Ex | ≤ 3, ∀ x ∈ V

      • 1 ≤ Ti ≤ 20

      • 1 ≤ Q ≤ 10

      • qi = 1

      • 0 ≤ Pi ≤ N

      Constraints - Subtask 2 (70%)

      • 1 ≤ C ≤ 20

      • 1 ≤ N ≤ 100

      • 1 ≤ Q ≤ 10

      • 2 ≤ Ti ≤ 2000

      • 1 ≤ qi ≤ 100

      • 0 ≤ Pi ≤ N 

       


      Added by:Venezuelan Programming League
      Date:2013-03-08
      Time limit:30s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14049. Annual Day

      Problem code: VOLNTEER

      Problem Statement

      The kids at DACT elementary school are very excited since they have their annual day coming up. On this occasion, the students get a chance to display all their projects and art work, as well as perform on stage for all the parents and other guests who will be coming. Since organizing an event so big requires a lot of effort, the poor teachers alone cannot handle it all. So, they decide to ask some of the students to volunteer to lend a hand.

      You are the class teacher of one such kindergarten class with N students, and you need to select exactly k of your students for the volunteer group. Luckily for you, all the kids are very enthusiastic and excited and everyone wants to help out ! But you also know that many of these students are very naughty and may start playing with each other halfway through instead of doing work. So you want to select this group of students in a smart manner to avoid such a scenario.

      Since you have been their class teacher for nearly a year, you know beforehand how naughty each kid is, and have assigned "goodness" scores to each of the students accordingly. The higher the score for a student, the less naughty he/she is. You can also use this individual goodness score to calculate the score for a group of students as follows :

      Goodness( a1, a2.... an ) = ( |a1|+|a2|....|an| ) * (-1)r

      Where a1, a2... an are the goodness scores of the n students in that group, and r is the number of naughty students in that group. ( Note : A naughty student is one with a negative goodness score )

      Also |x| refers to the absolute value of x. ( |x|=x if x>0. Else |x|=-x).

      Given the goodness scores of all the students in your class, it is up to you to select exactly k students such that their group goodness score is maximum.

       

      Input

      The first line contains 2 space separated integers N and k. ( 1 <= k<=N <= 105 ). Here N is the total number of students in your class, and k is the number of students to be selected.

      This is followed by N space separated integers a1, a2... aN, where ai is the goodness score of the ith student. ( |ai| <= 109 )

      Output

      On a single line output the maximum possible goodness value of any group of exactly k students that you may select.

       

      Example

      Input #1:
      10 1
      1 2 3 4 5 6 7 8 -9 9
       
      Output #1:
      9


      Input #2:

      10 3
      1 2 3 4 5 6 7 -8 -9 9

      Output #2:
      26


      Input #3:
      3 3
      12 78 2

      Output #3:
      92

      Explanation :

      Input #1 : Since you need to select exactly one student, you will select the one with the maximum individual goodness score, so the answer is 9.


      Input #2 : Here, the maximum score is obtained by selecting the students with scores of { -8, -9, 9 }.

      The corresponding final value is : (|-8|+|-9|+|9|)*(-1)2 = 26*1 = 26


      Input #3 : Here you have no choice but to select all the students. So the answer is 92.


      Added by:Gowri Sundaram
      Date:2013-03-09
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14055. The Wind Waker

      Problem code: WWAKER


      The world is in danger once again, and Link is the hero who will save us! In order to save the world, Link must travel overseas and collect some legendary items.

      The sea can be described as an infinite 2D plane with a Cartesian coordinate system, in which the point (0,0) denotes the center of the sea. Also, the cardinal directions are defined as usual:

      Cardinal drections


      Link must use his boat to travel. Unfortunately, Link's boat has a limitation: the boat can only move in the same direction as the Wind. So, for instance, if the wind is blowing North, Link can only travel to the North. If the wind is not blowing at all, Link doesn't move at all, too.

      Fortunately, Link has the wind waker, the magical baton. With this baton, Link can conduct the Wind's Requiem, a mystical melody that allows Link to control the wind. Each time the wind waker is used, Link can either make the wind stop blowing (this action is represented by the letter X) or make the wind blow in one of the 8 cardinal directions (North (N), South (S), East (E), West (W), Northeast (NE), Southeast (SE), Southwest (SW), Northwest(NW)).

      Wind Waker

      Link using the wind waker


      Link must go to the position (x2,y2) and stop there, to collect a legendary item. Right now, Link is at the position (x1,y1) and the wind is not blowing. You must find a trajectory from (x1,y1) to (x2,y2). A trajectory consists of a sequence of uses of the wind waker at certain positions. For example, to go from (0,0) to (1,1), a possible trajectory is:

      1. At point (0,0), make the wind blow north;
      2. At point (0,1), make the wind blow east;
      3. At point (1,1), make the wind stop blowing.

      You must find a trajectory that:

      • Minimizes the number of times Link uses the wind waker;
      • In case of a tie, minimizes the total distance traveled;
      • In case of a tie, uses the lexicographically smaller sequence of wind direction changes. Use E < N < NE < NW < S < SE < SW < W < X. For example, a trajectory that changes the wind to N, then to SW, then to W is preferable over a trajectory that changes the wind to N, then to W, then to E, because (N,NW,W) is lexicographically smaller than (N,W,E) (because N=N, NW < W).


      Check the sample input and output.

      Note: The names "Link", "The Wind Waker" and some images above are copyrighted by Nintendo (r).
      The author just wanted to make the problem more interesting. The author supports Nintendo!

      Input

      The input file consists of one or more test cases. Each test case is described by a line containing four integers x1, y1, x2, y2 (|x1|, |y1|, |x2|, |y2| ≤ 5 × 104, (x1, y1) (x2, y2)).

      The file ends with EOF.

      Output

      For each test case, print a line containing K, the number of times the wind waker is used. In the next K lines print xi yi D, meaning that the wind waker must be used to change the wind direction to D at the position (xi,yi). Print the coordinates rounded to exactly two fractional digits, and use D='S',N','W','E','SE','SW','NE','NW' or 'X'. Print the events in the order they occur in the trajectory.

      After the K lines, print the total distance traveled, rounded to exactly three fractional digits. Print a blank line after each test case. Check the sample output.

      Example

      Input:
      0 0 0 1
      0 0 3 2 Output:
      2
      0.00 0.00 N
      0.00 1.00 X
      1.000

      3
      0.00 0.00 E
      1.00 0.00 NE
      3.00 2.00 X
      3.828


      Added by:Ricardo Oliveira [UFPR]
      Date:2013-03-11
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14122. Inverse of Recurrence Problem With a Square Root

      Problem code: IRECSQRT


      Given this recurrence formula (be careful, it's in inverse form):

      Formula

      Given (0 ≤ n < 264) and (0 < m < 264), your task is to compute an modulo m.

      It's guaranteed that an is always an integer.

      Input

      First line containing an integer T (0 < T ≤ 5×104), than T cases follow.

      For each test case there're two integers n and m, writen in one line, separated by a space.

      Output

      For each test case, output the required answer: an modulo m.

      Example

      Input:
      10
      0 10
      1 10
      2 10
      3 10
      10 10
      100 100
      1000 1000
      10000 10000
      100000 100000
      9876543210123456789 1234567890987654321
      
      Output:
      1
      
      2
      5
      5
      5
      51
      251
      6251
      6251
      657422418465782775

       

      Time limit ~7x My program speed: Click here to see my submission history and time record for this problem

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-03-14
      Time limit:13s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ONMIPA sel 2013









      SPOJ Problem Set (classical)

      14138. Amazing Factor Sequence

      Problem code: AFS

      Bhelu is the classmate of Bablu who made the Amazing Prime Sequence .

      He felt jealous of his classmate and decides to make his own sequence. Since he was not very imaginative, he came up with almost the same definition just making a difference in f(n):

      a[0] = a[1] = 0;

      For n > 1, a[n] = a[n - 1] + f(n), where f(n) is the sum of natural numbers in the following set S.

      S = {x | x < n and n % x = 0}

      Now, Bablu asked him to make a code to find f(n) as he already had the code of his sequence. So, Bhelu asks for your help since he doesn't know Programming. Your task is very simple, just find a[n] for a given value of n(< 10^6).

      Input

      Your code will be checked for multiple Test Cases.

      First Line of Input contains T (<= 100), the number of Test Cases.

      Next T lines contain a single number N. (1 < N < 10^6).

      Output

      Single line containing a[n] i.e. nth number of the sequence for each test case.

      Example

      Input:
      3
      3
      4
      5
      Output:
      2
      
      5
      6
      Explanation:
      f(2) = 1 {1}
      f(3) = 1 {1}
      f(4) = 3 {1, 2}
      f(5) = 1 {1}

      Added by:c[R]@zY f[R]0G
      Date:2013-03-15
      Time limit:3s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      14156. Movie Theatre Madness

      Problem code: THEATRE

      Problem Statement

      A group of friends have gone to watch the first day first show of an awesome new movie. However, since they did not book the tickets well in advance, they have ended up with crazy seats. To be more specific, rather than getting seats such that all the friends are seated in the same row, they have ended up with seats such that all of them are seated in the same column! Now this is very inconvenient since they won't be able to chat with each other during the movie or have any kind of fun, but they are okay with this since they'd rather watch the movie like this, than not watch the movie at all.

      But there is another problem apart from this. Now we know that all the friends are seated in a single column, one behind the other. Since all of them reached the theatre just in time for the movie, they rushed and occupied the first of the booked seats that they could find. However all the friends have different heights, and due to the lack of planning, there is no guarantee that a shorter person is always seated in front of a taller person. But this would mean that the shorter person would struggle to see the screen throughout the movie !

      But the movie has started and it's too late now to do anything.

      What you need to do is the following : For every person, find the height of the closest person seated in front of him/her who is blocking his/her view ( that is, the person closest in front with a greater height ). If no such person exists, take this height as 1. Print the product of all such values modulo 1000000007.

       

      Input

      On the first line you have a single integer N ( 2<=N<=105 ), the total number of friends.

      This is followed by N space separated integers a1 a2.... aN, which correspond to the height of the people from back to front.That is, a1 is the height of the person seated on the last row, a2 is the height of the person seated on the second last row ( just in front of a1 ) and so on... uptil aN which is the height of the person seated right at the very front ( 1<=ai<=109 ). Note that all these integers are distinct.

      Output

      On a single line, output the result. ( For every person, find the height of the closest blocking person. This value is 1 if no such person exists. Print the product of all these values modulo 1000000007 ).

      NOTE : By closest blocking person to ai we mean find aj, such that aj>ai, j>i, and ( j-i ) is minimum. ( Please look at sample test cases for further clarity )

       

      Example

      Input #1:
      5
      5 2 1 4 3
       
      Output #1:
      16


      Input #2:

      5
      9 8 3 5 7

      Output #2:
      35


      Input #3:
      10
      30 10 50 70 11 60 20 80 31 12

      Output #3:
      999962375

      Explanation :

      Input #1 :

      blockingHeight( 5 ) = 1 ( since 5 is the tallest, no one is blocking him )
      blockingHeight( 2 ) = 4
      blockingHeight( 1 ) = 4 ( Note that although 3 is also taller that 1, 4 is closer to 1 )
      blockingHeight( 4 ) = 1 ( No one blocking 4 )
      blockingHeight( 3 ) = 1 ( No one blocking 3 )

      Answer=1*4*4*1*1=16


      Added by:Gowri Sundaram
      Date:2013-03-16
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      14168. Amazing Factor Sequence (medium)

      Problem code: AFS2


      Warning

      Here is a harder version of Amazing Factor Sequence .

      To make things clear, you'll need a O(n^0.5) method to solve this problem. You'll need to be careful with container of C-like language, and/or you'll need to find some little optimizations with slower language.

      The factor sequence

      We define our factor sequence with:

      a[0] = a[1] = 0, and

      for n > 1, a[n] = a[n - 1] + sum({x | x < n and n % x = 0}).

      Input

      First line of input contains an integer T, the number of test cases.

      Each of the next T lines contains a single integer n.

      Output

      For each test case, print a[n] on a single line.

      Example

      Input:
      3
      3
      4
      5
      Output:
      2
      5
      6

      Constraints

      0 < T < 101
      0 < n < 12148001999
      

      Numbers n are uniform-randomly chosen. Nmax was carefully chosen ;-)
      Time limit is ×2.5 my python one (5.26s).


      Added by:Francky
      Date:2013-03-16
      Time limit:13.14s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:AFS









      SPOJ Problem Set (classical)

      14175. Power Factor Sum Sum (hard)

      Problem code: AFSK


      Here is a mixed edition of Divisor Summation Powered and Amazing Factor Sequence (medium).

      The powered factor sequence

      For k an integer number, we define our powered factor sequence with:

      ak[0] = 0; ak[1] = 1, and

      for n > 1, ak[n] = ak[n - 1] + sum({x^k | 0 < x ≤ n and n % x = 0}).

      Input

      First line of input contains an integer T, the number of test cases.

      Each of the next T lines contains three integers n, k, m.

      Output

      For each test case, print ak[n] on a single line.
      As the answer could be a big number, you just have to output it modulo m.

      Example

      Input:
      3
      3 1 10
      4 2 55
      5 3 97
      Output:
      8
      37
      43

      Constraints

      0 < T < 101
      0 < n < 10^9
      0 < k < 11
      1 < m < 10^17
      

      Numbers n, k, m are uniform-randomly chosen.
      For your information, there's two input files, the first one is 'easy' with n≤100.
      My (1kB)-python code get AC around 2.4s. I have a much slower basic PIKE AC (19s).


      Added by:Francky
      Date:2013-03-17
      Time limit:30s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14181. LIFE IS A RACE

      Problem code: LIFERACE

       

      Life is a race with hard working humans . Assume an hypothetical situation in which God has to send many humans on earth with some level of intelligence . Level of intelligence is measured in a whole number. God has to take care that person arriving later on earth should have more level of intelligence so as to cope with the competitive world. God’s assistant suggested him a non-decreasing sequence called S .  Lets see the sequence.
      Description of Sequence:
      Any natural number n occurs exactly S[n] times and all n occurs consecutively. Few terms are stated below.
      n 1 2 3 4 5 6 7 8 9 10…………….....
      S(n) 1 2 2 3 3 4 4 4 5 5 …………………
      So , Person 1 arrives on earth with level of intelligence=1
      Person 2 arrives on earth with level of intelligence=2
      Person 3 arrives on earth with level of intelligence=2
      Person 4 arrives on earth with level of intelligence=3
      And so on….
      But God sends some Good hearted Person(Person who not only lives for themselves but for the world) when n ‘s cube root is an Positive integer.  But there is a SuperGod which rarely opens his eyes and as he opens his eyes ,he increases  the level of intelligence of some of the Good Hearted Persons. Now God needs to know the total level of intelligence of some of the Good Hearted People.
      Good hearted Person 1: Person 1
      Good hearted Person 2: Person 8
      Good hearted Person 3: Person 27
      Good hearted Person 4: Person 64
      And so on…..
      God needs a programmers to solve his queries. God’s input data Format is explained Below. 
      Will You help God??(He might increase your lifetime )
      Input
      First line of input contains 2 integer, x and y, where x denotes the number of time the SuperGod opened his eyes  and y denotes the number of queries of God.
      Next x lines follows 3 integers L,R,I  ,which denotes that SuperGod has increased the Level of Intelligence of Good Hearted People ranging between L and R(inclusive both) by a constant I.
      Next y lines follows 2 integers L,R  ,which denotes that God needs to know the Total level of intelligence of Good Hearted Persons ranging between L and R(inclusive both).
      Output
      Output should contain exactly y lines ,each containing the total answer.
      Sample Input
      1 1
      1 1 1
      1 2
      Sample Output
      6

       

      Life is a race with hard working humans . Assume a hypothetical situation in which God has to send many humans on earth with some level of intelligence . Level of intelligence is measured in a whole number. God has to take care that person arriving later on earth should have more level of intelligence so as to cope with the competitive world. God’s assistant suggested him a non-decreasing sequence called S .  Lets see the sequence.

      Description of Sequence:

      Any natural number n occurs exactly S[n] times and all n occurs consecutively. Few terms are stated below.

       

      n     1 2 3 4 5 6 7 8 9 10 11  12…………….....

      S(n) 1 2 2 3 3 4 4 4 5 5   5    6…………………

      S[1000]=86

      So , Person 1 arrives on earth with level of intelligence=1

      Person 2 arrives on earth with level of intelligence=2

      Person 3 arrives on earth with level of intelligence=2

      Person 4 arrives on earth with level of intelligence=3

      And so on….

      But God sends some Good hearted Person(Person who not only lives for themselves but for the world) when n ‘s cube root is a Positive integer.  But there is a SuperGod which rarely opens his eyes and as he opens his eyes ,he increases  the level of intelligence of some of the Good Hearted Persons. Now God needs to know the total level of intelligence of some of the Good Hearted People.

      Good hearted Person 1: Person 1

      Good hearted Person 2: Person 8

      Good hearted Person 3: Person 27

      Good hearted Person 4: Person 64

      And so on…..

      God needs a programmer to solve his queries. God’s input data Format is explained Below. 

      Will You help God??(He might increase your lifetime :) )

      Input

      First line of input contains 2 integer, x and y, where x denotes the number of time the SuperGod opened his eyes  and y denotes the number of queries of God.

      Next x lines follows 3 integers L,R,I  ,which denotes that SuperGod has increased the Level of Intelligence of Good Hearted People ranging between L and R(inclusive both) by a constant I.

      Next y lines follows 2 integers L,R  ,which denotes that God needs to know the Total level of intelligence of Good Hearted Persons ranging between L and R(inclusive both).

      Note:

       Good Hearted Person L is Person L*L*L 

      Good Hearted Person L+1 is Person (L+1)*(L+1)*(L +1)

      .....

      ...

      Good Hearted Person R is Person R*R*R 

      Output

      Output should contain exactly y lines ,each containing the answer.

      Sample Input

      1 1

      1 1 1

      1 2

      Sample Output

      6

      Explanation of Test Data:

       Asnwer is S[1]+S[2*2*2]+1=6

      Constraints:

       x<=100000

      y<=100000

      L,R>=1

      L,R<=999999

      I<=10

       

       

      Click here to see my set of problems at Spoj.


      Added by:Devendra Agarwal
      Date:2013-03-18
      Time limit:1s
      Source limit:5000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem.









      SPOJ Problem Set (classical)

      14329. Magic of the locker

      Problem code: LOCKER


      Vertu, the clever businessman, sells the ropes to his customers at the rate of 1 rupee per meter. He can only sell an integer length of a rope to a customer. Also, he has a magic locker which functions this way:
          Suppose the locker has 'x' rupees. Now if 'y' rupees more are put into this locker, it multiplies them and total money in the locker now is 'x*y'.
      This morning, Vertu starts his bussiness with 'n' meters of rope. He puts 1 rupee in the locker as to have good luck.
      Find the maximum money he can earn today considering that he sold all of his rope at the end of the day.

      NOTE: Vertu has to put all rupees into the locker as soon as he gets it, and can get rupees from locker only at the end of the day.

      Input  and Output

      The first line contains t, the number of test cases. t lines follow, each containing one positive integer n. For each of these integers, print the required answer modulo(109+7).

      Constraints

      t<105

      0<n<1012

      Example

      Input:
      2
      4
      5
      Output: 4
      6

      Added by:Lalit Kundu
      Date:2013-03-28
      Time limit:1s
      Source limit:5000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14330. Power of Phi(medium)

      Problem code: POWERPHI

      Vertu was very impressed by the golden ratio φ=(1+√5)/2 and about it occurring in nature and all that. He now begins to wonder if any non negative integral power of φ is also special. Since he does not like working with decimals, he decided to approximate the positive integral power of φ to its closest integer. Help him by printing the closest integer to φn , given n.

       

      Input and Output
      The first line contains t, the number of test cases. t lines follow, each containing one positive integer n. For each of these integers, print the closest integer to φn. If you think there are two closest possible integers, print either of them. Print the answer modulo(109+7).

      Constraints

      t<=100000

      0<=n<=109

       

      EXAMPLE:

      INPUT:

      2

      1

      3

      OUTPUT:

      2

      4


      Added by:Lalit Kundu
      Date:2013-03-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14334. Evil Overlord Cypher

      Problem code: DIXIE001

      You have been imprisoned by an evil, but stupid alien overlord. You told them it was a trap. It's not your fault. IT'S NOT YOUR FAULT.

      You can pass notes containing information to other prisoners to coordinate your escape. You want to use an algorithm that can be easily deciphered by your fellow prisoners, in between torture sessions of forced “Buffy the Vampire Slayer” marathons. But you also want the notes to remain unreadable to evil alien overlord and his minions should the notes be discovered.

      Therefore, you choose to implement a simple Caesar cypher given the following rule:

      When the characters in the document are sorted by frequency, then by ASCII code (case sensitive), each character is replaced by the character in the same position in the reversely sorted set. Make a single character frequency lookup for ENTIRE file.

      Given an arbitrary body of text as input, produce the appropriate output based on the cypher.

      The first line of the input will contain a count of all the remaining lines, the remaining line are all part of the text to be encrypted.

      Note: The symbol in the examples below represents a newline character. You may also ignore (strip/pop off) the first line of the input. It was added for languages that have difficulty (or lack of ability) detecting EOF.

      Also note that the newlines in the input text are treated as any other character and are encoded with the rest of the text. Note in particular that the last line of output may not end with a newline character. THIS IS WHITESPACE SENSITIVE.

      The sample input contains no whitespace characters at the end of a line unless marked with ¶ symbol at which point there is a newline character.

      Sample Input 1

      1
      Aliens are dumb


      Sample Output 1

       mn
      ibAud
      Aralse



      Sample Input 2

      1
      Mississippi
       

      Sample Output 2

      spMMpMMpiip

       

      Sample Input 3

      2
      Missi
      ssippi

      Sample Output 3

      iM

      Ms

      MppM


      Added by:Dixie State University
      Date:2013-03-30
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Created by Daniel Evans for the DSU 2013 ACM Competition









      SPOJ Problem Set (classical)

      14387. Science

      Problem code: SCIENCE


      May 30th 2014 - Due to a change in compilers the grader for this problem is no longer working and there appears to be technical issues preventing me from fixing it.  Have contacted SPOJ about it and will update when resolved.

      Welcome, ladies and gentlemen, to Aperture Science. Astronauts, war heroes, Olympians -- you're here because we want the best, and you are it. That said it's time to make some science.

      Now I want each of you to stand on one of these buttons. Well done, we're making great progress here. Now let's do it again. Oh come on, don't stand on the same button. Move people! No, no, that button's only for the astronauts, you know who you are. What?! You say you can't do everything I ask. Ok let's start over. You there, the Olympian, figure out how many times we can do this. And make it quick, we have a lot more science to get through.

      Input

      The first line will contain N (2 ≤ N ≤ 200) giving the number of people (and the number of buttons) in the experiment. The next N lines will contain N characters each. If the jth character of the ith line is 'Y' it indicates that the ith person can stand on the jth button (it is 'N' otherwise). The last line of input will be a 0.

      Output

      If it is impossible to get everyone on the buttons at once output "NO SCIENCE" (quotes for clarity). Otherwise first output K, the maximum number of times everyone can be standing on buttons such that nobody stands on the same button more than once. After that output K lines. Each line should contain N integers separated by a space where the ith integer describes who is on the ith button. All of the lines should be valid and none of them should put the same person on the same button.  If there are multiple solutions, output any of them.

      Examples

      Input:
      
      3
      YYY
      NYY
      YNY Output:
      2
      1 2 3
      3 1 2

      Input:

      2
      YN
      YN
      Output:

      NO SCIENCE

      Added by:Mark Gordon
      Date:2013-04-02
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:2012 University of Chicago Invitational Contest (but with harder constraints)









      SPOJ Problem Set (classical)

      14435. Decipher the AMSCO cipher

      Problem code: AMSCO2

      Here you have to decipher the AMSCO cipher :

      Due to A.M.SCOtt in the 19th century, it's an incomplete columnar transposition cipher
      with alternating single letters and digraphs
      . The first entry must be a digraph.
      In both even and odd periods the first column and the first row always alternate:

      7 4 5 6 3 2 1
      RI D ER S ON T HE
      S TO R MI N TO T
      HI S HO U SE W EA
      R EB O RN J IM M
      OR R IS O N

      Input

      N lines (N<1000)
      Each line of the input contains the numeric key (permutation order of the columns)
      and a ciphertext. Ciphertext letters are in [A-Z] only with no punctuation.
      The keylength max is 9 and the length of the ciphertext is limited to 250.
      The last line ends with EOF.

      Output

      Output consist of exactly N lines of plaintexts with letters in [A-Z] with no spaces.

      Example 1:

      Input:
      7456321 HETEAMTTOWIMONNSEJNDTOSEBRERRHOOISSMIURNORISHIROR Output:
      RIDERSONTHESTORMINTOTHISHOUSEWEAREBORNJIMMORRISON

      Example 2:

      Input:
      41325 CECRTEGLENPHPLUTNANTEIOMOWIRSITDDSINTNALINESAALEMHATGLRGR Output:
      INCOMPLETECOLUMNARWITHALTERNATINGSINGLELETTERSANDDIGRAPHS

      Added by:legrand
      Date:2013-04-04
      Time limit:0.800s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:ADA AWK BASH C C++ 4.3.2 C++ 4.0.0-8 C99 strict LISP sbcl LISP clisp FORT GO HASK JAVA LUA CAML PAS fpc PAS gpc PERL PHP PIKE PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n RUBY SCM guile SCM qobi
      Resource:classical ciphers









      SPOJ Problem Set (classical)

      14441. Three Circle Problem (EASY)

      Problem code: CIRCLE_E

      Given 3 distinct circles with positive integer radius R1R2, and R3, and arranged like in the picture below:

      Three Circle Problem

      Now, your task is to compute radius of small circle that can be created like yellow circle in the picture above. All circles in the picture above tangent each other.

      Input

      The first line in the input data, there is an integer T(0 < T ≤ 103) denoting number of test cases, than T lines follow.

      For each lines, there are three integer R1R2, and R3, (0 < {R1,R2,R3} < 109) denoting radius of each circle like in the picture above.

      Output

      For each test case, output radius of small circle that can be made, like in the picture above. Any output with absolute error less than 10-6 is accepted.

      Example

      Input:
      3
      1 1 1
      10 10 10
      23 46 69
      
      Output:
      0.154701
      1.547005
      6.000000

       

      You can see my submission history and time record for this problem: here

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-04-05
      Time limit:5s
      Source limit:10000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      14443. Three Circle Problem (HARD)

      Problem code: CIRCLE_H

      Given 3 distinct circles with positive integer radius R1R2, and R3, and arranged like in the picture below:

      Three Circle Problem

      Now, your task is to compute radius of small circle that can be created like yellow circle in the picture above. All circles in the picture above tangent each other.

      Input

      The first line in the input data, there is an integer T(0 < T ≤ 105) denoting number of test cases, than T lines follow.

      For each lines, there are three integer R1R2, and R3, (0 < {R1,R2,R3} < 1030) denoting radius of each circle like in the picture above.

      Output

      For each test case, output radius of small circle that can be made, like in the picture above. Truncate the output to 50 digit after decimal point.

      Example

      Input:
      3
      1 1 1
      10 10 10
      23 46 69
      
      Output:
      0.15470053837925152901829756100391491129520350254025
      1.54700538379251529018297561003914911295203502540253
      6.00000000000000000000000000000000000000000000000000

       

      You can see my submission history and time record for this problem: here

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-04-05
      Time limit:10s
      Source limit:10000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      14542. Pythagorean triples (medium)

      Problem code: PYTRIP2


      Pythagoras is credited, by tradition, for the first proof of the relation a2 + b2 = c2 in any right angled triangle where c is hypotenuse and a and b are the catheti.

      We define a Pythagorean triple as a set of three positive integers a, b, and c which satisfy the above equation , ie , a2 + b2 = c2.
      {3,4,5} is the most common example of such triples.

      Input

      The first line of input contains an integer T, the number of test cases.

      Each of the next T lines contains two integers N, M.

      Output

      For each test case, print on a single line the number of Pythagorean triplet {a,b,c} such that N ≤ a,b,c ≤ M.

      Example

      Input:
      3
      1 5
      4 10
      10 100
      
      Output:
      1
      1
      45
      

      Constraints

      0 < T < 100
      0 < N < M
      0 < T × M < 1.21×10^8
      

      There are several input files.
      Time limit is ×10 my top speed with C language (1kB of code).
      For your information, my total best time is 1.09s for the 6 input files ; 1.7MB of total memory print.
      Warning, it could be hard with interpreted languages.
      You can try before the quite similar tutorial problem : PYTRIP before.

      Information

      This problem is part of the Bubble Cup competition qualification round (April 2014). Without asking anything! Half proud of the choice, I regret that some teams use multi-accounts. I let open submissions but I hope a decent attitude of solvers. If there's another troubles, my problem could be hidden and closed. Thanks for your comprehension.
      @elder_solvers: I'm very sorry for the inconvenience, you will loose many points.
      @students: good luck. GNU_salutations.


      Added by:Francky
      Date:2013-04-11
      Time limit:1s-3.299s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14543. Range Sum

      Problem code: RANGESUM

      Problem Statement

      You are initially given an array of N integers ( 1<=N<=105 ). Given this array, you have to perform 2 kinds of operations :

      (i) Operation 1 : Op1( l, r )

      You are given 2 integers l and r. ( 1 <= l <= r <= current size of the array ). You need to return the sum of all the elements with indices between l and r ( both inclusive ). That is, if the elements currently in the array are a1, a2, a3.... an, you need to return the following sum : al + al+1 + al+2 ... + ar.

      (ii) Operation 2 : Op2( x )

      You are given a single integer x ( |x| <= 109 ). Add this element to the beginning of the array. After this operation, x will now become a1, the old a1 will now become a2, and so on. The size of the array will increase by 1.

       

      Input

      The first line contains a single integer N ( 1 <= N <= 105 ), the number of elements initially in the array.

      This is followed by a line containing N space separated integers, a1 a2 .... aN. ( |ai| <= 109 )

      The next line contains a single integer Q, the number of operations you will be asked to perform. ( 1 <= Q <= 105 )

      Q lines of input follow. Each such line starts with either the number 1 or the number 2. This indicates the type of operation that you are required to perform. The format of these queries are as follows :

      1 l r : Carry out operation 1 with arguments l and r. ( 1 <= l <= r <= current size of the array )
      That is, return the sum of the following array elements : al + al+1 ... + ar

      2 x : Carry out operation 2 with the argument x. ( |x| <= 109 )
      That is, add the value x at the beginning of the array.

       

      Output

      For each query of type 1, output the return value on a new line. No output needs to be printed for queries of type 2.

       

      Example

      Input #1:
      
      10
      1 2 3 4 5 6 7 8 9 10
      4
      1 1 10
      1 1 1
      1 10 10
      1 2 7

      Output #1:

      55
      1
      10
      27


      Input #2:


      5
      6 7 8 9 10
      9
      2 5
      2 4
      1 2 7
      2 3
      2 2
      2 1
      1 1 10
      1 1 1
      1 10 10


      Output #2:


      45
      55
      1
      10

      Added by:Gowri Sundaram
      Date:2013-04-11
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14629. Play with Binary Numbers

      Problem code: HAP01


      Let S be the binary representation of an Integer. We define two functions a(i) and b(i) such that
      a(i) = Number of occurrences of '1' at odd positions of S.
      b(i) = Number of occurrences of '1' at even positions of S.
      For example: for integer 19, S=10011.
      so, a(19)=2 and b(19)=1

      Input

      First line contains an integer T. T=Number of test cases. Then T lines follow
      On each line, you will be given three integers M,N,K.

      Output

      For each test case output a single integer R.
      Where, R is the number of integers 'i' between M and N(both inclusive) such that absolute difference of a(i) and b(i) is equal to K.
      Answer of each each test case should be on separate line

      Constraints

      T<=50
      1<=M<N<=10^19
      1<=N-M<=10^6
      0<=K<=50

      Example

      Input:
      1
      1 10 2
      
      Output:
      2
      

      Added by::-)
      Date:2013-04-16
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      14664. Shared cathetus (easy)

      Problem code: CATHETEN

      For any integer n, we define F(n) as the number of ways in which n can be the cathetus (leg) of a Pythagorean triangle.
      For example, there is exactly four Pythagorean triangles whith 15 as a lenght for a cathetus.

      catheten

      (8 15 17), (15 20 25), (15 36 39), (15 112 113)

      Thus F(15) = 4.

      Input

      The first line of input contains an integer T, the number of test cases.

      Each of the next T lines contains a single integer n.

      Output

      For each test case, print F(n) on a single line.

      Example

      Input:
      3
      5
      10
      15
      
      Output:
      1
      1
      4
      

      Constraints

      0 < T < 10^5
      0 < n < 10^9
      

      For your information, my C code ran in 0.10s, whereas my python3 one ran in 2.11s.


      Added by:Francky
      Date:2013-04-19
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Old problem









      SPOJ Problem Set (classical)

      14665. Delta catheti (hard)

      Problem code: DELTACAT

      (3, 4, 5) is a famous Pythagorean triple, it gives a quick answer to the question:
      For a given integer d, is there a Pythagorean triple (a, b, c) such that b - a = d?

      A solution is (3d, 4d, 5d), and in fact one can easily prove that the set of solutions is infinite, and that there is an obvious total order on those solutions.
      Given n, you'll have to find the nth term of the sequence of solutions.

      Geometrically, it is the study of right triangles for which the difference of the catheti are equal to d.

      Input

      The first line of input contains an integer T, the number of test cases.

      Each of the next T lines contains three integers n, d, m.

      Output

      For each test case, compute the nth term amongst the solutions (a, b, c) for the problem :
      a2 + b2 = c2 with b - a = d and 0 < a < b < c .

      As the answer could not fit in a 64-bit container, simply output your answer modulo m.

      Example

      Input:
      3
      1 1 235813
      3 21 1000
      9 119 11
      
      Output:
      3 4 5
      63 84 105
      5 3 1
      

      Explanations

      For the first case, the first solution is (3, 4, 5), as 4 - 3 = 1.

      For the second case, the firsts solutions are:
      (15, 36, 39), (24, 45, 51), (63, 84, 105), (144, 165, 219), (195, 216, 291), (420, 441, 609), ...
      The third one is (63, 84, 105).

      For the third case, the first solutions are:
      (24, 143, 145), (49, 168, 175), (57, 176, 185), (85, 204, 221), (136, 255, 289), (180, 299, 349), (196, 315, 371), (261, 380, 461), (357, 476, 595), (481, 600, 769), (616, 735, 959), ...
      The 9th solution is (357, 476, 595), reduced modulo 11, we get (5, 3, 1).

      Constraints

      0 < T < 10^5
      0 < n < 10^7
      0 < d < 10^8
      1 < m < 10^9
      

      n, d, m : Uniform randomly chosen in their range.

      Constraints allow some interpreted languages to get AC, but it could be hard.
      For your information, I have two distinct solutions.
      My first python3 code get AC under 32s with 28MB of memory print.
      My second python3 code get AC under 16s with 16MB of memory print.
      With a compiled language, it should be at least 20× faster. Have fun ;-)


      Added by:Francky
      Date:2013-04-19
      Time limit:60s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14697. Loop Expectation

      Problem code: LOOPEXP


      Consider the following pseudo-code

      int a[1..N]; 

      int max = -1;

      for i = 1..N:

      if(a[i] > max) 

      max = a[i];

       

      Your task is to calculate the expected number of times the 'if' block of the above pseudo-code executes. The array 'a' is a random permutation of numbers from 1..N chosen uniformly at random. 

      Input

      First line contains t, the number of test cases. t lines follow, each containing N, the number of elements in the array.

      1<= t <= 100

      1<= n <=100,000

      Output

      For each test case, output a single decimal. Your answer should be within 10^-6 of the correct answer.

      Example

      Input:
      1
      2
      
      Output:
      
      
      1.5
      Explaination :
      for N=2, you can have the following two permutations: [1,2]  and [2,1] . 
      for the first case the if block gets executed 2 times and for the second one the if block gets executed 1 time. So the expected 
      value is (3)/2 = 1.5

      Added by:Aman Gupta
      Date:2013-04-20
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      14700. Delta catheti II (Hard)

      Problem code: DELTACA2

      (3, 4, 5) is a famous Pythagorean triple, it gives a quick answer to the question:
      For a given integer d, is there a Pythagorean triple (a, b, c) such that b - a = d?

      A solution is (3d, 4d, 5d), and in fact one can easily prove that the set of solutions is infinite, and that there is an obvious total order on those solutions.
      Given n, you'll have to find the nth term of the sequence of solutions.

      Geometrically, it is the study of right triangles for which the difference of the catheti are equal to d.

      Input

      The first line of input contains an integer T, the number of test cases.

      2T lines fallow. Each case is on two lines.
      The first line of the case contains three integers n, d, m.
      The second line contains an integer L and 2L other integers (p, e), which give the prime factorization of d in standard format (d = product p^e).

      Output

      For each test case, compute the nth term amongst the solutions (a, b, c) for the problem :
      a2 + b2 = c2 with b - a = d and 0 < a < b < c .

      As the answer could not fit in a 64-bit container, simply output your answer modulo m.

      Example

      Input:
      3
      1 1 235813
      0
      3 21 1000
      2 3 1 7 1
      9 119 11
      2 7 1 17 1
      
      Output:
      3 4 5
      63 84 105
      5 3 1
      

      Explanations

      For the first case, the first solution is (3, 4, 5), as 4 - 3 = 1.

      For the second case, the firsts solutions are:
      (15, 36, 39), (24, 45, 51), (63, 84, 105), (144, 165, 219), (195, 216, 291), (420, 441, 609), ...
      The third one is (63, 84, 105).

      For the third case, the first solutions are:
      (24, 143, 145), (49, 168, 175), (57, 176, 185), (85, 204, 221), (136, 255, 289), (180, 299, 349), (196, 315, 371), (261, 380, 461), (357, 476, 595), (481, 600, 769), (616, 735, 959), ...
      The 9th solution is (357, 476, 595), reduced modulo 11, we get (5, 3, 1).

      Constraints

      0 < T < 10^4
      0 < n < 10^18
      0 < d < 10^14
      1 < m < 10^9
      

      d is the product of two integers lower than 10^7.
      n, d1, d2, m : Uniform randomly chosen in their range.
      Those constraints are set to allow C-like users to work only with 64bit containers.

      For your information, my 3kB-python3 code get AC in 2.80s with 12MB of memory print.
      It should be much faster with a compiled language.
      Warning : It's my hardest problem. Have fun ;-)


      Added by:Francky
      Date:2013-04-21
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14742. Building Bridges(HARD)

      Problem code: BRDGHRD

      The tribe soon discovers that just communication is not enough and wants to meet each other to form a joint force against the terminator.But there is a deep canyon that needs to crossed. Points have been identified on both sides on which bridge ends can be made. But before the construction could be started, a witch Chudael predicted that a bridge can only be built between corresponding end points, i.e. a bridge starting from the ith end point on one side can only end on the ith end point on the other side, where the position of end points is seen in the order in which the points were identified. If not, it would lead to the end of the tribe. The tribe just wants to make as many non-overlapping bridges as possible, with the constraint in mind.

      Input

      The first line of the input contains test cases t. It is followed by 3*t lines, 3 for each test case. The first line of input for each test case contains the number of end points identified on each side, n (1<=n<=105). The second line contains x-coordinates of end points identified on the first side and similiarly the third line contains the x-coordinates of corresponding end points identified on the other side. The end points are inputted in the order in which they were identified.  The x-coordinates can range between -106 to 106.

      Output

      You are required to output a single line for each test case. The line contains a single integer – the

      maximum number of bridges possible with the constraints explained above.

      Example

      Input:
      3

      4

      2 5 8 10

      6 4 1 2

      3

      5 3 10

      6 4 1

      6

      1 2 3 4 5 6

      3 4 5 6 1 2

      Output:

      2

      2

      4

       

      Expalanation: For the first test case, two non-overlapping bridges can be formed between the 3rd

      and 4th end points on each side.

      (This problem is based on: http://www.spoj.com/problems/BRIDGE.)


      Added by:Alex Abbas
      Date:2013-04-27
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Based on: Building Bridges By Troika::Bytes









      SPOJ Problem Set (classical)

      14751. Self Descriptive Number

      Problem code: SELFDESN


      A positive integer m is called "self-descriptive" in base b, where b≥2 and b is an integer, if:

      i) The representation of m in base b is of the form (a0a1...ab-1)b

      (that is m=a0bb-1+a1bb-2+...+ab-2b+ab-1, where 0≤ai≤b-1 are integer)

      ii) ai is equal to the number of occurences of number i in the sequence (a0a1...ab-1).

      For example, (21200)5 is "self-descriptive" in base 5, because it has five digits and contains two 0s, one 1s, two 2s, and no (3s and 4s).

      (21200)5 = (1425)10 so 1425 is "self-descriptive" number.

      Given n(1 ≤ n ≤1018)and m (1 ≤ m ≤ 109), your task is to find the n-th smallest "self-descriptive" number.

      Input

      The first line there is an integer T (1 ≤ T ≤ 105).

      For each test case there are two integers n and m written in one line, separated by a space.

      Output

      For each test case, output the n-th smallest "self-descriptive" number, (output the number in base 10) modulo m.

      Example

      Input:
      2
      1 1000
      2 1000
      
      Output:
      100
      136

      Explanation

      100 is "self descriptive" number in base 4: (1210)4

      136 is "self descriptive" number in base 4: (2020)4

       

      Time limit ~230x My program speed: Click here to see my submission history and time record for this problem

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-04-28
      Time limit:25s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IMC 2009 + My Idea to modify that problem









      SPOJ Problem Set (classical)

      14761. Almost-isosceles Pythagorean triple (easy)

      Problem code: ALMISPY

      (3, 4, 5) is the smallest almost-isosceles Pythagorean triple, as 4 - 3 = 1.
      Let S = { (a, a+1, c) | a2 + (a+1)2 = c2 with a and c positive integers}.
      One can prove that the set S of almost-isosceles Pythagorean triples is infinite.
      There is an obvious total order on this set.

      Input

      The first line of input contains an integer T, the number of test cases.
      On each of the next T lines, your are given two integers n and m.

      Output

      For each test case, you have to find the nth triple (a, a+1, c) in the ordered set S, and print a and c. As the answer could not fit in a 64-bit container, simply output your answer modulo m.

      Example

      Input:
      3
      1 10
      2 123
      4 289
      
      Output:
      3 5
      20 29
      118 118
      

      Constraints

      0 < T < 10^4
      0 < n < 10^18
      1 < m < 10^9
      

      For your information, my 500B-python3 code get AC in 1.61s with 12MB of memory print.
      In Python2.7 : (2.49s, 4.0MB), in Python2+psyco (2.04s, 36MB).
      My 1kB C code ran in (0.04s, 1.6MB), and time limit is ×125 this one.
      Have fun ;-)
      (edit) With wisfaq observation, all my best timings are divided by exactly two!!!


      Added by:Francky
      Date:2013-04-30
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14819. Permutation Generator

      Problem code: PERMTGEN

      Hasan Jaddouh has invented a new algorithm for generating permutations this algorithm takes an array with length N as input and generate a permutation with length N from this array.

      the array must satsify (1 <= Ai <= i) in order for the resulting array to be a permutation.

      and here is the pseudo code of the algorithm:

      read N
      for i=1 to N do
      read A[i]
      for i=1 to N do
      for j=1 to i-1 do
      if A[j] >= A[i] do
      A[j]=A[j]+1
      for i=1 to N do
      print A[i]

      but unfortunately for Hasan Jaddouh, his algorithm is too slow for big arrays so he asked you to help him to find a fast way to implement  his algorithm.

      your program should read input same as the pseudo code and output the new array

      Input

      first line contains integer N (1 <= N <= 105)

      second line contains N integers separated by spaces each interger is between 1 and 109 inclusive

      note: in order for Hasan Jaddouh's algorithm to work and generate a permutation the constrain (1 <= Ai <= i) must be satsified but to make this problem harder this constrian is not guaranteed so it's also not necessary that the output is a permutation.

      Output

      Output N integers separated by spaces, the new array after applying Hasan Jaddouh's algorithm

      Example

      Input:
      4
      4 2 1 3
      Output:
      7 4 1 3
      

      Added by:Hasan Jaddouh
      Date:2013-05-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      14820. Return of the Digger

      Problem code: RETDIG

      The adventures of “Digger” continue as he once again searches for treasure. This time, his money senses detect it underground. His plan is to dig down to it using an automatic pickaxe and his souped-up pneumatic drill.

      The treasure is within a thin stretch of land, running West to East, that is made up of dirt and some rocks. This stretch is $L$ ($1 \leq L \leq 200$) metres long. Digger’s money senses are very exact, and he knows the location of the treasure he seeks – it is no more than $10000$ metres below the surface. In addition to money senses, he apparently also has rock senses, which can pinpoint $N$ ($1 \leq N \leq 5000$) rocks among the dirt, none of which will be at a depth of more than $10000$ metres.

      Digger’s specially-designed pneumatic drill can only go straight down, and it can tunnel through dirt easily – however, it isn’t equipped with brakes, so it keeps on going until it hits a rock. When this happens, it stops just above the rock, but the drill bit also breaks. This time, Digger doesn’t have to worry about fuel – instead, he just wants to avoid breaking his drill bits! Once stationary, Digger can also use his pickaxe to dig left and right (yes, even through rocks!), but he can’t dig up or down with it.

      The treasure is pretty fragile, so Digger definitely doesn’t want to drill right into it. Instead, he can either get to the same depth as it and use his pickaxe to dig to it, or he can use his pneumatic drill to go right past it (either 1 metre to the left or right of it). However, once he gets his hands on the treasure, Digger’s plan isn’t complete – he intends to keep drilling down until he gets to China. As such, he must first navigate past the deepest of the $N$ rocks – at that point, it’s all dirt (or so he hopes...).

      Digger can start anywhere on the surface. Determine the minimum amount of drill bits that he must break in order to retrieve the treasure and dig down past all the rocks, if it’s possible at all.

      Input

      Line $1$: $L$ and $N$ – respectively, the length of the stretch of land (in metres) and the number of rocks.

      Lines $2..N+1$: $A$ and $B$ – the $i$th line gives the location of the ($i-1$)th rock, where $A$ is its depth, and $B$ is its distance from the West edge of the stretch of land (both in metres).

      Line $N+2$: $Y$ and $X$ – the location of the treasure, where $Y$ is its depth, and $X$ is its distance from the West edge of the stretch of land (both in metres). The treasure will not be within a rock.

      Output

      If it’s impossible for Digger to reach the treasure and dig down past all the rocks, output “Use dynamite”.

      Otherwise, output a single number – the minimum number of drill bits Digger must break to accomplish this.

      Example

      Input:
      10 20
      1 5
      2 1
      2 2
      2 4
      2 5
      2 6
      2 8
      2 9
      3 3
      4 7
      4 8
      4 9
      5 3
      5 4
      5 5
      5 6
      6 3
      10 1
      10 2
      10 7
      8 6
      Output:
      3
      Explanation of Sample:

      Digger starts on the surface, 7 metres from the West edge of the stretch of land. He drills down for 3 metres until he hits a rock and breaks his first drill bit. He then uses his pickaxe to walk to the left, and drills down another metre, hitting another rock and breaking his second drill bit. He then walks to the right (through a rock), and drills down for 5 metres, picking up the treasure on the way, until he hits another rock and breaks his third and final drill bit. He then walks to the right and drills down past the last rock. This route is shown below (‘.’: dirt, ‘x’: rock, ‘T’: treasure, ‘D’: drill, ’<’ or ‘>’: pickaxe):

      .....x.D..
      .xx.xxxDxx
      ...x..<D..
      ......D>xx
      ...xxxxD..
      ...x...D..
      .......D..
      ......TD..
      .......D>.
      .xx....xD.
      ........D.

       


      Added by:Jacob Plachta
      Date:2013-05-06
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14821. Traffic Lights

      Problem code: TLIGHTS


      Jim-Bob lives in a strange city where the streets don’t necessarily run NS or EW. Instead, the $N$ ($1 \leq N \leq 10^5$) streets run seemingly at random, sometimes crossing over each other by bridges, and intersecting with one another at exactly $K$ ($1 \leq K \leq 1000$) intersections. Each intersection consists of some streets coming together, as well as a traffic light.

      Street $i$ starts at intersection $s_i$ ($1 \leq s_i \leq K$), and ends at a different intersection $e_i$ ($1 \leq e_i \leq K$), going through no other intersections in between. It takes $t_i$ ($1 \leq t_i \leq 1000$) minutes to travel down street $i$ (this number is derived from the length, the average pothole size, and the amount of roadkill). Each road can be travelled in either direction in the same amount of time.

      The traffic lights in this city are also strange. First of all, each one only alternates between green and red. Each light also cycles through these colours at a different rate – the traffic light located at intersection $i$ stays green for $g_i$ ($1 \leq g_i \leq 1000$) minutes, then stays red for $r_i$ ($1 \leq r_i \leq 1000$) minutes, then goes back to green, and so on.

      Jim-Bob always obeys the law, and will never run a red light. If he arrives at an intersection while the light is green, he can pass right through it. Otherwise, he must wait there until the light turns green. If he gets to an intersection just as the traffic light is turning red, he must wait. It takes no time to drive through an intersection, so the light will never turn red on him as he drives through.

      Jim-Bob starts at his house, also known as intersection $1$. As soon as he leaves his house, all the traffic lights turn green, starting their green-red-green cycle. He wishes to drive to Billy-Bob’s house (which is right at intersection $K$) as fast as possible. Neither the starting nor the finishing intersections have traffic lights, so their $g$ and $r$ values will be given as 0. Find the minimum number of minutes Jim-Bob can take to drive from his house to Billy-Bob’s.

      Input

      Line $1$: 2 integers, $N$ and $K$

      Next $N$ lines: 3 integers, $s_i$, $e_i$, and $t_i$, for $i=1..N$

      Next $K$ lines: 2 integers, $g_i$ and $r_i$, for $i=1..K$

      Output

      A single integer – the minimum number of minutes it takes to drive from Jim-Bob’s house to Billy-Bob’s. It will always be possible to do this.

      Example

      Input:
      7 6
      1 2 4
      1 3 1
      3 5 2
      2 4 2
      2 5 6
      5 4 2
      5 6 10
      0 0
      5 5
      1 20
      2 5
      10 2
      0 0
      Output:
      19
      Explanation of Sample:

      Jim-Bob can drive to intersection 2 (4 min), drive on to intersection 4 (2 min), wait for the green light (1 min), drive down to intersection 5 (2 min), and finally drive to Billy-Bob’s house (10 min). This is a total of 19 minutes.

      Note: The traffic light at intersection 3 only stays green for 1 minute, which means that Jim-Bob would just miss it if he drove directly there. On the other hand, he makes the green lights at intersections 2 and 5 just in time, as they turn red 1 minute after he passes.

       


      Added by:Jacob Plachta
      Date:2013-05-06
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14822. Battleships

      Problem code: BSHIP


      You and a friend are playing the classic game of Battleships. You each have a grid consisting of $M$ rows of $N$ cells each ($1 \leq M,N \leq 2000$). Each cell is either empty or contains a player’s ship (in this version of the game, all ships are the size of one cell). The goal of the game is to destroy all of the opponent’s ships by hitting individual cells.

      You and your friend have bet tons of Internet Points on this game. Unfortunately, your friend is completely owning you. So desperate times call for desperate measures.

      You know for a fact that you can distract your friend for a brief moment by telling him that a famous programmer is behind him, but this trick will only work exactly once (programmers are so predictable). While he isn’t looking, you’ll have time to snatch up some of his ships with one hand. Your hand can cover a square of exactly $S$x$S$ cells ($1 \leq S \leq min\{M,N\}$), and you can gather all the ships within such a square at once.

      Of course, your friend is no fool, so he’s got his grid well concealed. As such, you don’t know anything about it except its size, so when the time comes, you’ll just choose a random square of size $S$x$S$ that’s completely within the grid.

      As usual, these bets attract large crowds. One of the bystanders who can see your opponent’s grid knows your plan, and is curious as to the expected number of ships that you will grab (in other words, the average number of ships out of all the possible snatches you could make). Nerdy though he is, he can’t calculate it in his head, so he runs over to a computer and codes up a program...

       

      Input

      Line $1$: 3 integers, $M$, $N$, and $S$

      Next $M$ lines: $N$ characters each, representing your opponent’s grid – an ‘X’ represents a ship, while a ‘.’ represents an empty cell

      Output

      A single number – the expected number of ships that you’ll grab, rounded to 6 decimal places.

      Example

      Input:
      3 4 2
      XX.X
      XX..
      .X..
      Output:
      
      2.000000
      Explanation of Sample:

      There are 6 possible areas you could pick, yielding this many ships each:

      4 2 1
      3 2 0

      This is a total of 12 ships, for an average of exactly 2 per grab.


      Added by:Jacob Plachta
      Date:2013-05-06
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14823. Advanced Battleships

      Problem code: ABSHIP


      You managed to beat your friend in Battleships and take his Internet Points! Perfectly legitimately, of course. However, for some strange reason he’s upset, and now challenges you to a rematch - this time at the game of Advanced Battleships, and with even higher stakes!

      You each have a grid consisting of $M$ rows of $N$ cells eacg ($1 \leq M,N \leq 500$). Each cell is either empty or contains part of a player’s ship. What makes this game so “advanced” is the fact that each ship consists of a maximal set of 1 or more adjacent, nonempty cells. Two cells are considered adjacent if they share a common side. Of course, this means that ships can have some very strange shapes. No two ships can be adjacent to one another, of course.

      You know for a fact that you can distract your friend for a brief moment, this time by telling him that someone proved that P = NP, but this trick will again only work exactly once. While he isn’t looking, you’ll have time to snatch up some of his ships with one hand. Your hand can cover a square of exactly $S$x$S$ cells ($1 \leq S \leq min\{M,N\}$), and you can gather all the ships that are at least partially within such a square at once.

      Of course, your friend is no fool, so he’s got his grid well concealed. As such, you don’t know anything about it except its size, so when the time comes, you’ll just choose a random square of size $S$x$S$ that’s completely within the grid.

      As usual, these bets attract large crowds. One of the bystanders who can see your opponent’s grid knows your plan, and is curious as to the expected number of ships that you will grab (in other words, the average number of ships out of all the possible snatches you could make). Nerdy though he is, he can’t calculate it in his head, so he runs over to a computer and codes up a program... 

      Input

      Line $1$: 3 integers, $M$, $N$, and $S$

      Next $M$ lines: $N$ characters each, representing your opponent’s grid – an ‘X’ represents a ship, while a ‘.’ represents an empty cell

      Output

      A single number – the expected number of ships that you’ll grab, rounded to 6 decimal places.

      Example

      Input:
      5 5 2
      XXXX.
      X..X.
      X..X.
      X....
      .XX..
      Output:
      
      0.875000
      Explanation of Sample:

      There are 16 possible areas you could pick, yielding this many ships each:

      1 1 1 1
      1 0 1 1
      1 0 1 1
      2 1 1 0

      This is a total of 14 ships, for an average of 0.875 per grab.


      Added by:Jacob Plachta
      Date:2013-05-06
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14830. The Codefather

      Problem code: CFATHER

      The computer science mafia, headed of course by the Codefather, have control of the computer science course points spreadsheet. The Codefather has the power to transfer points from one person to another.

      The Codefather’s daughter is getting married, and he wants to give a gift to his future son-in-law, who happens to be taking this computer science course. Since only the person with the most points can get a mark of 100% in this course, the Codefather wants to insure that his future son-in-law will have strictly more points than anyone else by performing a number of point transfers. However, he’s a cautious man (in his business, you have to be), so he follows the following rules:

         1. None of the transfers will involve his future son-in-law.

         2. For each pair of people, he will only perform up to one point transfer, though this transfer can involve any number of points.

         3. No person can be involved in both transfers in which they lose and gain points - only one or the other (or neither).

         4. After all the transfers are completed, no student can have a negative amount of points.

      There are $N$ ($1 \leq N \leq 5000$) students in this course, each with a unique student number from $1$ to $N$, inclusive. Student $i$ starts off with $P_i$ ($1 \leq P_i \leq 10^6$) points. The Codefather’s future son-in-law is student $1$.

      Though the Codefather is a powerful man, he’s still wary of the authorities, and wants to remain as inconspicuous as possible. Therefore, he wants to minimize the number of points in the largest transfer he makes, while still insuring that his future son-in-law will get 100%.

      Input

      Line $1$: 1 integer, $N$

      Next $N$ lines: 1 integer, $P_i$, for $i=1..N$

      Output

      If it’s possible for the Codefather to observe the rules and give his future son-in-law more points than anyone else, minimize the number of points in the largest transfer he must make and output this value.

      Otherwise, output “impossible”.

      Example

      Input:
      4
      500
      300
      900
      100
      
      Output:
      202
      Explanation of Sample:

      The future son-in-law only has 500 points, so the Codefather must make student 3 lose at least 401. However, the other students must also stay strictly below 500. His best strategy is to transfer 199 points from student 3 to student 2, and 202 points from student 3 to student 4. This will result in the following point distribution:

      Student 1: 500

      Student 2: 499

      Student 3: 499

      Student 4: 302


      Added by:Jacob Plachta
      Date:2013-05-06
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14831. Your Rank is Pure

      Problem code: GCJPURE


      Problem

       

      Pontius: You know, I like this number 127, I don't know why.
      Woland: Well, that is an object so pure. You know the prime numbers.
      Pontius: Surely I do. Those are the objects possessed by our ancient masters hundreds of years ago. Oh, yes, why then? 127 is indeed a prime number as I was told.
      Woland: Not... only... that. 127 is the 31st prime number; then, 31 is itself a prime, it is the 11th; and 11 is the 5th; 5 is the 3rd; 3, you know, is the second; and finally 2 is the 1st.
      Pontius: Heh, that is indeed... purely prime.

      The game can be played on any subset S of positive integers. A number in S is considered pure with respect to S if, starting from it, you can continue taking its rank in S, and get a number that is also in S, until in finite steps you hit the number 1, which is not in S.

      When n is given, in how many ways you can pick S, a subset of {2, 3, ..., n}, so that n is pure, with respect to S? The answer might be a big number, you need to output it modulo 100003.

      Input

      The first line of the input gives the number of test cases, T. T lines follow. Each contains a single integer n.

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the answer as described above.

      Limits

      T ≤ 200.

      2 ≤ n ≤ 500.

      Sample

      Input:

      2

      5

      6

      Output:

      Case #1: 5
      Case #2: 8

       

       

      (All problem statements, input data and contest analyses from google code jam are licensed under the Creative Commons Attribution License.)

       


      Added by:Shafaet
      Date:2013-05-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Google Code Jam Round 1B 2010, Problem C









      SPOJ Problem Set (classical)

      14833. The Fox and the Wolf

      Problem code: FOXWOLF

      In a certain peaceful forest, there live a Fox and a Wolf. Due to common misconception, one might suppose that the Wolf would want to hunt the Fox – however, both are in fact nice animals, and get along just fine. Indeed, they have such nice manners that, if they ever meet up, they will have a nice little chat for $C$ minutes ($1 \leq C \leq 9$).

      The forest that the Fox and the Wolf live in can be regarded as a rectangle, $N$ km long along its East side and $M$ km wide along its North side ($1 \leq N,M \leq 20$). It is divided into a grid of squares, each with a side length of 1 km. Each such square either contains a meadow (represented by a ‘.’), is full of burrs (‘B’), is blocked by trees (‘T’), contains the Fox’s den (‘F’), contains the Wolf’s lair (‘W’), currently contains the Fox (‘f’), or currently contains the Wolf (‘w’).

      At the end of a long day at work (consisting of solving complex computer science problems in their heads), both animals wish to get to their respective homes as soon as possible. Every minute, each of them can walk one km directly North, East, South, or West, or just stay put – however, they cannot enter squares blocked by trees, nor can they enter each other’s homes (that wouldn’t be very polite). They also don’t want to leave the forest, seeing as humans jealous of their supreme intellect are constantly lurking just outside.

      Every time the Fox or the Wolf goes from a square full of burrs to a meadow, he must stand still and spend $B$ minutes ($1 \leq B \leq 9$) picking burrs off of himself. As mentioned above, they must also stop and chat if they meet up. Though each square is quite big, the animals always walk to its exact centre before moving on. This means that they will meet up if they either occupy the same square at the same time, or if they pass each other while walking between squares (which would happen if they switched positions in the space of a minute). Once the animals have chatted once, they never have to chat again, having already satisfied the demands of etiquette. Both animals are great multitaskers, and can pick burrs while chatting with each other.

      Each animal wants to get home as soon as possible, but is also considerate of the other – as such, they will collaborate so as to minimize the time for both of them to get home. Due to their extreme intelligence, both animals will calculate this minimum time in their heads instantly – however you, the observer, will probably need to write a program to figure it out...

      Input

      Line $1$: 4 integers, $N$, $M$, $C$, and $B$

      Next $N$ lines: $M$ characters each, representing a row of the forest as described above

      Output

      A single integer – the minimum time for both the Fox and the Wolf to get to their respective homes, in minutes. If this is impossible, output -1 instead.

      Example

      Input:
      5 6 5 1
      ......
      BWTTTB
      B.TB..
      BBT..T
      .FTfw.
      Output:
      17
      Explanation of Sample:

      The Wolf should wait for the first three minutes, letting the Fox go first. From then on, the Fox can continue along its only possible route home. The Wolf will be 2 squares behind the Fox most of the time, except for when it enters the burr-filled square, when it will temporarily be 1 behind. With this strategy, the Wolf will take 14 minutes to get home, while the Fox will take 17, and since we only care about the larger, the total time is 17 minutes.


      Added by:Jacob Plachta
      Date:2013-05-07
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14834. Foxlings

      Problem code: FOXLINGS


      It’s Christmas time in the forest, and both the Fox and the Wolf families are celebrating. The rather large Fox family consists of two parents as well as $N$ ($1 \leq N \leq 10^9$) little Foxlings. The parents have decided to give their children a special treat this year – crackers! After all, it’s a well-known fact that Foxen love crackers.

      With such a big family, the parents can’t afford that many crackers. As such, they wish to minimize how many they give out, but still insure that each Foxling gets at least a bit. The parents can only give out entire crackers, which can then be divided and passed around.

      With this many children, not all of them know one another all that well. The Foxlings have names, of course, but their parents are computer scientists, so they have also conveniently numbered them from $1$ to $N$. There are $M$ ($1 \leq M \leq 10^5$) unique two-way friendships among the Foxlings, where relationship $i$ is described by the distinct integers $A_i$ and $B_i$ ($1 \leq A_i,B_i \leq N$), indicating that Foxling $A_i$ is friends with Foxling $B_i$, and vice versa. When a Foxling is given a cracker, he can use his tail to precisely split it into as many pieces as he wants (the tails of Foxen have many fascinating uses). He can then pass these pieces around to his friends, who can repeat this process themselves.

      Input

      Line $1$: 2 integers, $N$ and $M$

      Next $M$ lines: 2 integers, $A_i$ and $B_i$, for $i=1..M$

      Output

      A single integer – the minimum number crackers must be given out, such that each Foxling ends up with at least a small part of a cracker.

      Example

      Input:
      9 5
      3 1
      6 1
      7 6
      2 7
      8 9
      Output:
      4
      Explanation of Sample:

      The parents can give one cracker to Foxling 6, who will then split it into three and give pieces to his friends (Foxlings 1 and 7). Foxling 7 can then give half of his piece to his other friend, Foxling 2.

      They can give another cracker to Foxling 8, who will split it with Foxling 9.

      This leaves Foxlings 4 and 5, who have no friends (don’t worry, Foxen have long since outgrown the need for friends), and who must be given one cracker each. This brings the total up to 4 crackers.

       


      Added by:Jacob Plachta
      Date:2013-05-07
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14839. Boxdropper

      Problem code: BOXD

      The University of Waterloo is famous for its booming population of geese, and many researchers go there to study them. One day, Doctor Y (known for his work in the field of boxology) decided to go there and investigate how good geese are at optimization problems.

      At UW, there is a large lake (so large, in fact, that the boundaries are never an issue). Doctor Y decides to drop a number of 2D boxen onto this lake and command the geese to travel from one to another, recording how much time they spend flying as opposed to walking (naturally, the geese won’t swim, considering the not-so-appealing brown colour of the lake). He has a Boxdropper machine at his disposal to do the work for him – he can give it the following commands:

      B $x_1$ $y_1$ $x_2$ $y_2$: Drop a box onto the lake such that its lower-left coordinate is at ($x_1$, $y_1$) and its upper-right coordinate is at ($x_2$, $y_2$). Doctor Y defines the origin to be somewhere in the middle of the lake. Note that boxen can overlap with one another.

      G $a$ $b$: Command the geese to travel from the ath box dropped to the bth one, and record the total distance that they fly.

      Since the scientific community has not yet realized the benefits of studying boxen, Doctor Y isn’t receiving much funding – as such, he only has $500$ boxen at his disposal, and his machine can only handle $10^6$ commands before it overheats.

      The geese can walk across boxen freely, but sometimes they may have to fly over water to reach other boxen. The geese, secretly participating in the second stage of the Canadian Computing Competition every year, are well versed in optimization problems such as these, and so will always choose a path that will minimize the total distance that they spend flying. Given the commands that Doctor Y inputs into the Boxdropper, determine the distances recorded by it (one for every G command).

      Input

      On each line, one of the 2 types of commands will be given:

      If the line starts with the character B, it will be followed by 4 integers ($x_1$, $y_1$, $x_2$, and $y_2$), each with absolute value no greater than $10^6$.

      If the line starts with the character G, it will be followed by 2 integers ($a$ and $b$), with $a \neq b$ and $1 \leq a,b \leq n$ (where $n$ is the number of B commands inputted so far).

      Commands should be read until EOF.

      Output

      For every G command, output the distance that the geese spend flying. The numbers should be printed one per line, and rounded off to 2 decimal places.

      Example

      Input:
      B -1 2 1 5
      B 3 -4 4 1
      G 2 1
      B 4 -3 6 -2
      B 6 -6 8 -4
      G 2 3
      G 1 4
      Output:
      2.24
      0.00
      3.24
      Explanation of Sample:

      The lake looks like this:

      For the first G command, the geese must fly along the red line, which has a length of √5.

      For the second, the two boxen are touching, so no flight is necessary.

      For the third, the geese must first fly along the red line, then walk across boxen 2 and 3, and finally fly along the blue line, which has a length of 1.

       


      Added by:Jacob Plachta
      Date:2013-05-07
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14844. All Your Base

      Problem code: GCJ1C09A

      Problem

      In A.D. 2100, aliens came to Earth. They wrote a message in a cryptic language, and next to it they wrote a series of symbols. We've come to the conclusion that the symbols indicate a number: the number of seconds before war begins!

      Unfortunately we have no idea what each symbol means. We've decided that each symbol indicates one digit, but we aren't sure what each digit means or what base the aliens are using. For example, if they wrote "ab2ac999", they could have meant "31536000" in base 10 -- exactly one year -- or they could have meant "12314555" in base 6 -- 398951 seconds, or about four and a half days. We are sure of three things: the number is positive; like us, the aliens will never start a number with a zero; and they aren't using unary (base 1).

      Your job is to determine the minimum possible number of seconds before war begins.

      Input

      The first line of input contains a single integer, T. T test cases follow. Each test case is a string on a line by itself. The line will contain only characters in the 'a' to 'z' and '0' to '9' ranges (with no spaces and no punctuation), representing the message the aliens left us. The test cases are independent, and can be in different bases with the symbols meaning different things.

      Output

      For each test case, output a line in the following format:

      Case #X: V

      Where X is the case number (starting from 1) and V is the minimum number of seconds before war begins.

      Limits

      1 ≤ T ≤ 100
      The answer will never exceed 1018

      1 ≤ the length of each line < 61

      Sample


      Input
       

      Output
       
      3
      11001001
      cats
      zig
      Case #1: 201
      Case #2: 75
      Case #3: 11

      Added by:Shafaet
      Date:2013-05-07
      Time limit:20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Google Codejam 2009, Round 1C, Problem A









      SPOJ Problem Set (classical)

      14845. Center of Mass

      Problem code: GCJ1C09B

      Problem

      You are studying a swarm of N fireflies. Each firefly is moving in a straight line at a constant speed. You are standing at the center of the universe, at position (0, 0, 0). Each firefly has the same mass, and you want to know how close the center of the swarm will get to your location (the origin).

      You know the position and velocity of each firefly at t = 0, and are only interested in t ≥ 0. The fireflies have constant velocity, and may pass freely through all of space, including each other and you. Let M(t) be the location of the center of mass of the N fireflies at time t. Let d(t) be the distance between your position and M(t) at time t. Find the minimum value of d(t), dmin, and the earliest time when d(t) = dmin, tmin.

      Input

      The first line of input contains a single integer T, the number of test cases. Each test case starts with a line that contains an integer N, the number of fireflies, followed by N lines of the form

      x y z vx vy vz

      Each of these lines describes one firefly: (x, y, z) is its initial position at time t = 0, and (vx, vy, vz) is its velocity.

      Output

      For each test case, output

      Case #X: dmin tmin

      where X is the test case number, starting from 1. Any answer with absolute or relative error of at most 10-6 will be accepted.

      Limits

      All the numbers in the input will be integers.
      1 ≤ T ≤ 100
      The values of x, y, z, vx, vy and vz will be between -5000 and 5000, inclusive.

      Large dataset

      3 ≤ N ≤ 500

       

      Sample


      Input
       

      Output
       
      3
      3
      3 0 -4 0 0 3
      -3 -2 -1 3 0 0
      -3 -1 2 0 3 0
      3
      -5 0 0 1 0 0
      -7 0 0 1 0 0
      -6 3 0 1 0 0
      4
      1 2 3 1 2 3
      3 2 1 3 2 1
      1 0 0 0 0 -1
      0 10 0 0 -10 -1

      Case #1: 0.00000000 1.00000000
      Case #2: 1.00000000 6.00000000
      Case #3: 3.36340601 1.00000000

      Notes

      Given N points (xi, yi, zi), their center of the mass is the point (xc, yc, zc), where:

      xc = (x1 + x2 + ... + xN) / N
      yc = (y1 + y2 + ... + yN) / N
      zc = (z1 + z2 + ... + zN) / N
      

      Added by:Shafaet
      Date:2013-05-07
      Time limit:1s-20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Google Codejam 2009, Round 1C, Problem B









      SPOJ Problem Set (classical)

      14846. Bribe the Prisoners

      Problem code: GCJ1C09C


       

      Problem

      In a kingdom there are prison cells (numbered 1 to P) built to form a straight line segment. Cells number i and i+1 are adjacent, and prisoners in adjacent cells are called "neighbours." A wall with a window separates adjacent cells, and neighbours can communicate through that window.

      All prisoners live in peace until a prisoner is released. When that happens, the released prisoner's neighbours find out, and each communicates this to his other neighbour. That prisoner passes it on to his other neighbour, and so on until they reach a prisoner with no other neighbour (because he is in cell 1, or in cell P, or the other adjacent cell is empty). A prisoner who discovers that another prisoner has been released will angrily break everything in his cell, unless he is bribed with a gold coin. So, after releasing a prisoner in cell A, all prisoners housed on either side of cell A - until cell 1, cell P or an empty cell - need to be bribed.

      Assume that each prison cell is initially occupied by exactly one prisoner, and that only one prisoner can be released per day. Given the list of Q prisoners to be released in Q days, find the minimum total number of gold coins needed as bribes if the prisoners may be released in any order.

      Note that each bribe only has an effect for one day. If a prisoner who was bribed yesterday hears about another released prisoner today, then he needs to be bribed again.

      Input

      The first line of input gives the number of cases, N. N test cases follow. Each case consists of 2 lines. The first line is formatted as

      P Q

      where P is the number of prison cells and Q is the number of prisoners to be released.
      This will be followed by a line with Q distinct cell numbers (of the prisoners to be released), space separated, sorted in ascending order.

      Output

      For each test case, output one line in the format

      Case #X: C
      where X is the case number, starting from 1, and C is the minimum number of gold coins needed as bribes.

      Limits

      1 ≤ N ≤ 100
      QP
      Each cell number is between 1 and P, inclusive.

      Large dataset

      1 ≤ P ≤ 10000
      1 ≤ Q ≤ 100

      Sample


      Input
       

      Output
       
      2
      8 1
      3
      20 3
      3 6 14
      Case #1: 7
      Case #2: 35

      Note

      In the second sample case, you first release the person in cell 14, then cell 6, then cell 3. The number of gold coins needed is 19 + 12 + 4 = 35. If you instead release the person in cell 6 first, the cost will be 19 + 4 + 13 = 36.


      Added by:Shafaet
      Date:2013-05-07
      Time limit:20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Google Codejam 2009, Round 1C, Problem C









      SPOJ Problem Set (classical)

      14848. Boxlings

      Problem code: BOXLINGS

      Doctor Y, always eager to further his research in the field of boxology, is observing a family of boxen in their natural habitat – a barrel of wine. He has noticed that in addition to the $N$ ($1 \leq N \leq 200,000$) rectangular, two-dimensional boxen, there are $M$ ($1 \leq M \leq 200,000$) almost imperceptible points floating on the surface of the wine. He reasons that these must be baby boxen – also known as boxlings.

      Curious as to the customs of box families, Doctor Y wishes to count how many boxlings are floating on top of boxen. From his top-down view of the barrel, he has divided the surface of the wine into a two-dimensional Cartesian plane, and noted the positions of all the boxen and boxlings. Each box occupies a rectangular region parallel to the axes of the plane, with two of its opposite corners at coordinates ($x_1$, $y_1$) and ($x_2$, $y_2$). Doctor Y has observed that boxen sometimes overlap with one another. On the other hand, each boxling is so small that it occupies only a single point on the plane, with x-coordinate $a$ and y-coordinate $b$. All coordinates have absolute values no larger than $10^9$.

      Having recorded the locations of all of the life forms on the surface of the wine, Doctor Y is interested in counting exactly how many boxlings are floating on top of at least one box. Note that if a boxling is on the very edge or corner of a box, it counts as being on top. Also note that two boxlings can occupy the exact same locations, in which case they should still be counted separately. It's also possible for a box to have zero area, in which case it's treated as a line (or point) and can still have boxlings on top of it.

      With so many boxen and boxlings living in this wine barrel, Doctor Y doesn’t feel like sitting there and counting them all by hand, crazy though he is. As such, he wants you to write a program to, given the locations of all the boxen and boxlings, count the number of boxlings that are floating on top of at least one box. Don’t worry - your hard work will surely lead to exciting discoveries in the field of boxology. 

      Input

      Line $1$: 2 integers, $N$ and $M$

      Next $N$ lines: 4 integers, $x_1$, $y_1$, $x_2$, and $y_2$, the coordinates of each box

      Next $M$ lines: 2 integers, $a$ and $b$, the coordinates of each boxling

      Output

      A single integer – the number of boxlings that are on top of at least one box.

      Example

      Input:
      5 10
      -1 -1 2 5
      4 -3 5 3
      1 2 4 4
      5 -6 8 -4
      1 -2 8 0
      1 4
      5 4
      2 2
      3 1
      6 -5
      5 -1
      3 -3
      -1 -2
      -1 -1
      2 -1
      Output:
      6
      Explanation of Sample:

      Below is a top-down view of the surface of the wine:

      The coloured-in rectangles are the boxen, the red dots are boxlings that are on top of at least one box, and the blue dots are the other boxlings. Counting the red dots, it can be seen that there are six of them.

       


      Added by:Jacob Plachta
      Date:2013-05-07
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14856. Crazy Shopkeeper

      Problem code: CRAZYSK

      Zoglu Bepari is a peculiar shopkeeper of Chittagong. He is a very famous shopkeeper. Everyone loves him and gave him  a nick name ‘MAMU’. He has a beautiful small shop which is also known as “MAMUR DOKAN”. From morning to late night, he sells non-stop. His shop always remains over-crowded as he gives some weird and crazy offers almost every day. Most of the offers favor Customers. He recently created a special offer for his customers. For each item he sells, he gives a special card. These cards are rare and only available in his shop. And no one can cheat with him showing fake cards as he is really good at checking cards. Suppose, a Customer bought X items, he gives a positive number N along with X cards to the customer. Another important thing is Customers can return N cards for collecting another item of same type and a card in exchange.

      Now as a programmer, you just have to calculate the total number of items a customer can get after using maximum number of cards he gets.

       

      Input

      input starts with an positive integer T<100 followed by T lines. Each of these lines contain two positive integers, Number of item (X) bought in the first deal 1<X<=2^64, and number(N) that is given by Mamu 1<N<=X

      Output

      Print the total number of items the customer will have after exchanging maximum no of cards for getting extra items.

      Example 

      Input:

      5

      15 3

      2147483647 2

      34 3

      231 2

      5 2 

      Output:

      22

      4294967293

      50

      461

      9


      Added by:ওয়াসী (Wasi)
      Date:2013-05-07
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All except: SCALA SCM guile SCM qobi SED ST TCL WSPC
      Resource:own problem









      SPOJ Problem Set (classical)

      14858. digit count

      Problem code: DIGCNT


      Given two integers a and b, we write the numbers between a and b, inclusive,
      in a list. Your task is to calculate the number of occurrences of each digit except zero
      For example, if a = 1024 and b = 1032, the list will be 
      1024 1025 1026 1027 1028 1029 1030 1031 1032
      there are ten 1s, seven 2s, three 3s, and etc..
      Given two integers a and b, we write the numbers between a and b, inclusive, in a list. Your task is to calculate the number of occurrences of each digit except zero For example, if a = 1024 and b = 1032, the list will be 1024 1025 1026 1027 1028 1029 1030 1031 1032 there are ten 1s, seven 2s, three 3s, and etc.....
      
                                                                                               Input
      The input consists of up to 500 lines. Each line contains two numbers a and b
      where 1 <= a, b <= 10^16. The input is terminated by a line 0 0.  
      
                                                                                             Output
      For each pair of input, output a line containing ten numbers separated
      by single spaces. The first number is the number of occurrences of the digit 1,
      the second is the number of occurrences of the digit 2, etc..
      
                                                                                            Example
      
      input
      1 10
      0 0 
      
      output
      2 1 1 1 1 1 1 1 1 
      
       Input
      The input consists of up to 500 lines. Each line contains two numbers a and b
      2 1 1 1 1 1 1 1

      Added by:abdou 00
      Date:2013-05-08
      Time limit:1s
      Source limit:290B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:another version of http://www.spoj.com/problems/MDIGITS/









      SPOJ Problem Set (classical)

      14862. Union Laser

      Problem code: ULASER

      Doctor Y, a leading expert in the field of boxology, is investigating the properties of boxen with his expensive super-precision laser. In particular, he plans to position the laser inside the union of a bunch of boxen, and see where the beam collides with itself.

      Since Doctor Y blew all his cash on the laser, he can’t actually afford to purchase boxen to conduct his experiment – instead, he will simulate it on his old computer, which uses an integer grid system. He will give his computer an integer $N$, the number of boxen ($1 \leq N \leq 10,000$), as well as their descriptions. Each box is described by 4 integers, $x_1$, $y_1$, $x_2$, and $y_2$, and is an axis-aligned rectangle with coordinates ($x_1$, $y_1$) and ($x_2$, $y_2$) describing a pair of its opposite corners. Boxen may overlap with one another. He will also input the location of the laser ($A$, $B$), such that it will be positioned strictly within at least one of the boxen. The laser points down and right at a 45° angle. All coordinates have absolute values of at most $3000$.

      As it turns out, boxen are made of a perfectly reflective material (a fact which Doctor Y will discover upon completion of his experiment) – as such, whenever the laser beam hits the edge of the union of the boxen, it bounces off. For example, if it hits a vertical edge from the left, it bounces to the right, with the up-down direction preserved. If it hits a corner head-on, it will reverse direction, hence colliding with itself right at the corner. Normally, light travels quite fast, but due to the mysterious properties of boxen, the speed of light when inside a box union is only √2 units/second.

      Doctor Y plans to use his computer to simulate the path of the laser and see when and where it first collides with itself, but there’s one problem – he doesn't know how to program! Offering non-cafeteria food, he lures a desperate Waterloo student into his lab, where he forces him (or her?) to write the laser simulation program. That’s you.

      Input

      Line $1$: 1 integer, $N$

      Line $2$: 2 integers, $A$ and $B$

      Next $N$ lines: 4 integers, $x_1$, $y_1$, $x_2$, and $y_2$, describing the coordinates of each box

      Output

      If the laser beam never collides with itself or the laser, simply output “Time limit exceeded”.

      If the laser beam collides with the actual laser (at coordinates ($A$, $B$)) before it collides with another location through which the beam has already passed, the first line of output should consist of a single number – the amount of time that passes before laser beam collides with the laser, in seconds. The second line should read “Broken equipment”.

      Otherwise, the first line of output should consist of a single number – the amount of time that passes before laser beam first collides with itself, in seconds. The second line should contain a pair of numbers – the x and y coordinates of where this takes place.

      Each number should be rounded off to 1 decimal place.

      Example

      Input:
      7
      0 4
      -1 5 1 -1
      0 -2 4 2
      0 -4 1 2
      2 -4 5 -1
      5 2 7 4
      3 -5 4 -4
      0 -6 3 -4
      Output:
      12.0
      0.0 0.0
      Explanation of Sample:

      The grid looks like this:

      The filled-in squares represent squares that are part of at least one box – together, they make up the box union. Note that the union can have holes in it, and that it can be disjoint.

      The blue lines denote the boundaries of the union – these are the lines that the laser can bounce off of.

      The yellow lines are edges of boxen that do not contribute to the union – the laser can go through these freely.

      The red diamond is the position of the laser, and the red line is the path that the laser beam follows. Note that when it bounces off the corner at (2,-2), since it didn’t hit it head-on, it is the same as bouncing off of a horizontal edge.

      Following the path of the laser beam, it can be seen that it collides with itself at (0,0). Before this, it has travelled 12√2 units, which takes exactly 12 seconds.

      More Examples:

      If the laser were positioned at (0,3), the output should be:

      12.0
      0.0 -1.0

       If the laser were positioned at (0,1), the output should be:

      5.0
      5.0 -4.0

       If the laser were positioned at (0,0), the output should be:

      8.0
      Broken equipment

      Added by:Jacob Plachta
      Date:2013-05-08
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14864. Sales

      Problem code: SALES


      Bosco has gotten his hands on $B$ ($1 \leq B \leq 50$) dollars! Being a Magic the Gathering™ enthusiast, he wishes to spend some amount of his budget on cards to improve his deck.

      He has located a local store that has $N$ ($1 \leq N \leq 30,000$) cards for sale. Card $i$ costs $c_i$ ($1 \leq c_i \leq 50$) dollars, and will improve Bosco’s DQI (Deck Quality Index) by $v_i$ ($1 \leq v_i \leq 1000$) points. Only one copy of each card is for sale.

      Business hasn’t been too great lately, so the store is offering sales on various days. Though the term “price adjustments” would be more accurate, as card prices can increase, “sales” are much more appealing – and, indeed, Bosco wants to go do all of his shopping on one of the $D$ ($1 \leq D \leq 3000$) days of the sales. In fact, he’s already acquired a list of the price adjustments that will be made.

      On day $i$, the cost of card $a_i$ ($1 \leq a_i \leq N$) is changed to $b_i$ ($1 \leq b_i \leq 50$), while all other cards remain unchanged. That is, before day $1$, all cards have their initial costs ($c_{1..N}$), and from then on, price adjustments accumulate from day to day.

      Additionally, on each day, only certain cards from the store’s inventory are actually up for sale. In particular, on day $i$, only cards $x_i$ to $y_i$ ($1 \leq x_i \leq y_i \leq N$), inclusive, may be purchased.

      Bosco doesn’t care how much of his budget he spends, but he absolutely must have the best possible deck. As such, for each of the $D$ days, he wants to consider buying some (possibly empty) set of cards, such that the sum of their costs is no larger than $B$, and the sum of their DQI points is maximal. Determine this DQI sum for each day, so that Bosco will know when to go to take full advantage of the “sales”.

      Input

      Line $1$: 3 integers, $B$, $N$, and $D$

      Next $N$ lines: 2 integers, $c_i$ and $v_i$, for $i=1..N$

      Next $D$ lines: 4 integers, $a_i$, $b_i$, $x_i$, and $y_i$, for $i=1..D$

      Output

      For each day, output the maximal DQI sum of cards up for purchase that day which Bosco can purchase without going over his budget, considering all price changes that have occurred so far.

      Example

      Input:

      5 5 3
      9 6
      1 5
      2 3
      3 11
      2 7
      1 1 1 4
      4 6 3 5
      4 1 1 4

      Output:

      22
      10
      25

      Explanation of Sample:

      At first, the 5 cards (with point values 6, 5, 3, 11, and 7, respectively) have costs of 9, 1, 2, 3, and 2 dollars, in that order.

      On the first day, the cost of the first card is reduced to 1 dollar, and the first 4 cards are up for purchase.

      On the second day, the cost of the fourth card is increased to 6 dollars, and only the last 3 cards can be bought.

      On the final day, the cost of card 4 is changed again, this time to 1 dollar, and the first 4 cards are once again considered.

       

      On the first day, Bosco should buy the first, second, and fourth cards, costing a total of 5 dollars.

      On the second, cards 3 and 5 should be purchased with 4 dollars, as card 4 is now too expensive.

      On the final day, all of the cards up for sale can be bought for 5 dollars. Notice that card 1 still costs 1 dollar, from the first price change.

       


      Added by:Jacob Plachta
      Date:2013-05-08
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14871. STUDENTS

      Problem code: AU7_5


       

      Problem Statement

      Professor X wants to position N (1 <= N <= 100,000) girls and boys in a single row to present at the annual fair.

      Professor has observed that the boys have been quite pugnacious lately; if two boys too close together in the line, they will argue and begin to fight, ruining the presentation. Ever resourceful, Professor calculated that any two boys must have at least K (0 <= K < N) girls between them in order to avoid a fight.

      Professor would like you to help him by counting the number of possible sequences of N boys and girls that avoid any fighting. Professor considers all boys to be the same and all girls to be the same; thus, two sequences are only different if they have different kinds of students in some position.

      Input

      First line contains C (1<=C<=20) the number of test cases

      Next C lines contain N and K

      Output

      A single integer representing the number of ways Professor could create such a sequence of students. Since this number can be quite large, output the result modulo 5000011.

      Sample Input

      1

      4 2

      Sample Output

      6

      Explanation

      GGGG

      BGGG

      GBGG

      GGBG

      GGGB

      BGGB

      Time Limit

      1s

       


      Added by:arun
      Date:2013-05-08
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      14883. Box Factory

      Problem code: GCJ121CC


      You own a factory with two assembly lines. The first assembly line makes boxes, and the second assembly line makes toys to put in those boxes. Each type of box goes with one type of toy and vice-versa. 

      At the beginning, you pick up a box from the first assembly line and a toy from the second assembly line. You then have a few options.

      # You can always throw out the box and pick up the next one. 
      # You can always throw out the toy and pick up the next one. 
      # If the box and toy are the same type, you can put the toy in the box, and send it out to customers.

      You always pick boxes up in the order in which they are made, and similarly for toys. You know the order in which boxes and toys are made, and you want to plan out a strategy that will allow you to send as many boxed toys as possible to customers.


       Warning: The two assembly lines make a lot of boxes and toys. However, they tend to make one kind of thing for a long period of time before switching.

      Input

      The first line of the input gives the number of test cases, T. T test cases follow.

      Each test case begins with a line contains two integers N and M. It is followed by a line containing 2 * N integers a1, A1, a2, A2, ..., aN, AN, and another line containing 2 * M integers b1, B1, b2, B2, ..., bM, BM.

      This means that the first assembly line will make a1 boxes of type A1, then a2 boxes of type A2, etc., until it finishes with aN boxes of type AN. Similarly, the second assembly will make b1 toys of type B1, followed by b2 toys of type B2, etc., until it finishes with bM toys of type BM.

       A toy can be matched with a box if and only if they have the same type number.

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is the largest number of boxed toys that you can send out to customers.

      Limits

      1 ≤ T ≤ 100.
      1 ≤ ai, bi ≤ 1016.
      1 ≤ Ai, Bi ≤ 100.

      1 ≤ N, M ≤ 100.

      Example

      Input:
      4
      3 3
      10 1 20 2 25 3
      10 2 30 3 20 1
      3 5
      10 1 6 2 10 1
      5 1 3 2 10 1 3 2 5 1
      3 5
      10 1 6 2 10 1
      5 1 6 2 10 1 6 2 5 1
      1 1
      5000000 10
      5000000 100

      Output:

      Case #1: 35
      Case #2: 20
      Case #3: 21
      Case #4: 0

      Added by:Bidhan Roy ( বিধান )
      Date:2013-05-09
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Google Codejam 2012 Round 1C









      SPOJ Problem Set (classical)

      14886. Matts Trip

      Problem code: MATT


      Matt finds himself in a desert with $N$ ($2 \leq N \leq 10$) oases, each of which may have food, water, and/or a palm tree. If oasis $i$ has food, then $F_i=1$ - otherwise, $F_i=0$. Similarly, $W_i=1$ if and only if oasis $i$ has water, and $P_i=1$ if and only if it has a palm tree. These 3 values are completely independent of one another.

       

      Some pairs of these oases are connected by desert paths, which each take 1 hour to traverse. There are $M$ ($0 \leq M \leq 45$) such paths, with path $i$ connecting distinct oases $A_i$ and $B_i$ in both directions ($1 \leq A_i,B_i \leq N$). No pair of oases is directly connected by more than one path, and it's not guaranteed that all oases are connected by some system of paths.

       

      Matt starts at an oasis $S$, and wants to end up at a different oasis $E$ ($1 \leq S,E \leq N$).

      Both of these oases are quite nice - it's guaranteed that $F_S=W_S=P_S=F_E=W_E=P_E=1$.

      Since he's in a hurry to get out of the desert, he wants to travel there in at most $H$ ($1 \leq H \leq 10^9$) hours.

      However, he can only survive for up to $MF$ hours at a time without food, and up to $MW$ hours at a time without water ($1 \leq MF,MW \leq 4$). For example, if $MF=1$ and $MW=2$, then every single oasis he visits along the way must have food (as he would otherwise spend more than 1 hour without it), and he cannot visit 2 or more oases without water in a row.

       

      Since Matt is a computer scientist, before actually going anywhere, he's interested in the number of different paths he can take that will get him from oasis $S$ to oasis $E$ alive in at most $H$ hours.

      Note that there may be no such paths.

      Being a computer scientist, he of course only cares about this number modulo ($10^9+7$).

      Input

      Line $1$: 7 integers, $N$, $M$, $H$, $S$, $E$, $MF$, and $MW$

       

      Next $N$ lines: 3 integers, $F_i$, $W_i$, and $P_i$, for $i = 1..N$

       

      Next $M$ lines: 2 integers, $A_i$ and $B_i$, for $i = 1..M$

      Output

      1 integer, the number of different valid paths, modulo ($10^9+7$)

      Example 1

      Input:

      3 3 3 1 2 1 4

      1 1 1

      1 1 1

      0 1 0

      1 2

      2 3

      1 3

      Output:
      2
      Explanation:

      The two possible paths, described in terms of oases visited, are $1 \rightarrow 2$ and $1 \rightarrow 2 \rightarrow 1 \rightarrow 2$. Matt can never go to oasis 3, as it doesn't contain food, which he can't survive without for more than 1 hour. The path $1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 1 \rightarrow 2$ is not valid, as it would take 5 hours rather than at most 3.

      Note that oasis 3 is the only oasis without a palm tree.

      Example 2

      Input:

      5 5 3 3 2 3 2

      1 0 0

      1 1 1

      1 1 1

      0 0 1

      0 1 0

      1 2

      1 3

      1 4

      3 4

      4 2

      Output:
      2
      Explanation:

      The two possible paths are $3 \rightarrow 1 \rightarrow 2$ and $3 \rightarrow 4 \rightarrow 2$.

      This time, oases 1 and 5 are lacking in palm trees.


      Added by:Jacob Plachta
      Date:2013-05-09
      Time limit:8s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14887. Good Travels

      Problem code: GOODA


      \smallskip
      The Team is interested in a network of $N$ ($2 \leq N \leq 10^6$) cities (conveniently numbered $1..N$), interconnected by $M$ ($1 \leq M \leq 10^6$) one-way flights (similarly numbered $1..M$). Their hometown is city $S$ ($1 \leq S \leq N$), and the contest will take place in city $E$ ($1 \leq E \leq N$, $S \neq E$). Flight $i$ goes from city $a_i$ ($1 \leq a_i \leq N$) to city $b_i$ ($1 \leq b_i \leq N$, $a_i \neq b_i$), and no two flights connect the same pair of cities in the same direction. In general, no cities are guaranteed to be reachable from other cities by a sequence of flights. However, The Team of course knows that city $E$ is reachable from city $S$ - they're not about to break their streak of triumphant wins!
      \smallskip
      Now, each city $i$ has a fun value, $f_i$ ($0 \leq f_i \leq 10^6$), associated with it. Along their trip, The Team will take time to have fun at every city they visit, including the first and last. However, though they can visit a city multiple times (including cities $S$ and $E$), or even take a certain flight multiple times, surely this gets boring quickly - therefore, any city's fun can only be had up to once.
      \smallskip
      The Team wants to determine the maximal amount of fun they can have on any sequence of flights that starts at city $S$ and ends at city $E$. Naturally, every member on The Team is so intelligent that they've calculated this value in their heads (and are quite excited about it) - but can you?

      It's that time of year again - the best ACM-ICPC team of all time is off to the World Finals! Being the best, they realize that a good performance starts before the contest itself - in order to get into the perfect mindset, they must have as much fun on the trip to the contest site as possible!

      The Team is interested in a network of $N$ ($2 \leq N \leq 10^6$) cities (conveniently numbered $1..N$), interconnected by $M$ ($1 \leq M \leq 10^6$) one-way flights (similarly numbered $1..M$). Their hometown is city $S$ ($1 \leq S \leq N$), and the contest will take place in city $E$ ($1 \leq E \leq N$, $S \neq E$). Flight $i$ goes from city $a_i$ ($1 \leq a_i \leq N$) to city $b_i$ ($1 \leq b_i \leq N$, $a_i \neq b_i$), and no two flights connect the same pair of cities in the same direction. In general, no cities are guaranteed to be reachable from other cities by a sequence of flights. However, The Team of course knows that city $E$ is reachable from city $S$ - they're not about to break their streak of triumphant wins!

      Now, each city $i$ has a fun value, $f_i$ ($0 \leq f_i \leq 10^6$), associated with it. Along their trip, The Team will take time to have fun at every city they visit, including the first and last. However, though they can visit a city multiple times (including cities $S$ and $E$), or even take a certain flight multiple times, surely this gets boring quickly - therefore, any city's fun can only be had up to once.

      The Team wants to determine the maximal amount of fun they can have on any sequence of flights that starts at city $S$ and ends at city $E$. Naturally, every member on The Team is so intelligent that they've calculated this value in their heads (and are quite excited about it) - but can you?

      Input

      First line: 4 integers, $N$, $M$, $S$, and $E$

      Next $N$ lines: 1 integer, $f_i$, for $i = 1..N$

      Next $M$ lines: 2 integers, $a_i$ and $b_i$, for $i = 1..M$

      Output

      1 integer, the maximal amount of fun The Team can have on their trip.

      Example

      Input:
      5 6 1 4
      5
      4
      5
      10
      2
      1 2
      1 3
      2 4
      3 4
      4 5
      5 4
      
      Output:
      22 
      Explanation of Sample:

      The network of cities and flights looks like this (the fun values of cities are shown below them):

      The optimal route that The Team can take goes through cities $1 \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow 4$, yielding a total fun value of $5+5+10+2+0=22$.

       


      Added by:Jacob Plachta
      Date:2013-05-09
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14888. Good Predictions

      Problem code: GOODB


      Having arrived at the ACM-ICPC contest site in a fun-filled mood, The Team continues their important pre-contest preparations. Specifically, every world-class team knows the importance of making predictions about their upcoming submissions.

      The Team knows that they'll get plenty of AC (Accepted) submissions, and they find those quite boring by now. As such, they'll focus on their incorrect ones. From their vast experience, The Team knows that they'll only get exactly $N$ ($1 \leq N \leq 300$) submissions wrong throughout the upcoming contest - in fact, they predict that, of those, exactly $W$ ($0 \leq W \leq 100$) will get WA (Wrong Answer), $T$ ($0 \leq T \leq 100$) will get TLE (Time Limit Exceeded), and the remaining $R$ ($0 \leq R \leq 100$) will get RE (Runtime Error). Note that $W+T+R=N$.

      Assuming that their predictions will certainly be correct, the members of The Team are wondering in how many ways that might occur. In other words, how many different ordered combinations of $N$ incorrect results (each being WA, TLE, or RE) exist which satisfy their predictions? Since The Team doesn't make many mistakes, surely you can calculate this value, right? However, since it can get quite large for you, compute it modulo ($10^9+7$).

      Input

      4 integers, $N$, $W$, $T$, and $R$

      Output

      1 integer, the number of valid ordered combinations of submission results, modulo ($10^9+7$).

      Example

      Input:
      3 2 1 0
      
      Output:
      3
      Explanation of Sample:

      Out of 3 submissions, two are WA, while the third is TLE. The following 3 ordered combinations are then possible:

      WA, WA, TLE

      WA, TLE, WA

      or

      TLE, WA, WA

      The answer is then $3$ modulo ($10^9+7$) = $3$.


      Added by:Jacob Plachta
      Date:2013-05-09
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14889. Good Strategy

      Problem code: GOODC


      The ACM-ICPC World Finals have begun! However, let's not be too hasty - even though The Team features three of the best coders to have ever coded, they know the importance of first determining what to code.

      The contest features $N$ ($1 \leq N \leq 10^6$) problems (conveniently numbered $1..N$), and runs for $M$ ($1 \leq M \leq 10^6$) minutes. Every problem is associated with a distinct colour - and each time a team solves a problem, they receive a balloon of its corresponding colour, which is visible to all. Obviously, easier problems will be solved by more teams, and so more of their balloons will be floating around in the contest room. Additionally, The Team has found that earlier problems in the set tend to be easier. Therefore, given 2 problems $i$ and $j$, $i$ is considered easier than $j$ if there are either more $i$ balloons than $j$ balloons in the room, or there are an equal number of balloons and $i<j$.

      At the start of the contest (at the 0th minute), there are no balloons in the room, of course. After that, during every minute $i$ (for $i=1..M$), problem $p_i$ ($1 \leq p_i \leq N$) is either solved by The Team (which will only happen if they have not solved it previously), or by some opposing team. The former possibility is represented by $t_i=1$, and the latter by $t_i=2$. In either case, a $p_i$ balloon is brought into the room. However, in the former case, The Team will no longer care about problem $p_i$ in the slightest.

      At the end of every minute after the 0th one, the members of The Team want to get their bearings on what they should be working on (and what they should be staying away from). Specifically, out of problems that they haven't yet solved, they want to know what the single easiest and the single hardest problems are, given the information that can be gleaned from the balloons. These two values may be the same, if The Team has only one problem left to solve. If they're solved all of the problems already, they can instead commence the process of making distracting noises. Are you smart enough to figure out what The Team's strategy throughout the contest will be?

      Input

      First line: 2 integers, $N$ and $M$

      Next $M$ lines: 2 integers, $t_i$ and $p_i$, for $i = 1..M$

      Output

      $M$ lines: Either 2 integers, the easiest followed by the hardest unsolved problem number after the first $i$ minutes, or the string "Make noise" if all problems have bee solved by The Team, for $i = 1..M$.

      Example

      Input:
      3 8
      2 2
      2 1
      1 1
      2 3
      2 3
      1 2
      1 3
      2 1
      Output:
      2 3
      1 3
      2 3
      2 3
      3 2
      3 3
      Make noise
      Make noise
      
      Explanation of Sample:

      After the first minute, we've seen 1 balloon for problem 2, and 0 balloons for problems 1 and 3. Therefore, the easiest problem is 2, since it has the most balloons, and the hardest problem is 3, since it's the last problem with the least balloons.

      After the second minute, the counts for the 3 problems are 1, 1, and 0. The easiest problem is now 1, since it's the first problem with the most balloons, while the hardest is still 3.

      After the third minute, the counts for the 3 problems are 2, 1, and 0, but problem 1 has now been solved by The Team. The easiest remaining problem is 2, and the hardest is 3.

      After the fourth minute, the counts for the 3 problems are 2 (solved), 1, and 1. The easiest unsolved problem is 2, and the hardest is 3.

      After the fifth minute, the counts for the 3 problems are 2 (solved), 1, and 2. The easiest unsolved problem is 3, and the hardest is 2.

      After the sixth minute, the counts for the 3 problems are 2 (solved), 2 (solved), and 2. The only unsolved problem is 3.

      After the seventh and eighth minutes, all 3 problems have been solved by The Team, so noise should be made.


      Added by:Jacob Plachta
      Date:2013-05-09
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14890. Good Code

      Problem code: GOODD


      It's time for the members of The Team to do what they do best - coding! Faster than you can say "Dijkstra", they've already produced an elegant piece of work. The program has $N$ ($1 \leq N \leq 10^6$) lines of code (conveniently numbered $1..N$), and just one integer variable, $c$, which starts with a value of 0. The program starts executing at line 1, and every line $i$ contains one of the following:

         1. "c++;" - The value of $c$ is incremented by 1. Then, if $i=N$, the program terminates - otherwise, the program moves to line $i+1$.

         2. "x:" - This line contains the label $x$, where $x$ is an integer such that $1 \leq x \leq 10^6$. No value of $x$ will appear as a label more than once in the program. If $i=N$, the program terminates - otherwise, the program moves to line $i+1$.

         3. "goto x;" - The program jumps to the single line that contains the label $x$, where $x$ is an integer such that $1 \leq x \leq 10^6$. It is guaranteed that, for every such line, the corresponding label will exist in the program.

      Now, even though this program is glorious, its creators are wondering if it's quite correct. In particular, they know that $c$ should ideally reach a value of $M$ ($1 \leq M \leq 10^{12}$), but they're not sure when. If the program terminates with $c<M$, then certainly there's an issue, and the program should get a WA (Wrong Answer). If the program will never terminate, and $c$ will never reach a value of $M$, then that's also no good, and can be considered a TLE (Time Limit Exceeded). In all other cases, however, The Team would like to know exactly on which line $c$ will first attain a value of $M$. Naturally, having written the program, they instantly realized this already. But can you?

      Input

      First line: 2 integers, $N$ and $M$

      Next $N$ lines: The $i$th line of the program (as described above), for $i=1..N$

      Output

      Either 1 integer, the number of the line on which $c$ will first reach a value of $M$, or the string "WA" if the program terminates with $c<M$, or the string "TLE" if the program runs forever with $c<M$.

      Example

      Input:
      12 4
      c++;
      goto 6;
      18:
      c++;
      c++;
      goto 2;
      goto 6;
      6:
      goto 18;
      2:
      c++;
      c++;
      Output:
      11 
      Explanation of Sample:

      The program will run through the following lines, and corresponding values of $c$:

      Line 1 ("c++;"), $c=1$

      Line 2 ("goto 6;"), $c=1$

      Line 8 ("6:"), $c=1$

      Line 9 ("goto 18;"), $c=1$

      Line 3 ("18:"), $c=1$

      Line 4 ("c++;"), $c=2$

      Line 5 ("c++;"), $c=3$

      Line 6 ("goto 2;"), $c=3$

      Line 10 ("2:"), $c=3$

      Line 11 ("c++;"), $c=4$

      As can be seen, $c$ first achieves a value of $M=4$ on line 11.


      Added by:Jacob Plachta
      Date:2013-05-09
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14891. Good Debugging

      Problem code: GOODE


      Any good coder knows that writing a program is only half the battle - and each member of The Team is most certainly a good coder. Maybe you're not a good coder, though, and you're wondering what the other half is. Debugging, of course!

      The Team has a program with $N$ ($1 \leq N \leq 10^6$) lines (conveniently numbered $1..N$) - and, unfortunately, every single line happens to initially have a bug in it. The programming language they're using will run the program from the start, line by line, and will always crash as soon as it encounters a total of $L$ ($1 \leq L \leq 10^6$) buggy lines.

      The Team will make $M$ ($1 \leq M \leq 10^6$) attempts to debug the program. The $i$th attempt will consist of modifying every line in the inclusive range of lines $a_i..b_i$ ($1 \leq a \leq b \leq N$). In particular, these coders are so amazing that, every single time they modify a buggy line, it becomes perfect! However, every time they modify a perfect line, they instead introduce a bug into it. After every debugging attempt, The Team will run their new program, and observe how many lines of code it gets through before crashing. Sometimes, the program may even terminate successfully! The modified code will then carry over for future modifications.

      Now, the members of The Team would like to know how their program will fare throughout the debugging session. Are your debugging skills good enough to figure that out?

      Input

      First line: 3 integers, $N$, $M$ and $L$

      Next $M$ lines: $a_i$ and $b_i$, for $i=1..N$

      Output

      $M$ lines: Either 1 integer, the number of lines the program executes before crashing after the first $i$ modifications, or the string "AC?" if it doesn't crash at all, for $i=1..M$.

      Example

      Input:
      6 4 2
      2 4
      4 6
      1 1
      1 2
      Output:
      5
      4
      AC?
      2
      Explanation of Sample:

      The following table shows the status of each line of code after every modification, with newly-changed lines shown in bold font. Buggy lines represented by 1s, and correct ones by 0s.

      After 1 modification, then, the program will encounter its second bug at line 5, at which point it will crash. Similarly, after 2 modifications, it will crash after 4 lines, and after 4 modifications, it will crash after just 2. After 3 modifications, however, it will not crash at all, as the program will contain only 1 bug at that point.


      Added by:Jacob Plachta
      Date:2013-05-09
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14892. Good Aim

      Problem code: GOODF

      The heated competition of the ACM-ICPC World Finals continues, and The Team is at the top of their game! Well, okay, maybe they're not actually doing so well, according to the scoreboard, yet. But they have a plan!

      The contest is taking place in a huge room with a regular grid of desks. The columns and rows are each numbered $1..10^6$, and the desk in the $x$th column and $y$th row is considered to have coordinates ($x$,$y$). The Team is sitting at coordinates ($X$,$Y$). There are $N$ ($1 \leq N \leq 10^6$) opposing teams (conveniently numbered $1..N$), with team $i$ having $m_i$ ($1 \leq m_i \leq 10^6$) members, all sitting at coordinates ($x_i$,$y_i$). No desk is occupied by more than one team, and all other desks are empty.

      Now, The Team is interested in removing some of the more dangerous opponents from the competition. To accomplish this, they have a number of water balloons at their disposal (after all, where in the contest rules does it say that water balloons are not allowed?). Always conservative, they would first like to answer $Q$ ($1 \leq Q \leq 10^6$) queries - for the $i$th query, how many balloons it would theoretically take to take out all of the members of team $q_i$?

      In order to do any real damage, the water balloons will of course have to be thrown extremely hard - in fact, in a perfectly straight line, and not over any obstacles besides empty desks. This means that, if team $j$ lies exactly on the line segment from The Team to team $i$, then every member of team $j$ must be dispatched before any members of team $i$ can be hit. It takes one balloon to knock one person out (the members of The Team have received plenty of training, so they're not about to miss a throw). Note that these queries are all only theoretical (for the moment) - so each should be answered assuming that all teams are still untouched.

      The members of The Team will need to carefully choose with opponents to take out, based on how well they're doing and how many balloons it would take, so they're already answered all of their queries in their heads. Maybe, if you can answer them as well, you can also adopt such techniques in the future...

      Input

      First line: 4 integers, $N$, $Q$, $X$, and $Y$

      Next $N$ lines: 3 integers, $x_i$, $y_i$, and $m_i$, for $i = 1..N$

      Next $Q$ lines: 1 integer, $t_i$, for $i = 1..Q$

      Output

      $Q$ lines: 1 integer, the number of balloons that would be required to take out team $t_i$, for $i = 1..Q$.

      Example

      Input:
      6 6 3 2
      5 6 3
      2 1 5
      4 4 2
      4 3 1
      5 4 2
      7 6 1
      6
      5
      4
      3
      2
      1
      Output:
      4
      3
      1
      2
      5
      5
      Explanation of Sample:

      The following grid shows the positions of the $N$ opposing teams (marked with their numbers), as well as The Team (marked with a "T"). The line segments represent direct lines of sight to the opponents.

      As can be seen, team 6 is blocked by teams 4 and 5. Therefore, taking them out would require $1+2+1=4$ balloons in total. Similarly, team 5 is blocked by team 4, and requires $1+2=3$ balloons. Teams 4, 3, and 2 are not blocked by any others, and so only require 1, 2, and 5 balloons, respectively. Finally, team 1 is blocked by team 3, and would require $2+3=5$ balloons to dispose of.


      Added by:Jacob Plachta
      Date:2013-05-09
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14893. Good Inflation

      Problem code: GOODG

      The competition is drawing to a close, and The Team could really use another balloon to help them come out on top...good thing they're no chumps, and thought of this in advance! Before the contest started, they instructed an accomplice to go to the local balloon shop, buy an extra balloon, and deliver it to them at the conclusion of the event. It is true that their balloons then won't match up with the scoreboard's record of which problems they've solved - but, in the end, it's the balloons that count! In fact, The Team knows that, the larger their extra balloon, the more their opponents (and the judges) will be intimidated. They're not the best ACM-ICPC team in the world for nothing!

      However, this balloon shop is rather strange. The accomplice is given an empty balloon (a balloon with size 0), and told that he can tie it closed and keep it after exactly $N$ ($1 \leq N \leq 10^6$) minutes. In the meantime, during each minute, an inflation offer is available. If offer $i$ is taken, then, at the start of the $i$th minute, the balloon's size will be increased by $a_i$ ($0 \leq a_i \leq 10^6$). However, since the balloon cannot be closed until the end, its air will leak out at a constant rate, which depends on the gas that was used - in particular, its size will immediately start to decrease at a rate of $d_i$ ($0 \leq d_i \leq 10^6$) per minute, until either another offer is taken, or the balloon deflates completely (its size can never become negative, of course).

      The Team will not be happy if they don't receive the largest balloon possible. Unfortunately, their accomplice happens to be...you. Can you figure out the maximal size that the balloon can have at the start of minute $N+1$, before it's too late?

      Input

      First line: 1 integer, $N$

      Next $N$ lines: 2 integers, $a_i$ and $d_i$, for $i=1..N$

      Output

      1 integer, the maximal size which the balloon can have at the start of minute $N+1$.

      Example

      Input:
      5
      2 3
      10 2
      0 1
      5 4
      1 10
      Output:
      5
      Explanation of Sample:

      The best option is to take only the offers at minutes 2 and 3. At the start of minute 2, the balloon will be inflated to size 10, and will deflate to size 8 by the start of minute 3. At that point, the balloon's size will not change, but its deflation rate will change to 1. As a result, by the start of minute 6, its size will be 5.

      Note that, if the offer at minute 1 is additionally taken, the balloon will simply be inflated to size 2 before deflating back to size 0 by the start of minute 2 - therefore, this will not change the outcome.

      Also note that, if the offer at minute 4 is additionally taken, the balloon will inflate to size 12 at the start of minute 4, but its deflation rate of 4 will result in a size of 4 at the start of minute 6, which is not optimal.

       


      Added by:Jacob Plachta
      Date:2013-05-09
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14894. Good Celebration

      Problem code: GOODH

      The ACM-ICPC World Finals are over! Which team came out on top? Why, only our favourite team - everyone's favourite team - the most deserving, lovable, courteous, powerful, flawless, successful team that has ever existed. Who else?

      It's time to celebrate, and what better way is there to celebrate than by eating cake? The contest organizers have bought $N$ ($1 \leq N \leq 200$) cakes (conveniently numbered $1..N$) - however, ever generous, The Team will only eat cake 1, leaving the rest for the other, inferior teams. They will need their cake to be as tasty as possible, though. To help with this, $M$ ($0 \leq M \leq 200$) globs of icing are available, which will be distributed among the cakes. Icing is always used in whole globs.

      The cakes are arranged in a somewhat strange way - piled on top of one another. Cake 1 is directly on top of a table, while every other cake $i$ (for $i=2..N$) is directly on top of cake $c_i$. $c_1$ is considered to have a value of 0. Note that there may be multiple cakes on top of a single cake, and that the entire structure obeys the laws of physics (no cake is on top of itself, and no cakes are floating).

      Now, the tastiness of any cake $i$ is determined by the formula $b_i + m_i(x_i + y_i)$. $b_i$ ($0 \leq b_i \leq 100$) and $m_i$ ($0 \leq m_i \leq 100$) are simply properties of cake $i$, which depend on its size, shape, weight, temperature, fluffiness, and so on. $x_i$ is the number of globs of icing that are chosen to be applied to cake $i$. If there are no cakes on top of cake $i$, $y_i=0$ - otherwise, $y_i$ is the minimal tastiness of any cake directly on top of cake $i$. No cake will ever be capable of achieving a tastiness value larger than $2^{60}$, no matter how the icing is distributed.

      The members of The Team have already, of course, determined how the available icing could be optimally applied to the mountain of cakes to maximize the tastiness of their cake (cake 1). However, the contest organizers are the ones who will actually be distributing the icing, and they had better hope they get it right! Can you help them determine how tasty cake 1 should be? You don't want to know what The Team will do if their celebration isn't perfect...

      Input

      First line: 2 integers, $N$ and $M$

      Next $N$ lines: 3 integers, $c_i$, $b_i$, and $m_i$, for $i=1..N$

      Output

      1 integer, the maximal tastiness of cake 1, after all of the icing has been used

      Example

      Input:
      3 2
      0 5 1
      1 3 4
      1 2 6
      Output:
      12
      Explanation of Sample:

      The optimal icing distribution is 1 glob each on cakes 2 and 3. This gives cake 2 a tastiness of $3+4(1+0)=7$, and cake 3 a tastiness of $2+6(1+0)=8$. Since both of these cakes are on top of cake 1, it then has a tastiness of $5+1(0+min\{7,8\})=12$. No other icing distribution yields a higher tastiness for cake 1.

       


      Added by:Jacob Plachta
      Date:2013-05-09
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14905. Zig when you zag

      Problem code: ZIGZAG2


      We say that a sequence of numbers x(1),x(2),...,x(k) is zigzag if no three of its consecutive elements create a nonincreasing or nondecreasing sequence. More precisely, for all i=1,2,...,k-2 either x(i+1)<x(i),x(i+2) or x(i+1)>x(i),x(i+2).

      You are given two sequences of numbers a(1),a(2),...,a(n) and b(1),b(2),...,b(m). The problem is to compute the length of their longest common zigzag subsequence. In other words, you're going to delete elements from the two sequences so that they are equal, and so that they're a zigzag sequence. If the minimum number of elements required to do this is k then your answer is m+n-2k.

      Input

      There is a single integer t (t≤100) on the first line of input. Then t test cases follow. Each of them consists of two lines. The first line contains the length of the first sequence n (1≤n≤2000) and n integers a(1),a(2),...,a(n). The second line contains the length of the second sequence m (1≤m≤2000) and m integers b(1),b(2),...,b(m). All a(i) and b(i) are from [-109,109]. (REPEAT: the first number on the line is not part of the sequence, it's the length of the sequence.)

      Output

      For each test case output one line containing the length of the longest common zigzag subsequence of a and b.

      Example

      Input:
      2
      5 1 2 5 4 3
      5 4 1 2 5 3
      3 1 2 1
      2 1 1
      Output:
      3
      2
      

      Added by:Pawel Gawrychowski
      Date:2013-05-10
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14923. King Graffs Defense

      Problem code: GRAFFDEF

      King Graff, the ruler of the land of Feerie, has a problem - his nation is under attack! Luckily, he has an army at his disposal, composed of a whopping $S$ soldiers (where $S = 2$).

      Feerie consists of $N$ ($1 \leq N \leq 100,000$) towns (numbered $1..N$), and $M$ ($1 \leq M \leq 500,000$) roads. The $i$th road runs between distinct towns $A_i$ and $B_i$, in both directions. No pair of towns is directly connected by more than one road, but every pair of towns is connected by at least one path of connected roads. King Graff would like to position his two soldiers in two different towns to prepare for the impending assault - however, since he's not much of a strategist, he'll choose the towns at complete random.

      Graff's only real concern is with his enemies using a divide-and-conquer strategy. His soldiers will be susceptible to this type of attack if there exists any single road that, if blocked, will prevent them from reaching each other by any system of connected roads. As the royal computer scientist, your job is to determine the probability that King Graff will be defeated.

      Input

      First line: 2 integers, $N$ and $M$

      Next $M$ lines: 2 integers, $A_i$ and $B_i$, for $i = 1..M$

      Output

      1 real number (rounded to 5 decimal places), the probability that the two towns chosen by Graff can be disconnected by the removal of any single road

      Example

      Input:
      4 4
      1 2
      1 3
      2 4
      4 1

      Output:

      0.50000
      Explanation of Sample:

      The map of Feerie is illustrated below:

      King Graff can make 6 possible choices as to where to place his soldiers, and three of those (the three with one of the soldiers being at town 3) result in defeat (if the road between towns 1 and 3 is destroyed). The probability of failure is then $3/6 = 0.5$.


      Added by:Jacob Plachta
      Date:2013-05-12
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14924. King Graffs Tolls

      Problem code: GRAFFTOL

      King Graff, the ruler of the land of Feerie, feels that he is not quite rich enough. As such, he would like to impose travel tolls on his people! After all, why should they get to walk around his kingdom for free?

      Feerie consists of $N$ ($1 \leq N \leq 10^5$) towns (numbered $1..N$), and $N-1$ roads. The $i$th road runs between distinct towns $A_i$ and $B_i$, in both directions. Every pair of towns is connected by exactly one path of connected roads. Currently, all travel is free, but King Graff is interested in charging for passage through certain towns.

      He is planning to have a meeting with the royal computer scientest - that would be you. The meeting will last $M$ ($1 \leq M \leq 10^5$) minutes, and in the $i$th minute, one of two things will occur, described by $T_i$. If $T_i=$ "T", Graff will proclaim that town $X_i$ shall henceforth cost $Y_i$ ($0 \leq Y_i \leq 10^9$) dollars to pass through, and you'll update the map accordingly. Otherwise, if $T_i=$ "Q", he will ask you how much a trip from town $X_i$ to a different town $Y_i$ would currently cost a commoner, in order to gauge the effectiveness of his tolls - and you had better answer quickly! Note that neither the starting nor the ending town's tolls are included in a trip's cost, as they are not passed through. Note also that a town's toll may be modified by Graff mutiple times throughout the meeting, in which case the most recent modification at any point will stand.

      Input

      First line: 1 integer, $N$

      Next $N-1$ lines: 2 integers, $A_i$ and $B_i$, for $i = 1..N-1$

      Next line: 1 integer, $M$

      Next $M$ lines: 1 character, $T_i$, and 2 integers, $X_i$ and $Y_i$, for $i = 1..M$

      Output

      $X$ lines (where $X$ is the number of questions asked by King Graff): 1 integer, the cost of the $i$th trip asked for (in dollars), for $i = 1..X$

      Example

      Input:
      4
      1 3
      2 3
      4 3
      6
      Q 1 4
      T 3 5
      Q 4 2
      Q 3 1
      T 3 1
      Q 1 2

      Outut:

      0
      5
      0
      1
      Explanation of Sample:

      The map of Feerie is illustrated below:

      The first trip asked for by King Graff goes through towns $1 \rightarrow 3 \rightarrow 4$. Since town 3 has no toll at that point, the trip's cost is 0.

      The second trip goes through towns $4 \rightarrow 3 \rightarrow 2$ and has a cost of 5, due to the new toll on town 3.

      The third trip goes through towns $3 \rightarrow 1$, passing through no towns and so costing nothing.

      The final trip goes through towns $1 \rightarrow 3 \rightarrow 2$ and costs only 1, as town 3's toll is reduced by then.


      Added by:Jacob Plachta
      Date:2013-05-12
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14925. King Graffs Trip

      Problem code: GRAFFTRI

      King Graff, the ruler of the land of Feerie, is going on a trip through his realm! He would like to give his people a chance to see their great king amongst them, almost as if he too were a petty commoner with no future.

      Feerie consists of $N$ ($1 \leq N \leq 10^4$) towns (numbered $1..N$), and $M$ ($1 \leq M \leq 10^5$) roads. The $i$th road runs from town $A_i$ to a different town $B_i$ (and can only be travelled in that one direction), and takes $T_i$ ($1 \leq T_i \leq 10^9$) minutes to traverse. No pair of towns is directly connected by more than one road in the same direction. King Graff will start his trip at town $X$, and would like to end at a different town $Y$. Furthermore, since he has better things to do, he would like to complete it in at most $L$ ($1 \leq L \leq 10^{15}$) minutes.

      However, Graff does not like to go long without being worshipped, and the only proper place to do this is in a shrine built to him. $S$ ($1 \leq S \leq 100$) distinct towns contain such shrines - the $i$th shrine is in town $H_i$. He would like to minimize the longest continuous stretch of time spent during the trip without passing through any shrines. As the royal computer scientist, your job is to determine the length of this stretch, or break the news to your king that the trip cannot be completed in time. Note that the trip may be impossible to complete in any amount of time, if town $Y$ is not reachable from town $X$ by any path of connected roads.

      Input

      First line: 5 integers, $N$, $M$, $X$, $Y$, and $L$

      Next $M$ lines: 3 integers, $A_i$, $B_i$, and $T_i$, for $i = 1..M$

      Next line: 1 integer, $S$

      Next $S$ lines: 1 integer, $H_i$, for $i = 1..S$

      Output

      Line 1: 1 integer - the minimum value for the longest continuous stretch of travel time spent away from shrines (in minutes), or -1 if the trip cannot be completed in at most $L$ minutes

      Example

      Input:
      5 7 2 3 7
      2 3 5
      3 2 1
      2 1 4
      1 3 3
      2 4 3
      4 5 2
      5 3 3
      3
      1
      4
      5

      Output:

      4
      Explanation of Sample:

      The map of Feerie is illustrated below:

      The optimal route goes through towns $2 \rightarrow 1 \rightarrow 3$, taking 7 minutes with at most 4 minutes spent away from any shrines. The route $2 \rightarrow 3$ is shorter (taking 5 minutes), but has a longer continuous time away from shrines (5). The route $2 \rightarrow 4 \rightarrow 5 \rightarrow 3$ has a shorter such value (3), but takes longer than 7 minutes in total (8) and as such is not allowed.


      Added by:Jacob Plachta
      Date:2013-05-12
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14926. abdou set

      Problem code: KIMO1


      abdou has a set of unique positive integers . he wants to add several (possibly none) new positive integers to this set, such that when the set is sorted for every two consecutive numbers X , Y we have abs(X%m-Y%m) = 1 . your task is to calculate the smallest possible count of new numbers, with which he can achieve that. 
                                                                                      Input
       
      The first line contains T, the number of test cases. It is followed by 2*T each test case consist of two lines the first line contain two numbers m , N .. the second line contain N integer .
      1 <=T <= 5000 .
      1 <= m <= 10^5 
      2 <= N <=50.
      1 <= every integer in the set <= 10^6
                                                                                    Output
       
       For each line of input produce one line of output. This line contains the smallest possible count of new numbers, with which he can complete the set  or -1 if no solution .
                                                                                    Example
      input
      5
      2 3 
      2 10 20
      10 2
      10 20
      10 6
      11 19 5 30 40 100
      1 2 
      1  9999
      15 3
      4218 15210 1426
      10 6 11 19 5 30 40 1007
      output
      2
      1
      -1
      -1
      3
      expanation :
      in first test case we can add 3 and 13 to the given set to  achieve abdou goal  .
      you can see my time here 

       

      Abdou has a set of unique positive integers. He wants to add several (possibly none) new positive integers to this set, such that when the set is sorted, for every two consecutive numbers X , Y abs(X%M-Y%M) = 1 . Your task is to calculate the smallest possible count of new numbers, with which he can achieve that. 

                                                                                     Input

      The first line contains T, the number of test cases. It is followed by 2*T lines, two lines per test case. The first line contains two positive integers M and N. The second line contains N integers.

      1 <= T <= 5000 .

      1 <= M <= 10^5 

      2 <= N <=50.

      1 <= every integer in the set <= 10^6

                                                                                    Output

      For test case print a single integer in a separate line: the smallest possible count of new numbers, with which he can complete the set or -1 if no solution exists.

                                                                                    Example

      Input:

      5

      2 3 

      2 10 20

      10 2

      10 20

      10 6

      11 19 5 30 40 100

      1 2 

      1  9999

      15 3

      4218 15210 1426


      Output:

      2

      1

      -1

      -1

      3


      Explanation:

      In the first test case we can add 3 and 13 to the given set to achieve abdou goal.



      Added by:abdelkarim
      Date:2013-05-12
      Time limit:0.5s
      Source limit:5000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:owner









      SPOJ Problem Set (classical)

      14928. Pyramidal Constructions

      Problem code: PIRACON

      Humberto is a great Egyptian architect. In Egypt pyramid sculptural constructions were as common as ornaments. Pharaoh has asked Humberto to build N pyramids throughout Egypt. Humberto is very stingy when it comes to construction costs, so he always buys the exact necessary number of materials needed to complete his work.

      Tural Pyramids are built using smallest pyramids of "level 1", that are used as building blocks for higher levels. Stacking pyramids of "level 1" to create higher-level structures, leave gaps. Special parts, called "Tringus", are used to cover these gaps. They are of triangular shape, designed by Humberto to perfectly fill the gaps on piramid sides.

      For example, a pyramid of "Level 2" is constructed as follows: We are using a total of 6 pyramids of "level 1" (see the picture above). That leaves 4 gaps at the sides and we need 4 "Tringus" fo fill them. In total 10 pieces.

      Humberto asks us to help to calculate the total number and "Tringus" number of pieces needed for a pyramid of level K.

      Input

      First line contains integer T, number of test cases. Following N lines, each containing an integer K, the level of the piramid.

      Output

      You must print "Pyramid E. Nro# i: ", followed by the total number of parts used (both pyramids of "level 1" and "Tringus"). In the next line print "Tringus: ", followed by the number of "Tringus" used.

      Example

      Input:
      2
      1
      4
      
      Output:
      Pyramid E. Nro# 1: 1
      Tringus: 0
      Pyramid E. Nro# 2: 68
      Tringus: 24
      

      Constraints

      1<= T <= 10^4
      1<= K <= 10^6

      original statement(Spanish): Here

      Added by:Raffaele Ranaldo
      Date:2013-05-13
      Time limit:0.5s
      Source limit:500B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      14929. Subsequence

      Problem code: SUBSN

       

      A subsequence is a sequence that can be derived from another sequence by deleting some
      elements without changing the order of the remaining elements. For example “abd” is a
      subsequence of “abcdef”. - Wikipedia
      Your task in this problem is to decide if a given string is a subsequence of another string or not?
      Easy?

      A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example “abd” is a subsequence of “abcdef”. - Wikipedia.

      Your task in this problem is to decide if a given string is a subsequence of another string or not?

      Easy?

      Input

      The first line of input will be the number of test cases. Each test case will start with a line contains a string S, S will have letters from 'a' to 'z' and the length of S <= 100,000. This line will be followed by a number Q which is the number of queries you have to answer for the given string S, 1 <= Q <= 1000. Each of the next Q lines will contain a string T, T will have letter from 'a' to 'z' and the length of T <= 200. For each T you have to decide if T is a subsequence of S or not.

      Output

      For each test case print Q + 1 lines, The first line will have “Case C:” without quotes where C is the case number starting with 1. The next Q lines will have either “YES” or “NO” if the cross-ponding T is a subsequence of S or not respectively.

      Example

      Input:
      1
      abcdef
      3
      abd
      adb
      af
      
      Output:
      Case 1:
      YES
      NO
      YES

      Editors note:
      Strings in the input can be empty. Read data carefully to avoid issues. There should be no extra withespaces, of course except '\n'.


      Added by:hossamyosef
      Date:2013-05-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FCIS/ASU Local Contest 2013









      SPOJ Problem Set (classical)

      14930. Princess Farida

      Problem code: FARIDA

       

      Once upon time there was a cute princess called Farida living in a castle with her father, mother and uncle. On the way to the castle there lived many monsters. Each one of them had some gold coins. Although they are monsters they will not hurt. Instead they will give you the gold coins, but if and only if you didn't take any coins from the monster directly before the current one. To marry princess Farida you have to pass all the monsters and collect as many coins as possible. Given the number of gold coins each monster has, calculate the maximum number of coins you can collect on your way to the castle.

      Input

      The first line of input contains the number of test cases. Each test case starts with a number N, the number of monsters, 0 <= N <= 10^4. The next line will have N numbers, number of coins each monster has, 0 <= The number of coins with each monster <= 10^9. Monsters described in the order they are encountered on the way to the castle.

      Output

      For each test case print “Case C: X” without quotes. C is the case number, starting with 1. X is the maximum number of coins you can collect.

      Example

      Input:
      2
      5
      1 2 3 4 5
      1
      10
      Output:
      Case 1: 9
      Case 2: 10

      Added by:hossamyosef
      Date:2013-05-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FCIS/ASU Local Contest 2013









      SPOJ Problem Set (classical)

      14932. Lowest Common Ancestor

      Problem code: LCA

       

      A tree is an undirected graph in which any two vertices are connected by exactly one simple
      path. In other words, any connected graph without cycles is a tree. - Wikipedia
      The lowest common ancestor (LCA) is a concept in graph theory and computer science. Let T
      be a rooted tree with N nodes. The lowest common ancestor is defined between two nodes v and
      w as the lowest node in T that has both v and w as descendants (where we allow a node to be a
      descendant of itself). - Wikipedia
      Your task in this problem is to find the LCA of any two given nodes v and w in a given tree T.

      A tree is an undirected graph in which any two vertices are connected by exactly one simple path. In other words, any connected graph without cycles is a tree. - Wikipedia 

      The lowest common ancestor (LCA) is a concept in graph theory and computer science. Let T be a rooted tree with N nodes. The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself). - Wikipedia

      Your task in this problem is to find the LCA of any two given nodes v and w in a given tree T.

      For example the LCA of nodes 5 and 7 in this tree is the node number 3.

      Input

      The first line of input will be the number of test cases. Each test case will start with a number N the number of nodes in the tree, 1 <= N <= 1,000. Nodes are numbered from 1 to N. The next N lines each one will start with a number M the number of child nodes of the Nth node, 0 <= M <= 999 followed by M numbers the child nodes of the Nth node. The next line will be a number Q the number of queries you have to answer for the given tree T, 1 <= Q <= 1000. The next Q lines each one will have two number v and w in which you have to find the LCA of v and w in T, 1 <= v, w <= 1,000.

      Input will guarantee that there is only one root and no cycles.

      Output

      For each test case print Q + 1 lines, The first line will have “Case C:” without quotes where C is the case number starting with 1. The next Q lines should be the LCA of the given v and w respectively.

      Example

      Input:
      1
      7
      3 2 3 4
      0
      3 5 6 7
      0
      0
      0
      0
      2
      5 7
      2 7
      
      Output:
      Case 1:
      3
      1

      Added by:hossamyosef
      Date:2013-05-13
      Time limit:3s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:FCIS/ASU Local Contest 2013









      SPOJ Problem Set (classical)

      14935. Cactus

      Problem code: CAC

       

      In the mathematical field of graph theory, a spanning tree T of a connected, undirected graph
      G is a tree composed of all the vertices and some (or perhaps all) of the edges of G. Informally,
      a spanning tree of G is a selection of edges of G that form a tree spanning every vertex. That is,
      every vertex lies in the tree, but no cycles (or loops) are formed. On the other hand, every
      bridge of G must belong to T (a bridge is an edge whose deletion increases the number of
      connected components).
      A spanning tree of a connected graph G can also be defined as a maximal set of edges of G that
      contains no cycle, or as a minimal set of edges that connect all vertices. - Wikipedia
      In graph theory, a cactus (sometimes called a cactus tree) is a connected graph in which any
      two simple cycles have at most one vertex in common. Equivalently, every edge in such a graph
      belongs to at most one simple cycle. Equivalently, every block (maximal subgraph without a
      cut-vertex) is an edge or a cycle. - Wikipedia

      In the mathematical field of graph theory, a spanning tree T of a connected, undirected graph G is a tree composed of all the vertices and some (or perhaps all) of the edges of G. Informally, a spanning tree of G is a selection of edges of G that form a tree spanning every vertex. That is, every vertex lies in the tree, but no cycles (or loops) are formed. On the other hand, every bridge of G must belong to T (a bridge is an edge whose deletion increases the number of connected components).

      A spanning tree of a connected graph G can also be defined as a maximal set of edges of G that contains no cycle, or as a minimal set of edges that connect all vertices. - Wikipedia

      In graph theory, a cactus (sometimes called a cactus tree) is a connected graph in which any two simple cycles have at most one vertex in common. Equivalently, every edge in such a graph belongs to at most one simple cycle. Equivalently, every block (maximal subgraph without a cut-vertex) is an edge or a cycle. - Wikipedia

       

       

      cactus graph

       

      Your task in this problem is to count the number of ways you can convert a cactus graph to a spanning tree.

      Input

       

      The first line of input will be the number of test cases. Each test case will start with a two numbers N and E where N is the number of vertices of the cactus graph, vertices are numbered from 1 to N, 3 <= N <= 81 and E is the number of edges in the graph, 2 <= E <= 120. The next E lines each one will have two numbers v and w and that means there is an edge between vertix v and w.

       

      Output

       

      For each test case print “Case C: X” without quotes where C is the case number starting with 1 and X is the number of ways you can convert the given cactus graph to a spanning tree.

       

      Example

      Input:
      2
      3 3
      1 2
      2 3
      1 3
      5 5
      1 2
      2 3
      2 4
      3 4
      4 5
      
      Output:
      Case 1: 3
      Case 2: 3

      Added by:hossamyosef
      Date:2013-05-13
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:FCIS/ASU Local Contest 2013









      SPOJ Problem Set (classical)

      14943. Dynamically-Rooted Tree

      Problem code: DRTREE

      You are given a rooted tree with N nodes, numbered from 1 to N. Initially node 1 is the root. Each node i has a weight W[i]. You have to perform two types of operations:
      "S a" - Find the sum of weights of node a's sub-tree nodes (including node a).
      "R a" - Change root of the tree to a.

      Input

      Line 1: N (1 <= N <= 105), number of nodes.
      Line 2: N space-separated integers, weights of nodes from 1 to N. i'th integer is W[i] (1 <= W[i] <= 109).
      Line 3: N-1 space-separated integers, i'th integer is the parent of node i+1.
      Line 4: Q, the number of operations (1 <= Q <= 105).
      Lines 5 .. 5+Q-1: Every line contains a space separated character and an integer. Character describes the type of the operation, and integer is the node number.

      Output

      For each operation of type 'S', output the operations result in a separate line.

      Example

      Input:
      5
      2 1 1 1 2
      1 1 2 2
      3
      S 2
      R 2
      S 1
      
      Output:
      4
      3
      

      Added by:Hasan Jaddouh
      Date:2013-05-13
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      14944. Reindeer Games

      Problem code: SANTA1


      With the presents all crafted and packed into Santa's sack, it's almost time for his annual trip across the world, spreading cheer to all! However, he's first taking the time to experiment with various combinations of reindeer to pull his sleigh. For a successful journey, they'll have to work productively!

      Every reindeer has a unique name (a string of up to 20 case-sensitive letters), as well as a seniority and a productivity value (both positive integers no larger than $10^6$). When a group of reindeer is chosen to pull the sleigh, they line up in single file, always in descending order of seniority from the front. If multiple reindeer have the same seniority, they line up in descending order of productivity within themselves (no two reindeer have both the same seniority and the same productivity). The productivity of a pair of adjacent reindeer in the lineup is the product of their individual productivity values, and the total productivity of the lineup is the sum of all such productivities. The total productivity of a group of fewer than 2 reindeer is 0.

      Starting with an empty group of reindeer, Santa will perform $M$ ($1 \leq M \leq 10^5$) modifications. The $i$th modification will involve the reindeer with name $N_i$. If $A_i=$ 'A', then this reindeer will be added to the lineup (in its correct spot) - in this case, its seniority and productivity values, $S_i$ and $P_i$, will be given. Otherwise, if $A_i=$ 'R', then this reindeer will be removed from the lineup. Each reindeer will only be added once, and will only be removed if it's currently in the lineup.

      To track which combinations of reindeer are more effective than others, Santa would like you to calculate the total productivity of the lineup after every modification made to it. Quickly, now, Christmas won't wait!

      Input

      First line: $M$

      Next $M$ lines: $A_i$ and $N_i$, followed by $S_i$ and $P_i$ if $A_i=$ 'A', for $i = 1 .. M$

      Output

      $M$ lines: The total productivity of the reindeer lineup after every modification

      Example

      Input:
      5
      A Dancer 5 2
      A Prancer 3 8
      A Vixen 10 9
      R Dancer
      A Rudolph 3 1
      Output:
      0
      16
      34
      72
      80
      Explanation of Sample:

      After the first modification, the lineup consists of just Dancer, and so the total productivity is $0$.

      After the second modification, Prancer is standing behind Dancer. Their productivity is $2 \cdot 8 = 16$.

      After the third modification, we have Vixen, followed by Dancer, followed by Prancer. The productivity of Vixen and Dancer is $18$, while that of Dancer and Prancer is again $16$. Thus, the total productivity is $34$.

      After the fourth modification, the lineup consists of only Vixen and Prancer, with productivity $72$.

      Finally, after the fifth modification, Rudolph is behind Prancer, with this pair of reindeer contributing $8$ productivity, for a total of $80$.


      Added by:Jacob Plachta
      Date:2013-05-14
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14946. Travelling Santa

      Problem code: SANTA2

      At last, Santa is on his way! He's got a number of presents to deliver to various households, and he won't stop until he's disposed of them all. However, each present is only suitable for one gender - for example, men might enjoy such things as baseball bats, football helmets, and certain adult reading material, while women would prefer make-up, knitting needles, and certain other adult reading material.

      At the moment, Santa is in a neighbourhood with $H$ ($1 \leq H \leq 50$) houses (numbered $1..H$), connected by $R$ ($1 \leq R \leq 10^{4}$) roads. The family living in house $i$ includes $M_i$ ($0 \leq M_i \leq 10$) males and $F_i$ ($0 \leq F_i \leq 10$) females. The $i$th road runs between distinct houses $A_i$ and $B_i$, and can be travelled in either direction. No pair of houses is directly connected by more than one road.

      Santa starts at house $1$, carrying $M_S$ ($0 \leq M_S \leq 50$) male-appropriate and $F_S$ ($0 \leq F_S \leq 50$) female-appropriate presents. He then repeats the following process until he's out of gifts. First, he moves randomly to an adjacent house (a house reachable by taking one road) - it's guaranteed that there will be at least one such house. If he currently has $m$ male-appropriate and $f$ female-approrpiate presents, his probability of moving to adjacent house $i$ is proportional to the value of $M_i m + F_i f$. Of course, the probabilities for all adjacent houses must add up to $1$. Note that if this value is $0$ for all adjacent houses, then Santa will move to any of them with equal probability. After reaching the new house, he delivers a male present to it with probability $\frac{m}{m+f}$, and a female present otherwise.

      Wanting to plan ahead to leaving this neighbourhood, Santa is curious as to where he'll end up. He'd like you to calculate the probability of him being at each of the $H$ houses when he runs out of presents. 

      Input

      First line: $H$ and $R$

      Next $H$ lines: $M_i$ and $F_i$, for $i = 1..H$

      Next $R$ lines: $A_i$ and $B_i$, for $i = 1..R$

      Next line: $M_S$ and $F_S$

      Output

      $H$ lines: The probability of Santa finishing his present-delivering process at house $i$, rounded off to 6 decimal places, for $i = 1..H$

      Example

      Input:
      4 3
      1 2
      2 1
      1 1
      4 0
      1 2
      2 4
      3 1
      1 1
      Output:
      0.760000
      0.000000
      0.000000
      0.240000
      Explanation of Sample:

      The neighbourhood looks as follows:

      House $1$ is adjacent to houses $2$ and $3$. The probability of Santa moving to house $2$ is proportional to $2 \cdot 1 + 1 \cdot 1 = 3$, while the probability of him moving to house $3$ is proportional to $1 \cdot 1 + 1 \cdot 1 = 2$. Therefore, he will move to house $2$ with probability $\frac{3}{5}$, and to house $3$ with probability $\frac{2}{5}$. If he moves to house $3$, then, regardless of which present he delivers, he will be guaranteed to move back to house $1$ next, where he will deliver the remaining present.

      Otherwise, if he moves to house $2$ at first, then he will proceed to deliver a male-appropriate present there with probability $\frac{1}{1+1} = \frac{1}{2}$, and a female-appropriate one also with probability $\frac{1}{2}$. In the former case, he will then have just 1 female present remaining, so he will move on to house $4$ with probability $0$, and back to house $1$ with probability $1$. Otherwise, he will have 1 male present remaining, and will move on to house $4$ with probability $\frac{4}{5}$, and back to house $1$ with probability $\frac{1}{5}$. In any case, he will then deliver his second present and be done. 


      Editors note:
      You can deliver more male or female presents to a house, than the number of given gender inhabitants. Even if that number would be zero, you could still drop given type of presents. You only need to follow the formulas in the problem description.


      Added by:Jacob Plachta
      Date:2013-05-14
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14947. Breaking and Entering

      Problem code: SANTA3


      Santa's favourite part of Christmas is, of course, entering people's houses through their fireplaces at night and leaving them presents. On this occasion, he's visiting a house which can be modeled as a rectangular grid of cells, with $R$ ($1 \leq R \leq 100$) rows and $C$ ($1 \leq C \leq 100$) columns. Each cell is either empty (represented by a '.'), contains a wall ('#'), contains a fireplace ('F'), contains a stocking of a certain size ('1'..'9'), or is empty but initially contains a dog facing in a certain direction (with up represented by '^', right by '>', down by 'v', and left by '<'). Exactly one cell contains a fireplace, and this is where Santa begins his business.

      Based on the layout of the house, Santa has devised a plan of action in advance. He will enter carrying $P$ ($1 \leq P \leq 10^9$) presents, and will proceed to execute $M$ ($1 \leq M \leq 1000$) moves in order, one each second. Each move consists of moving one cell up (represented by a 'U'), right ('R'), down ('D'), or left ('L'). However, Santa cannot walk through walls, so if he would move outside the grid, or if the cell that he would move into contains a wall, he stays put for the second.

      Each second, just as Santa is making his move, all of the dogs in the house also move simultaneously. Each dog moves forward one cell in the direction that it's facing, if that cell is within the grid and is empty (ignoring other dogs or Santa). Otherwise, it rotates clockwise by 90 degrees. Note that dogs don't interfere with one another in any way, and at various points in time there may be multiple dogs in a single cell.

      Now, at the end of the second, if Santa finds himself in a cell with a stocking, he deposits a single present in it, if possible. In particular, he must be carrying at least one present, and the stocking must not have already been stuffed with a number of gifts equal to its capacity. Otherwise, if Santa is in the cell containing the fireplace, he immediately exits the house if he has no presents left, and/or he has already placed at least one present into every stocking in the house. Finally, if Santa finds himself in the same cell as one or more dogs, each such dog in turn steals half of his remaining presents, rounded up.

      Before executing his brilliant plan, Santa would like to know how well his excursion will actually go. He'd like you to make a copy of the grid representing the house, but with every cell containing a stocking labelled with a digit ('0'..'9') representing how many presents that stocking will contain in the end, and with every other cell represented by just a '.'. He'd also like to know where in the house he'll end up.

      Input

      First line: $R$ and $C$

      Next $R$ lines: $C$ characters, representing the $i$th row of the grid as described above, for $i=1..R$

      Next line: $M$ and $P$

      Next line: $M$ characters, representing Santa's moves

      Output

      $R$ lines: $C$ characters, representing the distribution of presents in the $i$th row of the grid as described above, for $i=1..R$

      Next line: The row and column of the last cell which Santa will visit

      Example

      Input:
      5 3
      .1.
      #F3
      #9.
      ..1
      ..<
      10 4
      RRDDDULUUU
      Output:
      .0.
      ..2
      .0.
      ..1
      ...
      2 2
       
      Explanation of Sample:

      After his first move, Santa ends up at coordinates (2,3) (the 3rd cell in the 2nd row), and deposits one present there. During his second move, he stays in that cell due to hitting the right wall of the house, and so he deposits another gift in the stocking.

      After 2 more seconds, he reaches the stocking at coordinates (4,3), and fills it up with a present. He returns to this cell 2 seconds later, but cannot put his last gift in the stocking because it's full.

      On his next move, Santa encounters a dog at coordinates (4,2). Before this, the dog had moved left to (5,1), rotated, moved up to (4,1), rotated, and moved to (4,2) after 6 seconds - when Santa arrives after 7 seconds, the dog is still in this cell, rotating to face downwards. As such, Santa loses his only remaining present to it.

      He next moves up to coordinates (3,2), but cannot deposit any presents in the stocking there because he has none. Finally, he moves up to the fireplace at coordinates (2,2), at which point he exits the house without ever making the final move up to (1,2).


      Added by:Jacob Plachta
      Date:2013-05-14
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      14949. HELPER

      Problem code: HELPER


      It's unbelievable, but an exam period has started at the OhWord University. It's even more unbelievable, that Valera got all the tests before the exam period for excellent work during the term. As now he's free, he wants to earn money by solving problems for his groupmates. He's made a list of subjects that he can help with. Having spoken with n of his groupmates, Valera found out the following information about them: what subject each of them passes, time of the exam and sum of money that each person is ready to pay for Valera's help.

      Having this data, Valera's decided to draw up a timetable, according to which he will solve problems for his groupmates. For sure, Valera can't solve problems round the clock, that's why he's found for himself an optimum order of day and plans to stick to it during the whole exam period. Valera assigned time segments for sleep, breakfast, lunch and dinner. The rest of the time he can work.

      Obviously, Valera can help a student with some subject, only if this subject is on the list. It so happenes, that all the students, to whom Valera spoke, have different, but one-type problems. Valera can solve any problem of subject listi in ti minutes.

      Moreover, if Valera starts working at some problem, he can break off only for sleep or meals, but he can't start a new problem, not having finished the current one. Having solved the problem, Valera can send it instantly to the corresponding student via the Internet.

      If this student's exam hasn't started yet, he can make a crib, use it to pass the exam successfully, and pay Valera the promised sum. Since Valera has little time, he asks you to write a program that finds the order of solving problems, which can bring Valera maximum profit.

      Input

      The first line contains integers m, n, k (1 ≤ m, n ≤ 100, 1 ≤ k ≤ 30) — amount of subjects on the list, amount of Valera's potential employers and the duration of the exam period in days.

      The following m lines contain the names of subjects listi (listi is a non-empty string of at most 32 characters, consisting of lower case Latin letters). It's guaranteed that no two subjects are the same.

      The (m + 2)-th line contains m integers ti (1 ≤ ti ≤ 1000) — time in minutes that Valera spends to solve problems of the i-th subject. Then follow four lines, containing time segments for sleep, breakfast, lunch and dinner correspondingly.

      Each line is in format H1:M1-H2:M2, where 00 ≤  H1, H2  ≤ 23, 00 ≤  M1, M2  ≤ 59. Time H1:M1 stands for the first minute of some Valera's action, and time H2:M2 stands for the last minute of this action. No two time segments cross. It's guaranteed that Valera goes to bed not before midnight, gets up earlier than he has breakfast, finishes his breakfast before lunch, finishes his lunch before dinner, and finishes his dinner before midnight. All these actions last less than a day, but not less than one minute. Time of the beginning and time of the ending of each action are within one and the same day. But it's possible that Valera has no time for solving problems.

      Then follow n lines, each containing the description of students. For each student the following is known: his exam subject si (si is a non-empty string of at most 32 characters, consisting of lower case Latin letters), index of the exam day di (1 ≤ di ≤ k), the exam time timei, and sum of money ci (0 ≤ ci ≤ 106, ci — integer) that he's ready to pay for Valera's help. Exam time timei is in the format HH:MM, where 00 ≤  HH  ≤ 23, 00 ≤  MM  ≤ 59. Valera will get money, if he finishes to solve the problem strictly before the corresponding student's exam begins.

      Output

      In the first line output the maximum profit that Valera can get. The second line should contain number p — amount of problems that Valera is to solve. In the following p lines output the order of solving problems in chronological order in the following format: index of a student, to whom Valera is to help; index of the day, when Valera should start the problem; time, when Valera should start the problem (the first minute of his work); index of the day, when Valera should finish the problem; time, when Valera should finish the problem (the last minute of his work). To understand the output format better, study the sample tests.

      Sample tests

      Input
      3 3 4
      calculus
      algebra
      history
      58 23 15
      00:00-08:15
      08:20-08:35
      09:30-10:25
      19:00-19:45
      calculus 1 09:36 100
      english 4 21:15 5000
      history 1 19:50 50
      Output
      150
      2
      1 1 08:16 1 09:29
      3 1 10:26 1 10:40
      Input
      2 2 1
      matan
      codeforces
      1 2
      00:00-08:00
      09:00-09:00
      12:00-12:00
      18:00-18:00
      codeforces 1 08:04 2
      matan 1 08:02 1
      Output
      3
      2
      2 1 08:01 1 08:01
      1 1 08:02 1 08:03
      Input
      2 2 1
      matan
      codeforces
      2 2
      00:00-08:00
      09:00-09:00
      12:00-12:00
      18:00-18:00
      codeforces 1 08:04 2
      matan 1 08:03 1
      Output
      2
      1
      1 1 08:01 1 08:02

      Added by:Shivam Mishra
      Date:2013-05-15
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14955. Dancing Cows

      Problem code: DCOWS


      It's the spring dance and, in a rare occurrence, the N (1 ≤ N ≤ 5000) bulls have been invited to dance with the M (N < M ≤ 5000) cows (as long as they stay on their very best behavior).

      Farmer John, almost obsessive-compulsive in his organization of dances, wants the spectacle to be as visually attractive as possible. Thus, he wants to pair up the N bulls with cow partners such that the total of all the magnitudes of differences in height is minimized. Bulls have heights B_i (1 ≤ B_i ≤ 1,000,000) and cows have height C_i (1 ≤ C_i ≤ 1,000,000). Of course, some cows will be unmatched since N-M of them will have no partners; ignore their heights.

      INPUT FORMAT:

      * Line 1: Two space-separated integers: N and M.
      * Lines 2..N+1: Line i+1 contains a single integer: B_i.
      * Lines N+2..M+N+1: Line i+N+1 contains a single integer: C_i.

      OUTPUT FORMAT:

      * Line 1: A single integer that is the minimum of the sum of the absolute value of the height differences that can be achieved.

      SAMPLE INPUT :

      5 7
      10
      16
      12
      10
      13
      7
      17
      12
      10
      9
      6
      11
      

      SAMPLE OUTPUT :

      4
      

      INPUT DETAILS:

      Five bulls + seven cows with various heights:
         Bulls:   10 10 12 13 16
         Cows:    6 7 9 10 11 12 17
      

      OUTPUT DETAILS :

      Here is one way to achieve a total difference of 4:
         Bulls:        10 10 12 13 16
         Cows:    6 7   9 10 11 12 17
      


      Added by:Hussain Kara Fallah
      Date:2013-05-15
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict FORT HASK JAVA JS PAS fpc PAS gpc PERL PHP PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n RUBY
      Resource:USACO 2008 Gold









      SPOJ Problem Set (classical)

      14956. Submerging Islands

      Problem code: SUBMERGE

      Vice City is built over a group of islands, with bridges connecting them. As anyone in Vice City knows, the biggest fear of vice-citiers is that some day the islands will submerge. The big problem with this is that once the islands submerge, some of the other islands could get disconnected. You have been hired by the mayor of Vice city to tell him how many islands, when submerged, will disconnect parts of Vice City. You should know that initially all the islands of the city are connected.

      Input

      The input will consist of a series of test cases. Each test case will start with the number N (1 ≤ N ≤ 10^4) of islands, and the number M of bridges (1 ≤ M ≤ 10^5). Following there will be M lines each describing a bridge. Each of these M lines will contain two integers Ui, Vi (1 ≤ Ui,Vi ≤ N), indicating that there is a bridge connecting islands Ui and Vi. The input ends with a case where N = M = 0.

      Output

      For each case on the input you must print a line indicating the number of islands that, when submerged, will disconnect parts of the city.

      Example

      Input:
      3 3
      1 2
      2 3
      1 3
      6 8
      1 3
      6 1
      6 3
      4 1
      6 4
      5 2
      3 2
      3 5
      0 0
      
      
      Output:
      0
      1
      

      Added by:Hector Navarro
      Date:2013-05-16
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:MiniMaraton 2013 - UCV









      SPOJ Problem Set (classical)

      14957. Chinese game

      Problem code: CHIGAME

      Little Mark went to China and learned an ancient chinese game dating from the 3rd century. In this game every player chooses two numbers A, B (all pairs of numbers B must be coprime). The players gather around in a circle. Initially each player puts A beans in front of the player on his left. At this point each player writes down on their notebook the number of beans he has in front of him. Now the game starts by rounds. On every round each player will place B beans in front of the player at his right. Then each player writes down on their notebook the number of beans in front of them. The rounds keep going until there is a number C that all players have written on their notebook. The winner is the player with more numbers written before C.

      For example, lets suppose there are three players, Mark, George and Mike. They choose the numbers 15 5, 17 8 and 16 7 respectively. Initially Mark would put 15 beans in front of Mike, George would put 11 beans in front of Mark and Mike would but 16 beans in front of George. Then everybody writes down the number in front of them (17,16 and 15). Now on each round Mark will put 5 beans in front of George, George will put 8 beans in front of Mike, and Mike will put 7 beans in front of Mark. The following table summarizes the numbers written on each person’s notebook:

       

      Mark George Mike
      17 16 15
      24 21 23
      31 26 31
      38 31 39

      The last row of the table is the last round of the game, since the number 31 has already been written down by each player. So now the winner is George, since he has 3 numbers written before the 31.

      Your task is to print the amount of numbers that the winner wrote before the common number C showed up. Since the game can get quite boring, in all the games the winner will have less than 2^31 numbers written on his notebook.

      Input

      The input will begin with the number N of players (2<=N<=10). Following, there will be N lines, each containing a pair of numbers Ai, Bi (0<=A<=10^6, 2<=B<=10^2) indicating the numbers A and B for player i.

      The end of the input will be a case with N=0

      Output

      For each test case on the input you must print a line containing the amount of lines that the winner wrote before the common number C.

      Example

      Input:
      3
      15 5
      17 8
      16 7
      2
      1 2
      1 3
      0
      
      Output:
      3
      0

      Added by:Hector Navarro
      Date:2013-05-16
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:MiniMaraton 2013 - UCV









      SPOJ Problem Set (classical)

      14961. Maximum Girth

      Problem code: MAXGRITH

      In graph theory, the girth of a graph is the length of a shortest cycle contained in the graph. Can you find the maximum girth a graph with N-vertices and (N+1) edges could possible have?

      Since the answer could be large output the answer modulo 10^9+7.

      Input

      The first line contains single integer T - the number of test cases. Each of the next T lines contains a single integer N.

      Output

      For every test case output the maximum girth (modulo 10^9+7) in a seperate line.

      Example

      Input:
      3
      45
      3434
      5656565
      Output:
      30
      2290
      3771044

      Constraints:

      1 <= T <= 1000
      1 <= N <= 10^18



      Added by:.:: Debanjan ::.
      Date:2013-05-16
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      14971. The Foxens Treasure

      Problem code: UOFTAB

      There are $N$ ($1 \leq N \leq 4$) Foxen guarding a certain valuable treasure, which you'd love to get your hands on. The problem is, the Foxen certainly aren't about to allow that - at least, not while they're awake.

      Fortunately, through careful observation, you've seen that each Fox has a regular sleep cycle. In particular, the $i$th Fox stays awake for $A_i$ ($1 \leq A_i \leq 23$) hours, then sleeps for $S_i$ ($1 \leq S_i \leq 23$) hours, repeating this pattern indefinitely ($2 \leq A_i+S_i \leq 24$). At the start of your treasure-nabbing attempt, the $i$th Fox is exactly $O_i$ ($0 \leq O_i < A_i+S_i$) hours into its cycle.

      There are $T$ ($1 \leq T \leq 20$) scenarios as described above. For each one, you'd like to determine how soon all of the Foxen will be simultaneously asleep, allowing you to grab their treasure, or if this will simply never happen.

      Input

      First line: 1 integer, $T$

      For each scenario:

      First line: 1 integer, $N$

      Next $N$ lines: 3 integers, $A_i$, $S_i$, and $O_i$, for $i = 1..N$

      Output

      For each scenario:

      1 integer, the minimum number of hours after the start to wait until all of the Foxen are asleep during the same hour. If this will never happen, output the string "Foxen are too powerful" (without quotes) instead.

      Example

      Input:
      2
      2
      2 1 2
      2 2 1
      3
      1 1 0
      1 1 0
      1 1 1
      Output:
      6
      Foxen are too powerful
      Explanation of Sample:

      In scenario 1, the following table illustrates the Foxen's sleeping cycles (with A representing being awake, S representing sleep, and a bold letter representing the start of a sleep cycle):

      As can be seen, the first hour during which both Foxen are asleep is 6 hours after the start.

      In scenario 2, the first 2 Foxen are always awake and asleep at the same times. However, the third Fox's schedule is exactly flipped, which means that it will never be asleep at the same time as the others.


      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14972. Foxhole

      Problem code: UOFTAC


      Everyone knows that Foxen love digging holes. You've been observing one Fox in particular, who's preparing to burrow underground in search of treasures. When viewed from the side, as a cross-section, his digging site can be represented as a grid of cells, $H$ ($1 \leq H \leq 100$) deep and $W$ ($1 \leq W \leq 100$) across. Every cell contains either dirt (represented by "D"), stone ("S"), empty space ("E"), or a treasure ("T"). The surface can also be traversed, effectively giving the grid an additional row of empty cells above the topmost row.

      The Fox starts immediately above the top-left cell, which is guaranteed to not be empty. It has a set of $N$ ($1 \leq N \leq 1000$) actions in mind before it starts its dig, which it will execute in order. Each action consists of moving either left (represented by "L"), right ("R"), or down ("D") by one cell. If the cell that the Fox would move to contains stone, or is beyond the boundaries of the grid in any direction, it will skip that action. If it enters a cell with a previously-uncollected treasure, it will collect it, leaving the cell empty. If the cell immediately below the Fox is ever empty, it will fall down until this is no longer the case. Note that collecting treasure occurs before falling, and that the Fox stops falling if it hits the bottom of the grid.

      There are $T$ ($1 \leq T \leq 20$) scenarios as described above. For each one, you'd like to determine how many treasures the Fox will collect throughout the course of its dig.

      Input

      First line: 1 integer, $T$

      For each scenario:

      First line: 3 integers, $H$, $W$, and $N$

      Next $H$ lines: $W$ characters, representing the $i$th row of the grid, for $i = 1..H$

      Next $N$ lines: 1 character, representing the $i$th action, for $i = 1..N$

      Output

      For each scenario:

      1 integer, the number of treasures collected in total.

      Example

      Input:
      2
      2 3 4
      DDD
      TES
      R
      D
      R
      L
      3 2 6
      TE
      TE
      ET
      R
      R
      L
      R
      L
      R
      Output:
      1
      2
      Explanation of Sample:

      In the first scenario, the Fox moves right along the surface, then digs down to the first row. As the cell below it is empty, it immediately falls to the 2nd row. It ignores its next action, as the cell to its right is filled with stone, and finally moves left to claim a treasure.

      In the second scenario, it moves to the right and promptly falls all the way down to the 2nd row. Because the Fox is already in the rightmost column, it ignores the action to move right. It then moves left, collects the treasure there, and then falls to the bottom row. Finally, it moves back and forth between the bottom-left and bottom-right cells twice - however, it only collects the treasure in the latter cell the first time.


      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14973. Reverse Fox Hunt

      Problem code: UOFTAD


      A family of Foxen, having caught a pesky farmer on their property, want to teach him a lesson. Of course, they're not cruel - they plan to simply prevent him from returning home to his farm, until he's willing to beg them for mercy.

      The Foxen and the farmer live in a forest, which may be viewed as a grid of cells, with $H$ ($1 \leq H \leq 6$) rows of $W$ ($1 \leq W \leq 6$) cells each. Each cell contains either grass (represented by "G"), trees ("T"), the farmer ("F"), or his farm ("H"). The farmer may repeatedly move up, down, left, or right to adjacent cells within the grid, provided that they are not blocked by trees. Due to his overconfidence in exploring the forest, the farmer is not directly adjacent to his farm.

      The family of Foxen can also block the farmer's way, by standing in grass-filled cells. He would not, of course, dare to enter a cell with a Fox in it. However, the Foxen do have better things to do, so they'd like to determine the minimum number of cells they must occupy in order to prevent the farmer from ever reaching his farm.

      There are $T$ ($1 \leq T \leq 20$) scenarios as described above. For each one, you'd like to answer the Foxen's question. Note that no Foxen might be necessary, if the trees already bar the farmer's way sufficiently.

      Input

      First line: 1 integer, $T$

      For each scenario:

      First line: 2 integers, $H$ and $W$

      Next $H$ lines: $W$ characters, representing the $i$th row of the grid, for $i = 1..H$

      Output

      For each scenario:

      1 integer, the minimum number of Foxen necessary to block the farmer.

      Example

      Input:
      2
      1 5
      FGTGH
      4 5
      GGGGG
      GFGTG
      GTTGH
      GGGGG
      Output:
      0
      2
       
      Explanation of Sample:

      In the first scenario, the farmer can already never reach his farm, so no Foxen are necessary.

      In the second scenario, one possible placement of two Foxen (each represented by an "X") is as follows:

      GGGGX
      GFGTG
      GTTGH
      GGXGG

      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14974. Foxling Feeding Frenzy

      Problem code: UOFTAE

      You've come across $N$ ($1 \leq N \leq 200$) adorable little Foxlings, and they're hungry! Luckily, you happen to have $M$ ($1 \leq M \leq 200$) crackers on hand, and everyone knows that Foxen love crackers! You'd like to distribute all of your crackers, without splitting any of them, among the Foxlings - but you have to be careful. Foxling $i$ must be fed at least $A_i$ crackers, or it will remain hungry, but no more than $B_i$ of them, or it will become hyper ($1 \leq A_i \leq B_i \leq 200$). You certainly don't want any hungry or hyper Foxlings on your hands, and you're curious as to how many ways this can be accomplished.

      There are $T$ ($1 \leq T \leq 100$) scenarios as described above. For each one, you'd like to determine the number of different distributions of your crackers that would satisfy all of the Foxlings, modulo $10^9+7$ (as this value can be quite large).

      Input

      First line: 1 integer, $T$

      For each scenario:

      First line: 2 integers, $N$ and $M$

      Next $N$ lines: 2 integers, $A_i$ and $B_i$, for $i = 1..N$

      Output

      For each scenario:

      Line 1: 1 integer, the number of valid cracker distributions modulo $10^9+7$

      Example

      Input:
      2
      2 5
      1 4
      2 6
      3 5
      2 2
      2 9
      2 3
      Output:
      3
      0
      Explanation of Sample:

      In the first scenario, you can give either 1, 2, or 3 crackers to the first Foxling, and the remaining 4, 3, or 2 (respectively) to the second.

      In the second scenario, each Foxling must receive at least 2 crackers, while you only have 5 to give out, so you have no valid options.


      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14975. Foxic Expressions

      Problem code: UOFTAF

      Let's talk about some definitions, shall we?

      An uppercase letter is a character between "A'' and "Z'', inclusive. You knew that.

      A string is a sequence of characters. You probably knew that.

      A Foxic letter is a superior uppercase letter - namely, one of "F", "O", or "X". You probably didn't know that.

      A Foxic string is a superior string, consisting only of Foxic letters. You didn't know that.

      Finally, a Foxic expression is a special string, with each of its characters being either a Foxic letter, or an "n" immediately following a Foxic letter. A Foxic expression can be translated into a Foxic string by a three-step process. First, up to one character can be added, removed, or modified, provided that the resulting string is still a valid Foxic expression. Next, every Foxic letter immediately preceding an "n" is replaced by zero or more occurrences of that same letter. Finally, each "n" is removed. You most certainly did not know that.

      There are $T$ ($1 \leq T \leq 100$) scenarios to consider, as described above. In each scenario, given a Foxic string $S$ of length $N$ ($1 \leq N \leq 100$) and a Foxic expression $E$ of length $M$ ($1 \leq M \leq 100$), you'd like to determine whether or not $E$ can be translated into $S$.

      Input

      Line 1: 1 integer, $T$

      For each scenario:

      Line 1: 1 integer, $N$

      Line 2: 1 string, $S$

      Line 3: 1 integer, $M$

      Line 4: 1 string, $E$

      Output

      For each scenario:

      The string "Yes" (without quotes) if $E$ can be translated into $S$, or "No" otherwise.

      Example

      Input:
      2
      5
      OOOFO
      7
      OXnFOXn
      3
      FOX
      7
      OFnOXnO
      Output:
      Yes
      No
      Explanation of Sample:

      In the first scenario, one possible course of action is to erase the second character of $E$, leaving the Foxic expression "OnFOXn". Next, we may choose to replace the first "O" with three copies of "O", and the remaining "X" with zero occurrences of "X", since each of these precedes an "n" - this yields the string "OOOnFOn". Finally, after removing each "n", we are left with "OOOFO", which matches $S$. Replacing the second character with an "O" would have also been possible.

      In the second scenario, it is impossible to translate $E$ into $S$ through any valid steps.


      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14977. Attack of the Bloons

      Problem code: UOFTBB

      The Bloons (not to be confused with balloons) are attacking! They are attempting to navigate your course of $L$ ($1 \leq L \leq 1000$) cells, laid out in a row and numbered from $1$ to $L$. You don't know what they'll do to you if they manage reach the end, and you don't want to find out! To that end, you've constructed some defensive towers along the course. You might say that this is a Bloons Tower Defense.

      There are $N$ ($1 \leq N \leq 1000$) towers ready to take out any Bloons that get close. The $i$th tower is located next to cell $C_i$ ($1 \leq C_i \leq L$), and can launch darts at any Bloons that are no more than $R_i$ ($0 \leq R_i \leq 1000$) cells away - that is, Bloons in cells $C_i-R_i$ to $C_i+R_i$, inclusive. Every second, it will do $D_i$ ($1 \leq D_i \leq 10^9$) HP worth of damage to any Bloons in this range.

      $M$ ($1 \leq M \leq 1000$) Bloons will attempt to float through your course, one after another. The $i$th Bloon begins with $H_i$ ($1 \leq H_i \leq 10^9$) HP, and will pop as soon as it has taken at least that much damage in total. Each Bloon starts in cell 1, and moves along the course at a speed of 1 cell per second. If a Bloon moves past cell $L$, it safely exits the course and can no longer be popped.

      There are $T$ ($1 \leq T \leq 20$) scenarios as described above. For each, you'd like to determine how far along the course each of the $M$ Bloons will make it.

      Input

      First line: 1 integer, $T$

      For each scenario:

      First line: 2 integers, $L$ and $N$

      Next $N$ lines: 3 integers, $C_i$, $R_i$, and $D_i$, for $i = 1..N$

      Next line: 1 integer, $M$

      Next $M$ lines: 1 integer, $H_i$, for $i = 1..M$

      Output

      For each scenario:

      $M$ lines: If the $i$th Bloon will survive the course, the string "Bloon leakage" (without quotes) - otherwise, 1 integer, the furthest cell which the $i$th Bloon will reach, for $i = 1..M$

      Example

      Input:
      1
      10 3
      3 3 1
      4 0 4
      10 2 2
      4
      1
      20
      9
      11
      Output:
      1
      Bloon leakage
      5
      8
      Explanation of Sample:

      The following diagram illustrates which cells each tower can hit:

      The first Bloon, having only 1 HP, will go down to the first tower in cell 1.

      The second Bloon will manage to clear the course, surviving past cell 10 with 4 HP remaining.

      The third Bloon will lose its final HP while at cell 5, having taken 5 damage from the first tower, and 4 from the second.

      The final Bloon will survive past cell 6 with 1 HP remaining, but will then go down at cell 8 when it takes 2 damage from the third tower.


      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14978. Homemade Asteroids

      Problem code: UOFTBC

      Pew pew pew!

      Everyone loves Asteroids, the classic arcade game involving senselessly blasting asteroids into submission with a spaceship. In fact, you love it so much that you built your very own version to play at home! Unfortunately, it sucks.

      Your version of the game is played on a 2D plane, containing your ship (a dot at coordinates ($X_S$, $Y_S$)) and $N$ ($1 \leq N \leq 1000$) stationary, triangular, positive-area asteroids. The $i$th asteroid has vertices at coordinates ($X_{Ai}$, $Y_{Ai}$), ($X_{Bi}$, $Y_{Bi}$), and ($X_{Ci}$, $Y_{Ci}$). All coordinates in the input are integers with absolute values no greater than $10^9$, and no two objects occupy any of the same space (even on their edges or vertices).

      Your game only permits you to fire a single missile, which travels in a straight line, destroying every asteroid that it comes in contact with (even on its edges or vertices). However, it doesn't exactly move very smoothly - instead, it starts at your ship at frame 0, and after every frame, its x-coordinate increases by $X_D$, and its y-coordinate by $Y_D$. These variables also have absolute values no greater than $10^9$, and at least one of them is guaranteed to be non-zero. After frame $F$ ($1 \leq F \leq 1000$), the missile simply disappears.

      There are $T$ ($1 \leq T \leq 20$) scenarios as described above. For each, you'd like to predict how many different asteroids your missile will be able to take out before frame $F+1$.

      Input

      First line: 1 integer, $T$

      For each scenario:

      First line: 2 integers, $N$ and $F$

      Second line: 4 integers, $X_S$, $Y_S$, $X_D$, and $Y_D$

      Next $N$ lines: 6 integers, $X_{Ai}$, $Y_{Ai}$, $X_{Bi}$, $Y_{Bi}$, $X_{Ci}$, and $Y_{Ci}$, for $i = 1..N$

      Output

      For each scenario:

      1 integer, the number of asteroids that will be destroyed by the missile

      Example

      Input:
      1
      4 4
      4 17 4 -2
      5 16 15 18 12 9
      16 13 13 11 14 10
      20 9 20 7 18 7
      22 5 23 11 27 6
      Output:
      2
      Explanation of Sample:

      The following grid shows the layout of the game, with your ship marked with an "S", and the missile's location at each frame marked with that frame's number:

      As can be seen, the missile destroys the first asteroid during frame 1, and then the third asteroid during frame 4. It does not destroy the second asteroid, even though its line of fire goes through it, as it does not intersect the asteroid during any of the frames. It also doesn't destroy the last asteroid, as it stops travelling after frame 4.


      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14979. Diablo Bot

      Problem code: UOFTBD

      Maybe you've played Diablo? There are three different character classes: Noobs, Suckers, and Pros. Noobs don't know anything about the game. Suckers think they know how to play. Pros know that the goal of the game is to write a script that will farm for valuable items that they can turn around and sell to Suckers on the black market. Obviously Pros would sell to Noobs if they could, but Noobs don't even know how to buy items.

      An obvious piece of preqrequisite information for making such a bot is knowing what sorts of items are worth picking up. There are Normal, Magic, Rare, and Set items:

      • Set items always belong to some famous dead person, so they always begin with a word that ends in "'s" (e.g. Andrew's). No other items are special enough to begin this way.
      • Rare items always have names that are two words long.
      • Magic items always have names that are between two and four words long, inclusive. If, and only if, a Magic item has more than two words in its name, then the last two words are "of [something]" (e.g. of Doom).
      • If the first word is "Damaged", the item is a Normal item. Furthermore, any item that could not possibly be Magic, Rare, or Set must also be Normal. No other items are Normal.
      • You may not have played Diablo, but hopefully you still know that a "word" is a maximal substring of non-space characters. Also, letter case is irrelevant.

      You have a list of $N$ ($1 \leq N \leq 1000$) item names, and you need to be able to classify these items as accurately as possible. It may not be possible to assign a unique type to each item, but as long as it's not Normal, surely you'll want it. Every item name is a string of no more than 100 characters, containing only alphabetic characters, spaces, and apostrophes. Every name begins and ends with a non-space character.

      Input

      First line: 1 integer, $N$

      Next $N$ lines: The name of the $i$th item, for $i = 1..N$

      Output

      $N$ lines: The type of the $i$th item (one of "Normal", "Set", "Magic", or "Rare"), or "Not sure, take anyways" (without quotes) if the item's type cannot be determined, but is known not to be Normal, for $i = 1..N$

      Example

      Input:
      7
      Somebody's Something of Whatever
      stone of jordan
      Wirt's Leg
      FLAMING TURNIP
      Damaged Goods
      Sword
      Fish shaped volatile organic compounds
      Output:
      Set
      Magic
      Set
      Not sure, take anyways
      Normal
      Normal
      Normal
       
      Explanation of Sample:

      The first and third items begin with possessives, so they must be Set items. The second item is three words long, and ends in "of [something]" so it must be Magic. The fourth item could be either Rare or Magic. The fifth item begins with "Damaged" so it's Normal. The last two items don't fit the descriptions of Set, Rare, or Magic, so they must be Normal also.


      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Written by Wesley May, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14980. MVP

      Problem code: UOFTBE

      It's down to the final match in the world's biggest SC2$^1$ tournament! You're the MVP$^2$ of MVP$^3$, and you're going up against MVP$^4$. There are $G$ ($1 \leq G \leq 20$) games in the series, with a winner decided after all have been played. Being a Protoss$^5$ player, you know the perfect way to win against that Terran$^6$ scum - with a cannon rush$^7$ every single game. Now you just have to execute it perfectly, by quickly getting your probe$^{10}$ to the correct location, and the prize money's sure to be yours.

      Each game will take place on a map which can be represented as a grid with $H$ ($2 \leq H \leq 1000$) rows of $W$ ($2 \leq W \leq 1000$) cells each. Each cell contains either empty space (represented by "E"), water ("W"), a unit ("U"), one of exactly two mineral patches ("M"), the probe ("P"), or the cannon rush site ("C"). Every second, your probe can move to a horizontally- or vertically-adjacent cell within the grid, with the goal of reaching the cannon rush site in as little time as possible. It can move freely from an empty cell to another empty cell (including its initial position and destination), while cells containing water or minerals may never be traversed.

      Normally, the probe may also not pass through units. However, it can if it is travelling towards a mineral patch. Specifically, the probe can only leave or enter a cell containing a unit if, for at least one of the two mineral patches on the map, the cell which the probe is entering is closer to that patch than the cell which the probe is leaving. Closeness is defined according to the minimum amount of time it would take to reach the mineral patch from the given cell, assuming the ability to pass through all units on the way.

      For each game, you'd like to determine whether or not you can be successful in your strategy, and, if so, how quickly you can execute the cannon rush. Of course, the point of this is to help prepare the correct BM$^{11}$ for the end of the game.

      Input

      First line: 1 integer, $G$

      For each game:

      First line: 2 integers, $H$ and $W$

      Next $H$ lines: $W$ characters, representing the $i$th row of the map, for $i = 1..H$

      Output

      For each game:

      The BM to be typed at the conclusion of the game. Namely, if the probe can reach the cannon rush site, the string "pwned you in $X$ seconds eZ$^{12}$, learn to play n00b$^{13}$" (without the quotes and glossary numbers), where $X$ is the minimum number of seconds for it to do so - otherwise, the string "terran so broken, apologize for playing this race".

      Example

      Input:
      2
      4 5
      WWEMC
      EEEUE
      PUWWU
      MEEEE
      5 4
      EWEM
      ECUE
      EEWE
      EWEE
      EUPM
      Output:
      pwned you in 8 seconds eZ, learn to play n00b
      terran so broken, apologize for playing this race
      Explanation of Sample:

      In the first scenario, the single shortest path that the probe may take to the cannon rush site is illustrated below:

      Note that the first move is made by going "towards" the top-right mineral patch, while the second move is made by going towards the bottom-left one.

      In the second scenario, the probe is unable to pass through any of the units, due to the locations of the mineral patches, and as such cannot reach its destination.

      Glossary of Terms:

      $^1$ SC2: StarCraft 2, by Blizzard Entertainment - a game of kings

      $^2$ MVP: Most valuable player

      $^3$ MVP: A top Korean SC2 team

      $^4$ MVP: A top Korean Terran player (who is not on the team MVP)

      $^5$ Protoss: The most pleasant race in SC2, which only nice people use

      $^6$ Terran: The most despicable race in SC2, which no decent human being would consider 

      $^7$ Cannon rush: The act of building proxy$^8$ cannons, a common type of cheese$^9$

      $^8$ Proxy: A structure made near or in your opponent's base, instead of your own

      $^9$ Cheese: A perfectly legitimate strategy which can allow you to win quickly, while leaving your opponent mad

      $^{10}$ Probe: A Protoss unit most useful for its ability to make cannons

      $^{11}$ BM: Customary parting words for your opponent, used to convey your respect for them

      $^{12}$ eZ: Easy

      $^{13}$ n00b: A player whose skill is somewhat lacking in calibre


      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14981. Light Cycling

      Problem code: UOFTBF

      Having been sucked into your father's secret computer through a projector in the back of his arcade (or something), you find yourself in the wonderful world of Tron! Here, you play games all day, and if you ever lose, you die.

      One such game involves you and an opponent driving around a flat grid on light cycles, which leave behind a permanent trail of...light...wherever they go. This grid can be modeled with the Cartesian plane, and is enclosed by a rectangle of impenetrable walls which ensure that the x-coordinate of each light cycle is always between $1$ and $10^{12}$, while its y-coordinate is between $1$ and $10^6$ (inclusive). Light cycles always stay on the grid lines, and move at a speed of 1 square per second.

      A match lasts $S$ ($1 \leq S \leq 10^{100}$) seconds. You start at coordinates ($X_A$, $Y_A$) and follow a set of $N_A$ ($1 \leq N_A \leq 10^5$) instructions, with your $i$th instruction consisting of moving $L_{Ai}$ squares in the direction given by the character $D_{Ai}$ (with "U", "D", "L", and "R" representing up, down, left, and right, respectively). Similarly, your opponent starts at coordinates ($X_B$, $Y_B$) and follows a set of $N_B$ ($1 \leq N_B \leq 10^5$) instructions, with their $i$th instruction described by $L_{Bi}$ and $D_{Bi}$. Of course, neither player's instructions will ever take them beyond the boundaries of the walls, and it will take each player exactly $S$ seconds to execute their instructions. Additionally, for each player, no instruction will have an equal or opposite direction to that of their previous instruction. Finally, if a grid point is ever visited more than once throughout the course of the match, it is guaranteed that one of the path segments intersecting there is passing directly through vertically, while the other is passing directly through horizontally (as such, this cannot happen at either player's starting or ending points).

      Whenever both light cycles reach the same grid point at the same time, or a light cycle hits an existing trail of light (in other words, a grid point which either light cycle had previously passed through), a collision occurs. Because you're just playing a practice match for now, neither player dies when this occurs, and, in fact, the collision is not counted in favour of either you or your opponent. Instead, for $T$ ($1 \leq T \leq 20$) scenarios as described above, you're simply interested in the number of collisions that will occur throughout each match.

      Input

      First line: 1 integer, $T$

      For each scenario:

      First line: 1 integer, $S$

      Next line: 3 integers, $X_A$, $Y_A$, and $N_A$

      Next $N_A$ lines: 1 character, $D_{Ai}$, and 1 integer, $L_{Ai}$, for $i = 1..N_A$

      Next line: 3 integers, $X_B$, $Y_B$, and $N_B$

      Next $N_B$ lines: 1 character, $D_{Bi}$, and 1 integer, $L_{Bi}$, for $i = 1..N_B$

      Output

      For each scenario:

      1 integer: The total number of collisions that will occur.

      Example

      Input:
      1
      12
      2 5 5
      R 4
      U 1
      L 1
      D 4
      L 2
      3 3 4
      U 3
      L 2
      D 2
      R 5
      Output:
      4
      Explanation of Sample:

      The following diagram illustrates the paths of the light cycles (yours drawn in solid lines, and your opponent's drawn in dotted ones), as well as all of the collision points (indicated with large dots):


      Added by:Jacob Plachta
      Date:2013-05-17
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2012 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      14991. Your Rank is Pure (EXTREME ver)

      Problem code: EGCJPURE


      Note: The problem description is same as GCJPURE, but with more higher constraints (to become more challenging), more strict time limit (to reject bad complexity), and more strict source limit (to reject hardcoded precomputation). Good Luck.

      Problem Description

      Pontius: You know, I like this number 127, I don't know why.
      Woland: Well, that is an object so pure. You know the prime numbers.
      Pontius: Surely I do. Those are the objects possessed by our ancient masters hundreds of years ago. Oh, yes, why then? 127 is indeed a prime number as I was told.
      Woland: Not... only... that. 127 is the 31st prime number; then, 31 is itself a prime, it is the 11th; and 11 is the 5th; 5 is the 3rd; 3, you know, is the second; and finally 2 is the 1st.
      Pontius: Heh, that is indeed... purely prime.

      Pontius: You know, I like this number 127, I don't know why.

      Woland: Well, that is an object so pure. You know the prime numbers.

      Pontius: Surely I do. Those are the objects possessed by our ancient masters hundreds of years ago. Oh, yes, why then? 127 is indeed a prime number as I was told.

      Woland: Not... only... that. 127 is the 31st prime number; then, 31 is itself a prime, it is the 11th; and 11 is the 5th; 5 is the 3rd; 3, you know, is the second; and finally 2 is the 1st.

      Pontius: Heh, that is indeed... purely prime.

      The game can be played on any subset S of positive integers. A number in S is considered pure with respect to S if, starting from it, you can continue taking its rank in S, and get a number that is also in S, until in finite steps you hit the number 1, which is not in S.

      When n is given, in how many ways you can pick S, a subset of {2, 3, ..., n}, so that n is pure, with respect to S? The answer might be a big number, you need to output it modulo 109+7.

      Input

      The first line of the input gives the number of test cases, T. T lines follow. Each contains a single integer n.

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the answer as described above.

      Constraints

      T<105

      2≤n≤105

      Note: This constraints was selected carefully

      Example

      Input:
      2
      5
      6
      
      Output:
      Case #1: 5
      Case #2: 8

       

      Other Info

      Sorry for slow language user, I've made an experiment and the result is if I set constraints that allow slow languages to be accepted with 'good' complexity O(f(n)), then the 'bad' complexity O(f(n)*log(n)) could be accepted too using fast language (Because slow language is ~80x slower than fast language). I don't want this happen. But don't feel so bad :-) I've made this tutorual problem that allow slow languages to be accepted (except maybe: PIKE).

      Time limit ~4× My Program top speed (25.53s using 1744B of C code).

      You can see my submission history and time record for this problem: here

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-05-21
      Time limit:100s
      Source limit:5000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Inspired by GCJPURE problem, but this is much harder









      SPOJ Problem Set (classical)

      15038. Yell Classico

      Problem code: CLASSICO


      The Old Yellers, the contestants of the old days of IIUC are going to have a football match with the current contestants. As the yellers are going to be the host of the match, it will be called 'Yell Classico'. As the yellers are always busy in yelling, oops, I mean programming, they have appointed you as the manager of their team. Now, as a manager of the Yeller team, you have to select 11 players for the match from N players.

      All the N players will stand in a line just before the match. Your task will be to select 11 players from them in such a way that, the player standing in front is as tall as possible. If there are more than one such team formations, do it in a way where the 2nd player is as tall as possible. If still there is a tie, choose the formation having tallest player in the 3rd position and so on. (Which means, until you can break the tie or reach the 11th position, keep looking in the next position).

      Note that,

      1. You don't have enough time to change the order in which players are standing.
      2. If you have tie even after reaching the 11th position, select from any of the tied formations.

      Players are quite same in their playing abilities, you don't need to bother about that.

      Input

      First line of input will contain the number of test cases, T<100.

      For each test case, there are two lines.

      The first line contain N (number of players, 1<N<2000).

      The second one is a line of N integers separated by spaces. The ith integer of this line will specify the height of the ith player. (Heights will not be greater than 109).

      Output

      For each test case output `Case X: ', (X is the case number, starting from 1). Then print the heights of the 11 selected players separated by spaces. If it's not possible to select exactly 11 players, then send the spectators home by printing `go home!' (Without quotations). See the sample output for exact formatting.

      Sample Input

      4
      15
      2 10 8 5 1 5 9 9 3 5 6 6 2 2 8
      11
      2 6 3 8 7 2 5 3 4 3 3
      4
      2 7 9 6
      12
      6 2 3 8 7 2 5 3 4 3 3 10

      Output for Sample Input

      Case 1: 10 8 9 9 3 5 6 6 2 2 8
      Case 2: 2 6 3 8 7 2 5 3 4 3 3
      Case 3: go home!
      Case 4: 6 3 8 7 2 5 3 4 3 3 10
      
      

      Problem Setter: Bidhan Roy



      Added by:Bidhan Roy ( বিধান )
      Date:2013-05-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem ( http://uva.onlinejudge.org/external/125/12580.html )









      SPOJ Problem Set (classical)

      15060. Elegant Diamond

      Problem code: GCJ102A


      Problem

      The king has hired you to make him an elegant diamond. An elegant diamond is a two-dimensional object made out of digits that's symmetric about a horizontal and a vertical axis. For example, the following four shapes are elegant diamonds:

         2       8      3     7
        3 3     8 8    2 2
       4 1 4     8      3
        3 3 
         2
      

      These three shapes are diamonds, but are not elegant:

        2       1        3
       1 1     1 2      1 1
        1     1 1 1    3 1 3
               2 1      1 1
                1        2
      

      These three shapes are not diamonds:

        1     2     8   8
       1 1   222      0
              2     00000
      

      The king will start by giving you a diamond, which may not be elegant. Your job is to make it elegant by enhancing it, adding digits on to make a bigger diamond. Because you don't want to spend too much money, you want to do it with as little cost as possible.

      Definitions

      A diamond of size k is 2k-1 lines of digits, 0-9, separated by single spaces, organized in the following way:

      • Line i (1 ≤ i ≤ k) contains k-i spaces, then i digits separated by single spaces.
      • Line i (k < i < 2k) contains i-k spaces, then 2k-i digits separated by single spaces.

      An elegant diamond of size k is a diamond of size k with the following two symmetry properties:

      • Horizontal symmetry: Let ci be the number of digits on line i. The jth digit on line i (where j=1 for the first digit) must be the same as the ci+1-jth digit.
      • Vertical symmetry: The jth digit on line i (where i=1 for the first line) must be the same as the jth digit on line 2k-i.

      A diamond of size k can be enhanced by adding digits to it. The result of enhancing a diamond of size k has the following properties:

      • The result is a diamond of size ≥ k.
      • The original diamond is part of the result. In other words, there exist some X and some Y such that, for all values of i and j such that the jth character of the ith line of the original is a digit (as opposed to a space), the j+Xth character on the i+Yth line of the result is also a digit and it's the same as the jth character on the ith line of the original.

      The cost of enhancing a diamond is equal to the number of digits in the result of the enhancement, minus the number of digits in the original diamond.

      Input

      The first line of the input gives the number of test cases, T. T test cases follow. Each test case consists of a single integer k in a line on its own, followed by a diamond of size k.

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the minimum cost required to enhance the given diamond into an elegant diamond. If the diamond is already elegant, y=0.

      Limits

      1 ≤ T ≤ 100.

      Large dataset

      1 ≤ k ≤ 51.

      Sample


      Input
       

      Output
       
      4
      1
      0
      2
       1
      2 2
       1
      2
       1
      1 2
       1
      3
        1
       6 3
      9 5 5
       6 3
        1
      Case #1: 0
      Case #2: 0
      Case #3: 5
      Case #4: 7

      Explanation

      There are four cases. The first two cases start as elegant diamonds of size 1 and 2, respectively, and don't need to be enhanced; so the cost is 0. The third case can be enhanced to look like:

        3
       1 1
      1 2 1
       1 1
        3
      

      There are several possible enhancements, but this is one with the lowest possible cost, which is 5. In the fourth case we can enhance the diamond into the following elegant diamond:

         9
        1 1
       6 3 6
      9 5 5 9
       6 3 6
        1 1
         9
      

      ...for a cost of 7.


      Added by:Shafaet
      Date:2013-05-29
      Time limit:20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Google Codejam 2010 Round 2









      SPOJ Problem Set (classical)

      15061. World Cup 2010

      Problem code: GCJ102B


      Problem

      After four years, it is the World Cup time again and Varva is on his way to South Africa, just in time to catch the second stage of the tournament.

      In the second stage (also called the knockout stage), each match always has a winner; the winning team proceeds to the next round while the losing team is eliminated from the tournament. There are 2P teams competing in this stage, identified with integers from 0 to 2P - 1. The knockout stage consists of P rounds. In each round, each remaining team plays exactly one match. The exact pairs and the order of matches are determined by successively choosing two remaining teams with lowest identifiers and pairing them in a match. After all matches in one round are finished, the next round starts.



         

      In order to help him decide which matches to see, Varva has compiled a list of constraints based on how much he likes a particular team. Specifically, for each team i he is willing to miss at most M[i] matches the team plays in the tournament.

      Varva needs to buy a set of tickets that will guarantee that his preferences are satisfied, regardless of how the matches turn out. Other than that, he just wants to spend as little money as possible. Your goal is to find the minimal amount of money he needs to spend on the tickets.

      Tickets for the matches need to be purchased in advance (before the tournament starts) and the ticket price for each match is known. Note that, in the small input, ticket prices for all matches will be equal, while in the large input, they may be different.

      Example

      A sample tournament schedule along with the ticket prices is given in the figure above. Suppose that the constraints are given by the array M = {1, 2, 3, 2, 1, 0, 1, 3}, the optimal strategy is as follows: Since we can't miss any games of team 5, we'll need to spend 50, 400, and 800 to buy tickets to all the matches team 5 may play in. Now, the constrains for the other teams are also satisfied by these tickets, except for team 0. The best option to fix this is to buy the ticket for team 0's first round match, spending another 100, bringing the total to 1350.

      Input

      The first line of the input gives the number of test cases, T. T test cases follow. Each case starts with a line containing a single integer P. The next line contains 2P integers -- the constraints M[0], ..., M[2P-1].

       

      The following block of P lines contains the ticket prices for all matches: the first line of the block contains 2P-1 integers -- ticket prices for first round matches, the second line of the block contains 2P-2 integers -- ticket prices for second round matches, etc. The last of the P lines contains a single integer -- ticket price for the final match of the World Cup. The prices are listed in the order the matches are played.

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the minimal amount of money Varva needs to spend on tickets as described above.

      Limits

      1 ≤ T ≤ 50
      1 ≤ P ≤ 10
      Each element of M is an integer between 0 and P, inclusive.

      Large dataset

      All the prices are integers between 0 and 100000, inclusive.

      Sample


      Input
       

      Output
       
      2
      2
      1 1 0 1
      1 1
      1
      3
      1 2 3 2 1 0 1 3
      100 150 50 90
      500 400
      800
      Case #1: 2
      Case #2: 1350

      Added by:Shafaet
      Date:2013-05-29
      Time limit:20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Google Codejam 2010 Round 2









      SPOJ Problem Set (classical)

      15062. Bacteria

      Problem code: GCJ102C


      Problem

      A number of bacteria lie on an infinite grid of cells, each bacterium in its own cell.

      Each second, the following transformations occur (all simultaneously):

      1. If a bacterium has no neighbor to its north and no neighbor to its west, then it will die.
      2. If a cell has no bacterium in it, but there are bacteria in the neighboring cells to the north and to the west, then a new bacterium will be born in that cell.

      Upon examining the grid, you note that there are a positive, finite number of bacteria in one or more rectangular regions of cells.

      Determine how many seconds will pass before all the bacteria die.

      Here is an example of a grid that starts with 6 cells containing bacteria, and takes 6 seconds for all the bacteria to die. '1's represent cells with bacteria, and '0's represent cells without bacteria.

       

      000010
      011100
      010000
      010000
      000000
      
      000000
      001110
      011000
      010000
      000000
      
      000000
      000110
      001100
      011000
      000000
      
      000000
      000010
      000110
      001100
      000000
      
      000000
      000000
      000010
      000110
      000000
      
      000000
      000000
      000000
      000010
      000000
      
      000000
      000000
      000000
      000000
      000000
      

      Input

      The input consists of:

      • One line containing C, the number of test cases.

      Then for each test case:

      • One line containing R, the number of rectangles of cells that initially contain bacteria.
      • R lines containing four space-separated integers X1 Y1 X2 Y2. This indicates that all the cells with X coordinate between X1 and X2, inclusive, and Y coordinate between Y1 and Y2, inclusive, contain bacteria.

      The rectangles may overlap.

      North is in the direction of decreasing Y coordinate.
      West is in the direction of decreasing X coordinate.

      Output

      For each test case, output one line containing "Case #N: T", where N is the case number (starting from 1), and T is the number of seconds until the bacteria all die.

      Limits

      1 ≤ C ≤ 100.

      Large dataset

      1 ≤ R ≤ 1000
      1 ≤ X1X2 ≤ 1000000
      1 ≤ Y1Y2 ≤ 1000000

      The number of cells initially containing bacteria will be at most 1000000.

      Sample


      Input
       

      Output
       
      1
      3
      5 1 5 1
      2 2 4 2
      2 3 2 4
      Case #1: 6

      Added by:Shafaet
      Date:2013-05-29
      Time limit:30s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Google Codejam 2010 Round 2









      SPOJ Problem Set (classical)

      15073. Team Slide Treasure Hunt Race

      Problem code: SLIDE


      Alice and Bob are participating in an exciting new Olympic event, the Team Slide Treasure Hunt Race! This event takes place on a slide with various treasures on it, which is up to 10m wide and 10km long. Yes, that's kilometers.

      The slide can be represented as a grid of cells, with $N$ ($2 \leq N \leq 10^4$) rows and $M$ ($2 \leq M \leq 10$) columns. The rows are numbered $1, 2, \ldots, N$ from top to bottom, and the columns are numbered $1, 2, \ldots, M$ from left to right. The cell in row $i$ and column $j$ is referred to as cell ($i$, $j$), and contains a treasure with value $G_{i,j}$ ($1 \le G_{i,j} \le 10^5$).

      The two friends will each get to travel once down the slide, one after another. First, Alice will slide from the top-left corner of the slide (cell ($1$, $1$)) down to the bottom-left corner (cell ($N$, $1$)). Then, Bob will slide from the top-right corner (cell ($1$, $M$)) down to the bottom-right corner (cell ($N$, $M$)). Whenever a person moves in the slide, they move from their current row to the next row down, and they can also guide themselves left or right by one column if desired. This means that they can go from cell ($i$, $j$) to either cell ($i+1$, $j-1$), ($i+1$, $j$), or ($i+1$, $j+1$), as long as they don't exit the slide. Throughout the race, both Alice and Bob collect the treasure in each cell they slide through - this includes their respective starting and ending cells. However, if Bob goes through any cell that Alice has already visited, he can't collect the treasure in it again.

      Alice and Bob would like to determine a sliding plan to allow them to collect as much treasure as possible, and win the gold medal! They've asked you to determine the maximum total value of treasure that they can collect, out of all valid strategies.

      Input

      The first line of the input will contain two integers $N$ and $M$, separated by a space. Each of the next $N$ lines, for $i$ from $1$ to $N$, will contain the $M$ space-separated integers $G_{i,1} \,\,\, G_{i,2} \,\,\, \dots \,\,\, G_{i,M}$.

      Output

      Output one number on a line by itself: the maximum combined treasure value that Alice and Bob can collect.

      Example

      Input:
      5 4
      3 6 8 2
      5 2 4 3
      1 1 20 10
      1 1 20 10
      1 1 20 10
      Output:
      73
      Explanation of Sample:

      The single optimal sliding plan involves Alice sliding down-right, down-right, down-left, and down-left, followed by Bob sliding down-left, down-right, down-left, and down-right. The treasures collected are shown in bold on the following grid:

      Alice collects a total treasure value of $3+2+20+1+1=27$, while Bob collects $2+4+10+20+10=46$. Their total is then $27+46=73$.


      Added by:Jacob Plachta
      Date:2013-05-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      15074. Tourney

      Problem code: TOURNEY

      Don Cherry has been hired to run 24-hour coverage of a series of single-elimination, bracket-style, furniture disassembly tourneys (tournaments). Each competitor has a furniture disassembly skill level, an integer between $1$ and $10^9$. In every head-to-head match, the competitor with the larger skill level wins and moves on, while the other is eliminated from the tourney. It is guaranteed that, at any time, the skill levels of all competitors are distinct, so there are no ties.

      There are $2^N$ ($1 \leq N \leq 20$) competitor positions in the tourney tree, numbered $1, 2, \ldots, 2^N$ from left to right. In the first round, competitors 1 and 2 face off in a furniture disassembly race, as do competitors 3 and 4, etc. In each subsequent round, the winners of the first two matches from the previous round compete, as do the winners of the following two, etc. After $N$ rounds, a single winner remains. For example, when $N=2$, the tourney tree looks like this:

      where A represents the winner of the match between competitors 1 and 2, B represents the winner of the match between competitors 3 and 4, and C represents the winner of the match between A and B. The winner of this tourney is C.

      Because of sponsorship contracts, some competitors will be replaced over time. After any new person comes in, a new tourney is held.

      In order to help Don Cherry, you must write a program to compute certain tourney statistics at various points in time, given a sequence of $M$ ($1 \leq M \leq 10^6$) commands - see the input format below.

      Input

      The first line of input contains two integers, $N$ and $M$.

      The next $2^N$ lines, for $i$ from $1$ to $2^N$, each contain one integer $S_i$, indicating the skill level of the initial competitor at position $i$ in the tourney tree.

      Each of the following $M$ lines will be a command in one of three formats:

      • "R $i$ $s$" means that the competitor at position $i$ is removed, and replaced with a new one with skill level $s$. A new tourney should then be held.
      • "W" means that your program should determine who won the current tourney. Print out the position $i$ (between $1$ and $2^N$) of this competitor.
      • "S $i$" means that your program should print out the number of rounds that the competitor at position $i$ won in the current tourney.

      Output

      For each "W" or "S $i$" command in the input, print out the corresponding integer on a line by itself.

      Example

      Input:
      2 8
      30
      20
      10
      40
      S 1
      W
      R 4 9
      S 4
      W
      R 2 35
      S 2
      W
      Output:
      1
      4
      0
      1
      2
      2
      Explanation of Sample:

      The results of the initial tourney are as follows:

      As can be seen, competitor 1 wins 1 match, and competitor 4 wins the entire tourney. After this, competitor 4 is replaced by a new competitor with skill level 9. As can be seen below, this causes a different outcome for the tourney held after the third command:

      Finally, the state of the tourney tree after the next competitor replacement (caused by the sixth command) is:


      Added by:Jacob Plachta
      Date:2013-05-30
      Time limit:8s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2013 CCC Stage 2









      SPOJ Problem Set (classical)

      15075. A Romantic Dinner Outing

      Problem code: RDINNER


      Brian the Computer Science Nerd is going on a date with his girlfriend, Anatevka! His romantic location of choice is a Chinese restaurant.

      At this restaurant, $N$ ($1 \leq N \leq 15$) different dishes are available, and Brian would like to order each one exactly once. The waiter will come to his table to take orders $N$ times - the $i$th time he comes will be $W_i$ ($1 \leq W_1 < W_2 < \dots < W_N \leq 10^9$) minutes after the start of the meal. He has quite a poor memory, so each time he comes by, Brian will have a chance to order exactly one new dish.

      Dish $i$ takes $T_i$ ($1 \leq T_i \leq 10^9$) minutes to prepare, which means that it will generally come exactly that many minutes after being ordered, delivered by a different waiter who will not take orders. However, meals are guaranteed to arrive in the same order in which they were ordered - this means that, if meal $i$ was ordered before meal $j$, but meal $j$ is ready before meal $i$, then meal $j$ will instead arrive at the same time as meal $i$.

      Now, Brian considers time spent waiting for the first meal after the start of the dinner, as well as for each subsequent meal after the previous one, to be idle time. Of course, these are the worst parts of the date, as they require actually engaging in conversation rather than consuming sustenance. In order to impress Anatevka with his optimal ordering skills, he'd like to minimize the length of the largest continuous stretch of idle time throughout the dinner.

      Input

      Line 1: 1 integer, $N$

      Line 2: $N$ integers, $W_{1..N}$

      Line 3: $N$ integers, $T_{1..N}$

      Output

      1 integer, the minimal length possible for the longest stretch of idle time throughout the meal, in minutes

      Example

      Input:
      3
      1 5 6
      4 2 3
      Output:
      4
      Explanation of Sample:

      Brian's optimal strategy is to order dish 3, then 2, then 1. These dishes will then arrive 4, 7, and 10 minutes into the dinner, respectively. The longest stretch of idle time is then 4 minutes long.

      As a further example, if Brian were to order dish 3, then 1, then 2, the last 2 dishes would both arrive 9 minutes into the dinner, with dish 2 being held up by dish 1.


      Added by:Jacob Plachta
      Date:2013-05-30
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      15076. A Romantic Movie Outing

      Problem code: RMOVIE

      Brian the Computer Science Nerd is going on a date with his girlfriend, Anatevka! His romantic location of choice is a movie theatre - but not an IMAX theatre, of course, as that would be far too expensive.

      This theatre has $10^9$ rows of $1000$ seats each, which are initially empty. The rows are numbered $1..10^9$ starting from the one closest to the screen, and the seats in each row are numbered $1..1000$ from left to right. Seat $c$ in row $r$ is denoted as seat ($r$, $c$). Seats in rows $1..L$ ($1 \leq L \leq 1000$) are considered to be "close" to the screen, while seats in further rows are considered to be "far".

      Over the course of $T$ ($1 \leq T \leq 500,000$) minutes before the movie starts, a number of events occur. During the $i$th minute, either a person enters and sits in the empty seat ($R_i$, $C_i$), the person sitting in the occupied seat ($R_i$, $C_i$) leaves, or Anatevka suggests that she and Brian take seats ($R_i$, $C_i$) and ($R_i$, $C_i+1$). The type of the $i$th event is represented by the character $E_i$, with $E_i =$ "E" indicating a person entering, $E_i =$ "L" indicating a person leaving, and $E_i =$ "S" indicating a seating suggestion. All seats involved in the events are valid seats inside the theatre, and every seat that Anatevka suggests will be "close", as she believes that they're the best.

      Every time Anatevka makes a suggestion, Brian must, of course, analyze its quality. If either of the two seats she suggests are already occupied, he should explain that her recommendation is invalid with a simple "No". Otherwise, he'd like to calculate the total inconvenience of both seats in such an arrangement. The inconvenience of sitting in seat ($r$, $c$) is the number of occupied seats in its field of vision (excluding itself). The field of vision of seat ($r$, $c$) includes all seats which are no further than it from seat ($1$, $c$) by Manhattan distance, as shown below (with the "S" representing a suggested seat, and an "F" representing a seat within its field of vision):

      After all of the events have taken place, the movie is about to start, and a final decision must be made on where to sit - and Brian will handle that. He concludes that seats that are "far" are clearly superior (as they offer a broader view of the screen), and he knows that the point of going to the movies is to have an optimal viewing experience, so selecting two adjacent seats is certainly not mandatory. As such, he'd like to determine the minimum total inconvenience for any two "far", unoccupied seats in the theatre. Note that, if one of the chosen seats is in the other's field of vision, this does not count towards its inconvenience - it's only determined by other people sitting in the theatre.

      Input

      First line: 2 integers, $L$ and $T$

      Next $T$ lines: 1 character, $E_i$, and 2 integers, $R_i$ and $C_i$, for $i = 1..T$

      Output

      1 line for each of Anatevka's suggestions: If the suggestion is invalid, the string "No" - otherwise, the total inconvenience of the two suggested seats

      Final line: The minimum total inconvenience of any pair of "far", unoccupied seats

      Example

      Input:
      3 7
      E 1 2
      E 2 5
      S 3 3
      E 2 3
      L 2 5
      S 1 3
      S 2 2
      Output:
      3
      0
      No
      0
      Explanation of Sample:

      When Anatevka makes her first suggestion, the front 3 rows and leftmost 5 columns of the theatre look as follows (where a "P" represents a person, and an "S" represents one of the suggested seats):

      The person sitting in seat ($1$, $2$) is in the field of vision of both suggested seats, while the person sitting in seat ($2$, $5$) is only in the way of the right one. As such, the total inconvenience of the two seats is $1+2=3$.

      The second suggestion is shown below:

      These two seats aren't obstructed by any people, so their total inconvenience is $0$. The final suggestion is invalid, as one of its two seats (seat ($2$, $3$)) is already occupied.

      Finally, Brian can easily select two "far" which each have inconvenience $0$, as the theatre has $10^9-3$ "far" rows with $1000$ seats each, and most are far from the two people setting in the theatre after the last event. For example, he might choose to take seat ($4$, $6$), while recommending that Anatevka enjoy the view from seat ($100$, $1000$).


      Added by:Jacob Plachta
      Date:2013-05-30
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2013 CCC Stage 2









      SPOJ Problem Set (classical)

      15086. Land Acquisition

      Problem code: ACQUIRE

      **********************************************************************
                                 GOLD PROBLEMS
      **********************************************************************
                        Three problems numbered 1 through 3
      **********************************************************************
      
      Problem 1: Land Acquisition [Paul Christiano, 2007]
      
      Farmer John is considering buying more land for the farm and has
      his eye on N (1 <= N <= 50,000) additional rectangular plots, each
      with integer dimensions (1 <= width_i <= 1,000,000; 1 <= length_i
      <= 1,000,000).
      
      If FJ wants to buy a single piece of land, the cost is $1/square
      unit, but savings are available for large purchases. He can buy
      any number of plots of land for a price in dollars that is the width
      of the widest plot times the length of the longest plot. Of course,
      land plots cannot be rotated, i.e., if Farmer John buys a 3x5 plot
      and a 5x3 plot in a group, he will pay 5x5=25.
      
      FJ wants to grow his farm as much as possible and desires all the
      plots of land. Being both clever and frugal, it dawns on him that
      he can purchase the land in successive groups, cleverly minimizing
      the total cost by grouping various plots that have advantageous
      width or length values.
      
      Given the number of plots for sale and the dimensions of each,
      determine the minimum amount for which Farmer John can purchase all
      
      PROBLEM NAME: acquire
      
      INPUT FORMAT:
      
      * Line 1: A single integer: N
      
      * Lines 2..N+1: Line i+1 describes plot i with two space-separated
              integers: width_i and length_i
      
      SAMPLE INPUT:
      
      4
      100 1
      15 15
      20 5
      1 100
      
      INPUT DETAILS:
      
      There are four plots for sale with dimensions as shown.
      
      OUTPUT FORMAT:
      
      * Line 1: The minimum amount necessary to buy all the plots.
      
      SAMPLE OUTPUT:
      
      500
      
      OUTPUT DETAILS:
      
      The first group contains a 100x1 plot and costs 100. The next group
      contains a 1x100 plot and costs 100. The last group contains both the 20x5
      plot and the 15x15 plot and costs 300. The total cost is 500, which is
      minimal.

      Added by:Hasan Jaddouh
      Date:2013-05-31
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:USACO Mar08









      SPOJ Problem Set (classical)

      15088. Ancient Aliens

      Problem code: BFDIV

      Everyone knows that our human ancestors relied on extraterrestrial beings to teach them about science and technology. After helping us build pyramids and chart the stars, our alien mentors decided we needed some time to grow in isolation, so they took some dolphins and left to colonise another planet. Just before leaving, though, they gave us instructions on how to contact them in case of an emergency, such as global warming, nuclear holocaust, or a shortage of fish. The intergalactic telephone they designed consisted of a large golden box powered by alien arc technology. It was entrusted to the United Anarchist Alliance, but was lost when they went to war with the Unified Anarchist League after unsuccessful negotiations to decide which name was more logical for anarchists to call themselves. It remained lost for several centuries at the bottom of a lake until renowned archaeologists Indiana Serkis and Meronym Spader discovered it by chance during a fishing trip. Upon opening the box and pressing the large red button they found inside, an ancient alien immediately appeared and asked them deep, probing questions to determine whether humanity had advanced to the point where the aliens could come back to Earth and chill with us. Among other things, the aliens asked Indiana what his favorite color was, and what the result would be if 38157917385 were divided by 53387519, expressed as quotient and remainder. Since mathematics was never Indiana’s or Meronym’s strong suit, they’ve asked you to write a program for them to perform such computations automatically. They have a computer with them that only understands one language, but they assure you that despite its simplicity the language is Turing complete and perfectly capable of computing the desired quantities efficiently.

      Note: You can use any programming language you want, as long as it is brainf**k.

      Input

      The first line contains an integer T (1 ≤ T ≤ 1000). Then follow T lines, each containing integers x (0 ≤ x ≤ 10^20) and y (1 ≤ y ≤ 10^20) separated by a single space. Each line, including the last, is terminated by a single newline (linefeed) character, which has ASCII value 10.

      Output

      T lines containing the quotient and remainder of x divided by y, separated by a space.

      Example

      Input:

      5
      0 42
      42 42
      123 45
      12 345
      10000 42
      

      Output:

      0 0
      1 0
      2 33
      0 12
      238 4
      

      Additional Info

      There are two randomly generated data sets, one with T=1000 and the other with T=500. The average number of digits in x is about 13.5, the average number of digits in y is about 8, and the probability that the quotient is nonzero is about 0.82.

      My solution at the time of publication has 1516 bytes (not golfed) and runs in 0.14s with 1.9M memory footprint.


      Added by:Mitch Schwartz
      Date:2013-06-01
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BF









      SPOJ Problem Set (classical)

      15089. Farmer Joe

      Problem code: BFMUL


      Farmer Joe is a strange fellow indeed. He owns a rare breed of cow that eats chocolate and produces chocolate milk, and each cow has exactly L legs. Lately, Joe has been suffering from sore feet, and his intuition tells him that it must be from the chocolate milk. The cows, he suspects, are in pain from stepping on sharp pebbles while crossing the road with chickens in their bare hooves. Naturally, they are transferring their pain karmically through the milk. So he has taken it upon himself to make proper hoofwear for all of them. As he lives at the top of an ivory tower, he finds it most convenient to count their heads. (Each cow has exactly one head.) Joe would like to know how many shoes he must make given that he has counted H heads, and in fact he wrote a program for just this purpose but can’t seem to find it. The program is written for a special computer that he constructed while he was writing his dissertation on Turing machines. He has asked for your help in replacing his program. Please help him quickly, so his cows can suffer as little as possible.

      Note: You can use any programming language you want, as long as it is brainf**k.

      Input

      The first line contains an integer T (1 ≤ T ≤ 1000). Then follow T lines, each containing integers L and H (0 ≤ L,H ≤ 10^20) separated by a single space. Each line, including the last, is terminated by a single newline (linefeed) character, which has ASCII value 10.

      Output

      T lines containing the number of shoes Farmer Joe must make.

      Example

      Input:

      5
      0 0
      0 42
      42 0
      42 42
      12345 67890
      

      Output:

      0
      0
      0
      1764
      838102050
      

      Additional Info

      There are two randomly generated data sets, one with T=1000 and the other with T=500. L and H are generated independently, and the average number of digits in either is about 11.

      My solution at the time of publication has 410 bytes (not golfed) and runs in 0.27s with 1.8M memory footprint.


      Added by:Mitch Schwartz
      Date:2013-06-01
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BF









      SPOJ Problem Set (classical)

      15091. One Good Base Deserves Another

      Problem code: BFBASE

      Basil and Blaise are very interested in manufacturing sodium hydroxide, ammonia, and other bases. They currently work out of an old basement but are itching to establish a new home base at the base of a tall mountain overlooking the bay. They’re meeting with their real estate agent, Bane, to look for a building large enough to house their basic operations. Bane seems like a trustworthy fellow, based on his professional manner and charming smile, but he secretly harbors base intentions. He uses a special bank, Hexcorp, that conducts all of its business in hexadecimal. He is extra careful to make sure all the figures in his contracts use only the digits 0 through 9, even though they are in hexadecimal, in the hopes that his clients will unwittingly agree to his inflated prices so he can keep a hefty share for himself. He has included a notice about his unusual choice of numeric base in the very fine print of his contracts, to protect himself legally and cover all bases.

      Fortunately, Basil and Blaise always read contracts very carefully before signing them, and the strange notice catches their attention. But they don’t know anything about converting numbers between bases, since before turning to chemistry Basil was a professional baseball player and Blaise was an aspiring bass guitarist, and neither has had much mathematical training. Please help them avoid getting scammed by sending them a program that will allow them to take an integer in one base and convert it into another base. But be careful: Bane has a deep network of spies, and if they intercept your correspondence, Bane may take drastic action. Luckily, his spies don’t understand brainf**k, so you can safely send them anything in that language.

      Note: You can use any programming language you want, as long as it is brainf**k.

      Input

      For clarity, all integers in this section are given in decimal.

      The first line contains an integer T (1 ≤ T ≤ 1000) expressed in decimal. Then follow T lines, each containing 3 space-separated integers: B1 and B2 (2 ≤ B1,B2 ≤ 35) expressed in base 36, followed by N (0 ≤ N ≤ 35^35) expressed in base B1. For bases greater than 10, only uppercase letters are used.

      Each line, including the last, is terminated by a single newline (linefeed) character, which has ASCII value 10.

      Output

      T lines containing N expressed in base B2. For bases greater than 10, only uppercase letters are allowed.

      Example

      Input:

      9
      F A 50000
      A 2 42
      2 A 101010
      2 Z 1011011101111011111
      7 8 0
      Z 7 YWX123ABC
      Y I ABCDEFG
      I Y ABCDEFG
      Y Y ABCDEFG
      

      Output:

      253125
      101010
      42
      8QQF
      0
      22400453332065605
      1816CB9F4
      7X2J66
      ABCDEFG
      

      Additional Info

      There are two randomly generated data sets, one with T=1000 and the other with T=500. B1 and B2 are generated independently, and the average value of either is about 18.5. The average number of digits in N when expressed in decimal is about 14.

      My solution at the time of publication has 678 bytes (not golfed) and runs in 3.71s with 1.8M memory footprint.


      Added by:Mitch Schwartz
      Date:2013-06-01
      Time limit:30s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BF









      SPOJ Problem Set (classical)

      15092. A Kleene Implementation

      Problem code: BFREGEX1

      Thor, the Norse god of thunder, was shopping for groceries when he noticed a sale on Kleenex brand tissues. This got him thinking about Kleene’s recursion theorem and its application to quines in functional programming languages. As this gave him a headache, he instead turned his attention to how one might recognise regular expressions with Kleene stars on a Turing machine. Unfortunately, this just made his headache worse. So he took out a slip of paper, jotted down a brainf**k program to handle regular expressions containing Kleene plusses, paid for his groceries, and congratulated himself on a job well done.

      Note: You can use any programming language you want, as long as it is brainf**k.

      Input

      The first line contains an integer T (1 ≤ T ≤ 1000). Then follow T test cases.

      For each test case: The first line contains a regular expression P (1 ≤ |P| ≤ 30). The next line contains an integer Q (1 ≤ Q ≤ 10). Then follow Q lines, each containing a string S (1 ≤ |S| ≤ 100). Finally, there is an empty line at the end of each test case.

      Each line, including the last, is terminated by a single newline (linefeed) character, which has ASCII value 10.

      All regular expressions are guaranteed to be valid; in particular, P may not start with a plus, and it may not contain two consecutive plusses. P is a string over the alphabet {a,b,c,d,+}, and S is a string over the alphabet {a,b,c,d}.

      Output

      T lines each containing a string of length Q. The ith character of the string indicates whether S is in the regular language defined by P: 'Y' for a match, and '.' otherwise. Note that we are concerned whether P matches S, as opposed to a substring of S. In other words, we could insert '^' at the beginning of P and '$' at the end, and then test for a match using e.g. m// in Perl. See the example for further clarification.

      Example

      Input:

      3
      a
      2
      a
      aa
      
      a+
      2
      a
      aa
      
      a+bc
      6
      abbacadabba
      aaaabc
      abc
      bc
      abcd
      babc
      
      

      Output:

      Y.
      YY
      .YY...
      

      Additional Info

      There are two randomly generated data sets, one with T=1000 and the other with T=500. The average value of Q is about 6, the probability of a match is about 0.25, the average length of P is about 14, and the average length of S is about 27.

      My solution at the time of publication has 803 bytes (not golfed) and runs in 0.20s with 2.6M memory footprint.


      Added by:Mitch Schwartz
      Date:2013-06-01
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BF









      SPOJ Problem Set (classical)

      15143. play with prime numbers (I)

      Problem code: POP1


      A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself .

      we define here a new prime number called prime of primes number (POP) is a prime number that consist of other prime numbers less than this number .

      example : 

      1013 consist of 101 and 3 and both are primes .

      notes :

      2003 is not POP because leading zero not allowed .

      the POP number must contain more than or equal two primes , and overlapping not allowed .

      Input

       

      The first line contains an integer T specifying the number of test cases. (T <= 1000) followed by 
      T lines , each line contains an integer m number 0<=m<=10^9 .

      The first line contains an integer T specifying the number of test cases. (T <= 10^4) followed by 

      T lines , each line contains an integer m number 0<=m<=10^9 .

      Output

      For each test case print single line contain the first integer greater than or equal to m and is (POP) .

      Example

      Input:

      3
      10
      100
      1000

      Output:

      23
      113
      1013

      after solving this you can try http://www.spoj.com/problems/POP2/


      Added by:abdou 00
      Date:2013-06-05
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:owner









      SPOJ Problem Set (classical)

      15148. play with prime numbers (II)

      Problem code: POP2

      A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself .

      we define here a new prime number called prime of primes number (POP) is a prime number that consist of other prime numbers less than this number .

      example : 

      1013 consist of 101 and 3 and both are primes .

      notes :

      2003 is not POP because leading zero not allowed .

      the POP number must contain more than or equal two primes , and overlapping not allowed .

      Input

       

      The first line contains an integer T specifying the number of test cases. (T <= 1000) followed by 
      T lines , each line contains an integer m number 0<=m<=10^9 .

      The first line contains an integer T specifying the number of test cases. (T <= 200) followed by 

      T lines , each line contains an integer m number 0<=m<=10^18 .

      Output

      For each test case print single line contain the first integer greater than or equal to m and is (POP) .

      Example

      Input:

      3
      10
      100
      1000

      Output:

      23
      113
      1013

      after solving this you can try http://www.spoj.com/problems/POP3/



      Added by:abdou 00
      Date:2013-06-06
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:owner









      SPOJ Problem Set (classical)

      15149. play with prime numbers (III)(hard )

      Problem code: POP3


      A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself .

      we define here a new prime number called prime of primes number (POP) is a prime number that consist of other prime numbers less than this number .

      example : 

      1013 consist of 101 and 3 and both are primes .

      notes :

      2003 is not POP because leading zero not allowed .

      the POP number must contain more than or equal two primes , and overlapping not allowed .

      Input

       

      The first line contains an integer T specifying the number of test cases. (T <= 1000) followed by 
      T lines , each line contains an integer m number 0<=m<=10^9 .

      The first line contains an integer T specifying the number of test cases. (T <= 200) followed by 

      T lines , each line contains an integer m number 0<=m<=10^27 .

      Output

      For each test case print single line contain the first integer greater than or equal to m and is (POP) .

      Example

      Input:

      3
      10
      100
      1000

      Output:

      23
      113
      1013
      time limit has been changed and all solution was rejudged .

      Added by:abdou 00
      Date:2013-06-06
      Time limit:90s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:owner









      SPOJ Problem Set (classical)

      15164. primes triangle (I)

      Problem code: PTRI

      primes triangle is a triangle that contain all prime numbers .

                2

               3 5

            7 11 13

         17 19 23 29

        .........

      you task is very easy given an integer from 1 to 10^8 prints its place in the primes triangle .

      you task is very easy given an integer from 1 to 10^8 prints its place in the primes triangle .

       

      Input

      in the first line integer 1<= T <= 10^5  , followed by T lines each line contain integer 1 <= n <= 10^8 .

      Output

      one line contain pair of integers i , j .where i is the row number and j is the column number , 1 base . or -1 if n not exist in the primes triangle .

      Example

      Input:
      3
      3
      23
      4
      Output:
      2 1
      4 3
      -1
      if you find Time limit is small here you can solve the tutorial version here :
       http://www.spoj.com/problems/PTRI2/

      Added by:abdou 00
      Date:2013-06-07
      Time limit:0.200s
      Source limit:5000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:owner









      SPOJ Problem Set (classical)

      15165. primes triangle (II)

      Problem code: PTR2

      primes triangle is a triangle that contain all prime numbers .

                2

               3 5

            7 11 13

         17 19 23 29

        .........

      you task is very easy given an integer from 1 to 10^8 prints its place in the primes triangle .

      you task is very easy given an integer from 1 to 10^9 prints its place in the primes triangle .

       

      Input

      in the first line integer 1<= T <= 10^4  , followed by T lines each line contain integer 1 <= n <= 10^9 .

      Output

      one line contain pair of integers i , j .where i is the row number and j is the column number , 1 base . or -1 if n not exist in the primes triangle .

      Example

      Input:
      3
      3
      23
      4
      Output:
      2 1
      4 3
      -1
      if you find Time limit is small here you can solve the tutorial version here :
      http://www.spoj.com/problems/PTR22/

      Added by:abdou 00
      Date:2013-06-07
      Time limit:1.5s
      Source limit:20000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:owner









      SPOJ Problem Set (classical)

      15190. MAXIMUM RARITY

      Problem code: SBO


      Given a sequence of numbers, each number between 1 and 100000 (inclusive), find the contiguous subsequence with maximum rarity.

      The rarity of a sequence is defined as the count of numbers which appear only once in that sequence. For example, let's consider the following sequence:

      1 1 2 5 1 16 5

      The rarity of the subsequence 1 1 2 5 is 2. This is because 2 and 5 are the only numbers which appear just once. 1 appears twice in the sequence, hence doesn't contribute to it's rarity. The rarity of subsequence 1 16 5 is 3 as each of the numbers appears only once. The maximum rarity achieved by any contiguous subsequence in the sequence 1 1 2 5 1 16 5 is 4. This is the rarity of 2 5 1 16.

      Your task is to find the contiguous subsequence with maximum rarity and output that rarity value. You don't have to output the subsequence itself.

      Input

      The first line of input will contain an integer N. N is the count of numbers in the input sequence.

      1<=N<=500000.

      The next line will contain the sequence of numbers. Each number in the sequence is an integer between 1 and 100000.

      Output

      The maximum rarity that any contiguous subsequence possesses.

      Example

      Input 1:
      7
      1 1 2 5 1 16 5
      Output 1: 4

      Input 2:
      3
      1 2 3
      Output 2:
      3

      Input 3:
      10
      2 1 4 1 5 6 7 1 8 2
      Output 3:
      6

      Input 4:
      20
      3 4 14 14 9 7 11 7 15 13 9 9 14 9 13 10 13 9 5 4
      Output 4:
      7

      Explanation:
      Input 2:
      The maximum rarity is achieved by the sequence itself.
      Input 3: The maximum rarity is achieved by the subsequences 1 4 1 5 6 7 1 8 2, 4 1 5 6 7 1 8 2 and 5 6 7 1 8 2.
      All the three contiguous subsequences have rarity 6.
      Input 4:
      The maximum rarity is achieved by the subsequence 11 7 15 13 9 9 14 9 13 10 13 9 5 4.
      This sequence has 7 numbers which appear only once in it, i.e., 11, 7, 15, 14, 10, 5, 4.

      Added by:Pushkar Mishra
      Date:2013-06-10
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      15208. Minimum Cost

      Problem code: MC


      Problem Statement :

      Given two string S and T. you can delete a character  from  with  cost 15 and  a Character T with cost 30. Your goal is to make the string equal (same). It is not mandatory  to delete  character .

      For example :  S = a5b and  T = 2ab . Now , if we delete X from S and Y from T, then total cost  =  15+30 = 45.  And  S and T will become ab.

      Another example : S = ab , T = cd , Now  total cost = 15  + 15 + 30 + 30 = 90.

      Another example : S = abcd , T = acdb , Now  total cost = 15 + 30 = 45.

      Input:

      Input consists of pairs of lines. The first line of a pair contains the first string S and the second line contains the second string T. Each string is on a separate line and consists of at most 1,000 characters . The end of input occurs when the first sequence starts with an "#"character (without the quotes).

      Output:

      For each subsequent pair of input lines, output a line containing one integer number which  the minimum cost to make the string equal (same).

       

      Sample Input/Output:

       

      Sample Input

      Sample Output

       axb

       yab

       ab

       cd

       ko

       p

       abcd

       acdb

       # 

       45

       90

       60

       45


      ___________________________________________________________________________________________________________
      Problem Setter: Shipu Ahamed , Dept. of CSE 

      Bangladesh University of Business and Technology (BUBT)


      Added by:Shipu Ahamed
      Date:2013-06-15
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:BAPS









      SPOJ Problem Set (classical)

      15215. David and his Obsession

      Problem code: PUCMM009

      You are walking by an empty corridor at PUCMM. All around you are arithmetic expressions written on the walls and on the floor. You find it odd and quickly realize all these expressions seem to be failed attempts to solve a problem. As you read by, you hear a voice coming from one of the classrooms that is whispering “I do not see it! I do not see it!” You walk to the classroom and find David rolling on the floor in frustration.


      “What’s going on, David? you ask.

      “The answer.. I do not see! Do you see?” replies David back.

       

      “What answer?” you ask him.

      “Professor Olson gave me this problem and … I do not see.”

       

      “Ok. What about you stand up and describe the problem to me?” you ask again.

      “Well, OK. You are pretty smart yourself. Imagine ten slips of paper bearing the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 are put into a hat. 5 slips are drawn at random and laid out in a row in the order in which they were drawn.” He sighs deeply. “What is the probability that the 5-digit number so formed is divisible by 495?”

       

      On your backpack there is a laptop. Help him. Write an algorithm that solves the problem.

       

      Input

       

      There is no input for this problem.

       

      Output

       

      Print in a single line the answer as a fraction expressed in its lowest terms.

       

      Sample cases

       

      There are no sample cases for this problem.

       

      Notes

      In case you need this, the greatest common divisor of (a, b) is defined recursively as follows:

       

      gcd(a,b) = b if a == 0, otherwise gcd = gcd(b mod a, a).

       


      Added by:kojak_
      Date:2013-06-15
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Yaglom Challenging Mathematical Problems With Elementary Solutions









      SPOJ Problem Set (classical)

      15241. Luis Quest

      Problem code: VPL2_AA

      Luis is playing his old metroid game. Just a little while ago he pass trough a scenario where the room was filled with some amoeba-like creatures. The room started with some initial number of creatures, but they multiply their selves very quickly, because their growth rate is proportional to the number of creatures at a certain time. Luis took note about this fact, he wrote the number of creatures at the initial time, and then, after wait t time units, he wrote the new amount. Now Luis wants to know, for a certain number of creatures p, the exact time he has to be in the room to see that amount.

      Input

      The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.

      For each test case, there will be 2 lines, the first one will contain 4 integers, p0, p1, t and p. These numbers represents the initial amount of creatures, the second amount of creatures, the time units that Luis waited to see that change, and the number of creatures that Luis wants to see.

      Output

      For each input case you must print a single line containing the string Scenario #i: where i is the number of the test case (starting at one), and then the answer to the problem rounded to two decimal places. There will always be an answer.

       

       

      INPUT

      OUTPUT

      4

      10 15 3 15

      10 15 3 20

      5 12 2 50

      5 12 2 7

      Scenario #1: 3.00

      Scenario #2: 5.13

      Scenario #3: 5.26

      Scenario #4: 0.77


      Constraints - 100%

       1 ≤ T , p0, p1, t, p ≤ 100 

       


      Added by:Venezuelan Programming League
      Date:2013-06-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15242. Betos Quest

      Problem code: VPL2_AB

      Beto is playing a game called "Impossible Mission" and he is getting very angry. He got completely stuck on the final mission. Here's what's the mission is about: Ethan Hunt must simply walk from a given start field to an end one. Hindering his progress, there are fake floor tiles that he must avoid. However that's not all, there are cameras everywhere!

      Camera i has range Ri and can be directed in four cardinal directions. It will scan Ri fields in a given direction, not including field were it's placed itself. Every second camera will rotate 90 degrees clock-wise.

      Ethan can move only in the four cardinal directions. He must make exactly one move every second (he can't stand in place). In addition, Ethan Hunt can use a special suit that makes him invisible to the cameras, even if he is in the range of multiples cameras. Unfortunately, as everything in the IMF, the suit is a prototype and tends to fail after a second of use. That's ́why Ethan has C suits that he will be able to use. It's possible Ethan will start on a field screened by a camera. In such a case he must use a suit. If he doesn't have one, the game is already lost. Also for final position, you must use a suit to shield against screening before exiting, if you are spotted by a camera.

      Your mission, if you choose to accept it, is to help Beto to succeed in the game by telling him whether if it is possible or not to cross the maze. If it is possible, give Beto a clue and output the minimum steps needed to solve the problem.

      Input

      The first line contains an integer T, which specifies the number of test cases. Then the descriptions of T test cases follow.

      For each case, first line will contain four integers N, M, K, C denoting the height and the width of the matrix, the number of cameras and the number of camouflage suits Ethan has.

      Next N lines will follow with M characters each. The ’#’ character denotes a fake floor and Ethan must avoid it. The ’.’ denotes a normal floor. Note than a fake floor will only block Ethan and not a camera field of view.

      Next K lines will follow with the description of the cameras. Each line will consist on four integers, denoting respectively the row and the column where the camera is (both 0-based), the range Ri of the camera and it's initial direction Di. 0 means that the camera is pointing to north, 1 east, 2 south and 3 west.

      Final two lines will contain two integers each, denoting the starting point and the ending point of Ethan Hunt. For both lines, first integer describes the row and second the column, both 0-based. It is guaranteed that Ethan won't start or be directed to a fake floor.

      Output

      For each input case, you must print a single line. The string "Scenario #i: " where i denotes the case you are analyzing (starting by 1), followed by the minimum number of steps that Ethan must make in order to reach his destination. If it is impossible, print -1.


      Example

      INPUT

      OUTPUT

      2
      5 4 3 0
      ....
      .#..
      ..#.
      ....
      ....
      0 3 4 2
      2 1 4 0
      4 0 1 0
      0 0
      4 3
      3 3 2 0
      ...
      ...
      ...
      0 2 1 2
      2 0 1 3
      0 0
      2 2
      
      Scenario #1: 7
      Scenario #2: -1
      

       

      Constraints - Subtask 1 (30%)

       1 ≤ T ≤ 30

       1 ≤ N ,M ≤ 100

       1 ≤ K ≤ 100

       0 ≤ C ≤ 0

       1 ≤ Rk ≤ 100

      Constraints - Subtask 2 (30%)

       1 ≤ T ≤ 20

       1 ≤ N ,M ≤ 100

       1 ≤ K ≤ 100

       0 ≤ C ≤ 10

       1 ≤ Rk ≤ 100

      Constraints - Subtask 3 (40%)

       1 ≤ T ≤ 10

       1 ≤ N ,M ≤ 1000

       1 ≤ K ≤ 1000

       0 ≤ C ≤ 10

       1 ≤ Rk ≤ 1000 

       


      Added by:Venezuelan Programming League
      Date:2013-06-22
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15243. Primos Quest

      Problem code: VPL2_AC

      Primo is playing Guitar Hero, but he has been playing it for quite long, and his hand is a little tired. He knows that for every change between colors his energy goes down. The colors of the guitar are ordered like this: Green, Red, Yellow, Blue and Orange. The energy to change from playing a color A, to a color B, is the absolute difference of the distance between them, by example, changing from Red to Yellow, costs 1 unit of energy, and changing from Blue to Green costs 3 units of energy. Primo knows that he has exactly C units of energy left, and he also know the colors of the notes from a random song. Help him find out the maximum number of notes in a row that he can play on this song.

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow the descriptions of T test cases.

      For each test case you will have a single line containing an integer C, representing the energy left of Primo, and a string S, representing the colors and the order of the notes from the song. Each character in S will be ’G’ for Green, ’R’ for Red, ’Y’ for Yellow, ’B’ for Blue or ’O’ for Orange.

      Output

      For each input case you must print Scenario #i: where i is the number of the test case (starting at one), and then the answer to the problem. 

       

      INPUT

      OUTPUT

      3

      0 OORRBYYYGG

      1 RRORGRRRBOY

      3 RRRORORRRR

      Scenario #1: 3

      Scenario #2: 4

      Scenario #3: 5

       

      Constraints - 40%

       1 ≤ T ≤ 100

       0 ≤ C, |S| ≤ 1000

      Constraints - 60%

       1 ≤ T ≤ 100

       0 ≤ C, |S| ≤ 1000000 


      Added by:Venezuelan Programming League
      Date:2013-06-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      15244. Davids Quest

      Problem code: VPL2_AD

      David is playing minesweeper and he really wants to break his record at the game. The only way to achieve this is by cheating! As he is a fast clicker (or at least he believes that), he wants to know how much clicks must be given in order to solve the puzzle.

      I case you never played minesweeper, here are some basic rules. You are given a rectangular map divided into square cells. At the start of the game, all the cells are hidden. Under some of them there are mines. You are required to uncover all cells WITHOUT mines (we will call them safe cells). If you try to uncover a mine, the game is over and you lost. On safe cells there are hints to help you along the way. They contain numbers that indicate how many mines are hidden on the 8 adjacent cells (less in case of border cells). So we have numbers 1 to 8 and those can be uncovered with a single click. If there are no neighboring mines the filed is simply empty. In addition, if you will uncover this empty cells, all its neighboring will be uncovered automatically. This effect is also recursive, so can uncover a bigger chunk with one click, if there are more connected empty cells.

      David knows everything about the puzzle: where the mines are located and thus he can also deduce the number hints on others cells.

      Input

      The first line contains an integer T, the number of test cases. Description of T testcases follow. Every case with two numbers N and M: denoting the height and the width of the puzzle. Then N lines with M characters each. Characters are as follows:
           '-': denotes an empty cell,
           '*': denotes a mine,
           '1'-'8': Numbers i denotes that there is i mines adjacent to the current one.

      Output

      For each input case you must print a single line. The string "Scenario #i: " where i denotes the case you are analyzing (starting with 1), followed by the number of clicks that must be given in order to uncover all safe cells.

       

      INPUT

      OUTPUT

      3
      3 2
      *2
      2*
      11
      3 3
      ***
      232
      ---
      8 8
      1*1-----
      111-1221
      ----1**1
      ----2331
      11--1*32
      *1--13**
      11---2**
      -----13*
      
      Scenario #1: 4
      Scenario #2: 1
      Scenario #3: 9
      

       

      Constraints - Subtask 1 (40%)

       1 ≤ T ≤ 10

       1 ≤ N ≤ 128

       1 ≤ M ≤ 128

      Constraints - Subtask 2 (60%)

       1 ≤ T ≤ 10

       1 ≤ N ≤ 2048

       1 ≤ M ≤ 2048 


      Added by:Venezuelan Programming League
      Date:2013-06-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15248. Swap (Easy - Level 2)

      Problem code: SWAP_ESY


      Let's play with sequence of non negative integer. Given two sequence of n non negative integers (a1,a2,...,an) and (b1,b2,...,bn). Both sequence has maximum element less than k, max(a1,a2,...,an)<k and max(b1,b2,...,bn)<k. The game rule is you can edit both sequence with this operaton: swap ai and bi with 1≤in, and the goal is to make sequence a and b become increasing sequence: ai≤aj if and only if ij and bi≤bj if and only if ij. But not all initial sequence a and b can be solved.

      For example (2,0) and (0,1) is a pair of sequence that can't be solved:

      • If you don't swap any element, you have (2,0) and (0,1), but sequence (2,0) is not increasing.
      • If you swap first element only, then the pair become like this (0,0) and (2,1), sequence (2,1) is not increasing.
      • If you swap second element only, then the pair become like this (2,1) and (0,0), again (2,1) is not increasing.
      • If you swap both element, thrn the pair become like this (0,1) and (2,0), again (2,0) is not increasing

      So it's impossible to solve if initial sequence is (2,0) and (0,1), because all possible move can't make both sequence become increasing.

      Now given n and k, your task is to compute number of different pair of initial sequence (a,b) that can be solved with game described above.

      Input

      First line there is an integer T denoting number of test case, then T test cases follow.

      For each case, there are two integers n and k writen in one line, separated by a space.

      Output

      For each case, output number of different pair of initial sequence (a,b), since the answer can be large, output the answer modulo 109+7.

      Constraints

      0<T≤105

      0<min(n,k)≤2

      0<max(n,k)<109

      Example

      Input:
      6
      2 1
      1 2
      1 3
      2 2
      3 2
      2 3
      Output:
      1
      4
      9
      11
      26
      46

      Explanation

      Here is list of all possible pair of initial sequence (a,b) on each case:

      Case 1: {[(0,0),(0,0)]}

      Case 2: {[(0),(0)],[(0),(1)],[(1),(0)],[(1),(1)]}

      Case 3: {[(0),(0)],[(0),(1)],[(0),(2)],[(1),(0)],[(1),(1)],[(1),(2)],[(2),(0)],[(2),(1)],[(2),(2)]}

      Case 4: {[(0,0),(0,0)],[(0,0),(0,1)],[(0,0),(1,1)],[(0,1),(0,0)],[(0,1),(0,1)],[(0,1),(1,0)],[(0,1),(1,1)],[(1,0),(0,1)],[(1,1),(0,0)],[(1,1),(0,1)],[(1,1),(1,1)]}

      Case 5: {[(0,0,0),(0,0,0)],[(0,0,0),(0,0,1)],[(0,0,0),(0,1,1)],[(0,0,0),(1,1,1)],[(0,0,1),(0,0,0)],[(0,0,1),(0,0,1)],[(0,0,1),(0,1,0)],[(0,0,1),(0,1,1)],[(0,0,1),(1,1,0)],[(0,0,1),(1,1,1)],[(0,1,0),(0,0,1)],[(0,1,0),(1,0,1)],[(0,1,1),(0,0,0)],[(0,1,1),(0,0,1)],[(0,1,1),(0,1,1)],[(0,1,1),(1,0,0)],[(0,1,1),(1,0,1)],[(0,1,1),(1,1,1)],[(1,0,0),(0,1,1)],[(1,0,1),(0,1,0)],[(1,0,1),(0,1,1)],[(1,1,0),(0,0,1)],[(1,1,1),(0,0,0)],[(1,1,1),(0,0,1)],[(1,1,1),(0,1,1)],[(1,1,1),(1,1,1)]}

      Case 6: {[(0,0),(0,0)],[(0,0),(0,1)],[(0,0),(0,2)],[(0,0),(1,1)],[(0,0),(1,2)],[(0,0),(2,2)],[(0,1),(0,0)],[(0,1),(0,1)],[(0,1),(0,2)],[(0,1),(1,0)],[(0,1),(1,1)],[(0,1),(1,2)],[(0,1),(2,2)],[(0,2),(0,0)],[(0,2),(0,1)],[(0,2),(0,2)],[(0,2),(1,0)],[(0,2),(1,1)],[(0,2),(1,2)],[(0,2),(2,0)],[(0,2),(2,1)],[(0,2),(2,2)],[(1,0),(0,1)],[(1,0),(0,2)],[(1,1),(0,0)],[(1,1),(0,1)],[(1,1),(0,2)],[(1,1),(1,1)],[(1,1),(1,2)],[(1,1),(2,2)],[(1,2),(0,0)],[(1,2),(0,1)],[(1,2),(0,2)],[(1,2),(1,1)],[(1,2),(1,2)],[(1,2),(2,1)],[(1,2),(2,2)],[(2,0),(0,2)],[(2,1),(0,2)],[(2,1),(1,2)],[(2,2),(0,0)],[(2,2),(0,1)],[(2,2),(0,2)],[(2,2),(1,1)],[(2,2),(1,2)],[(2,2),(2,2)]}

      Other Info

      Test case (n and k) is generated randomly using this rule:

      • Probability that n>k or n<=k is ~50% each.
      • Maximum n and k is random log-uniform.
      • Minimum n and k is random uniform.

      Click here if you want to know my program speed and other detail.

      Time limit >100× my program top speed.


      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-06-23
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Modified Swap (Original) problem









      SPOJ Problem Set (classical)

      15249. Swap (Medium - Level 200)

      Problem code: SWAP_MED

      Let's play with sequence of non negative integer. Given two sequence of n non negative integers (a1,a2,...,an) and (b1,b2,...,bn). Both sequence has maximum element less than k, max(a1,a2,...,an)<k and max(b1,b2,...,bn)<k. The game rule is you can edit both sequence with this operaton: swap ai and bi with 1≤in, and the goal is to make sequence a and b become increasing sequence: ai≤aj if and only if ij and bi≤bj if and only if ij. But not all initial sequence a and b can be solved.

      For example (2,0) and (0,1) is a pair of sequence that can't be solved:

      • If you don't swap any element, you have (2,0) and (0,1), but sequence (2,0) is not increasing.
      • If you swap first element only, then the pair become like this (0,0) and (2,1), sequence (2,1) is not increasing.
      • If you swap second element only, then the pair become like this (2,1) and (0,0), again (2,1) is not increasing.
      • If you swap both element, thrn the pair become like this (0,1) and (2,0), again (2,0) is not increasing

      So it's impossible to solve if initial sequence is (2,0) and (0,1), because all possible move can't make both sequence become increasing.

      Now given n and k, your task is to compute number of different pair of initial sequence (a,b) that can be solved with game described above.

      Input

      First line there is an integer T denoting number of test case, then T test cases follow.

      For each case, there are two integers n and k writen in one line, separated by a space.

      Output

      For each case, output number of different pair of initial sequence (a,b), since the answer can be large, output the answer modulo 109+7.

      Constraints

      0<T≤105

      0<min(n,k)≤200

      0<max(n,k)<1018

      Example

      Input:
      6
      2 1
      1 2
      1 3
      2 2
      3 2
      2 3
      Output:
      1
      4
      9
      11
      26
      46

      Explanation

      Here is list of all possible pair of initial sequence (a,b) on each case:

      Case 1: {[(0,0),(0,0)]}

      Case 2: {[(0),(0)],[(0),(1)],[(1),(0)],[(1),(1)]}

      Case 3: {[(0),(0)],[(0),(1)],[(0),(2)],[(1),(0)],[(1),(1)],[(1),(2)],[(2),(0)],[(2),(1)],[(2),(2)]}

      Case 4: {[(0,0),(0,0)],[(0,0),(0,1)],[(0,0),(1,1)],[(0,1),(0,0)],[(0,1),(0,1)],[(0,1),(1,0)],[(0,1),(1,1)],[(1,0),(0,1)],[(1,1),(0,0)],[(1,1),(0,1)],[(1,1),(1,1)]}

      Case 5: {[(0,0,0),(0,0,0)],[(0,0,0),(0,0,1)],[(0,0,0),(0,1,1)],[(0,0,0),(1,1,1)],[(0,0,1),(0,0,0)],[(0,0,1),(0,0,1)],[(0,0,1),(0,1,0)],[(0,0,1),(0,1,1)],[(0,0,1),(1,1,0)],[(0,0,1),(1,1,1)],[(0,1,0),(0,0,1)],[(0,1,0),(1,0,1)],[(0,1,1),(0,0,0)],[(0,1,1),(0,0,1)],[(0,1,1),(0,1,1)],[(0,1,1),(1,0,0)],[(0,1,1),(1,0,1)],[(0,1,1),(1,1,1)],[(1,0,0),(0,1,1)],[(1,0,1),(0,1,0)],[(1,0,1),(0,1,1)],[(1,1,0),(0,0,1)],[(1,1,1),(0,0,0)],[(1,1,1),(0,0,1)],[(1,1,1),(0,1,1)],[(1,1,1),(1,1,1)]}

      Case 6: {[(0,0),(0,0)],[(0,0),(0,1)],[(0,0),(0,2)],[(0,0),(1,1)],[(0,0),(1,2)],[(0,0),(2,2)],[(0,1),(0,0)],[(0,1),(0,1)],[(0,1),(0,2)],[(0,1),(1,0)],[(0,1),(1,1)],[(0,1),(1,2)],[(0,1),(2,2)],[(0,2),(0,0)],[(0,2),(0,1)],[(0,2),(0,2)],[(0,2),(1,0)],[(0,2),(1,1)],[(0,2),(1,2)],[(0,2),(2,0)],[(0,2),(2,1)],[(0,2),(2,2)],[(1,0),(0,1)],[(1,0),(0,2)],[(1,1),(0,0)],[(1,1),(0,1)],[(1,1),(0,2)],[(1,1),(1,1)],[(1,1),(1,2)],[(1,1),(2,2)],[(1,2),(0,0)],[(1,2),(0,1)],[(1,2),(0,2)],[(1,2),(1,1)],[(1,2),(1,2)],[(1,2),(2,1)],[(1,2),(2,2)],[(2,0),(0,2)],[(2,1),(0,2)],[(2,1),(1,2)],[(2,2),(0,0)],[(2,2),(0,1)],[(2,2),(0,2)],[(2,2),(1,1)],[(2,2),(1,2)],[(2,2),(2,2)]}

      Other Info

      Test case (n and k) is generated randomly using this rule:

      • Probability that n>k or n<=k is ~50% each.
      • Maximum n and k is random log-uniform.
      • Minimum n and k is random uniform.

      Click here if you want to know my program speed and other detail.

      Explanation about my Algorithm complexity:

      My 2.8KB of python 3 code that got AC in 18.7s, the complexity is O(min(n,k)^3) "This is direct translation [line by line] of my C code, there are many room for opti like fast I/O, data structure, etc"

      My 3.7KB of C code that got AC in 6.36s, the complexity is O(min(n,k)^4)

      My 3.8KB of C code that got AC in 0.53s, the complexity is O(min(n,k)^3) "Note that altough the size of code is similar, but my O(min(n,k)^4) and O(min(n,k)^3) code is very different"

      To challenge fast language user with O(min(n,k)^3) complexity, I made this Hard version.
      For slow language user this medium version will be look like hard version ;-) good luck.

      About complexity, I've proved using math that no algo with complexity better than O(min(n,k)^2), this is the lower bound. My best algo for now is O(min(n,k)^3), this is the upper bound. So the optimal algo lies between that lower and upper bound. I still don't have proof that my algo is optimal, so there is possibility that there is an algorithm that better than O(min(n,k)^3).

      Time limit ~37× my program top speed.


      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-06-23
      Time limit:20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Modified Swap (Original) problem









      SPOJ Problem Set (classical)

      15250. Swap (Hard - Level 1000)

      Problem code: SWAP_HRD

      Let's play with sequence of non negative integer. Given two sequence of n non negative integers (a1,a2,...,an) and (b1,b2,...,bn). Both sequence has maximum element less than k, max(a1,a2,...,an)<k and max(b1,b2,...,bn)<k. The game rule is you can edit both sequence with this operaton: swap ai and bi with 1≤in, and the goal is to make sequence a and b become increasing sequence: ai≤aj if and only if ij and bi≤bj if and only if ij. But not all initial sequence a and b can be solved.

      For example (2,0) and (0,1) is a pair of sequence that can't be solved:

      • If you don't swap any element, you have (2,0) and (0,1), but sequence (2,0) is not increasing.
      • If you swap first element only, then the pair become like this (0,0) and (2,1), sequence (2,1) is not increasing.
      • If you swap second element only, then the pair become like this (2,1) and (0,0), again (2,1) is not increasing.
      • If you swap both element, thrn the pair become like this (0,1) and (2,0), again (2,0) is not increasing

      So it's impossible to solve if initial sequence is (2,0) and (0,1), because all possible move can't make both sequence become increasing.

      Now given n and k, your task is to compute number of different pair of initial sequence (a,b) that can be solved with game described above.

      Input

      First line there is an integer T denoting number of test case, then T test cases follow.

      For each case, there are two integers n and k writen in one line, separated by a space.

      Output

      For each case, output number of different pair of initial sequence (a,b), since the answer can be large, output the answer modulo 109+7.

      Constraints

      0<T≤104

      0<min(n,k)≤1000

      0<max(n,k)<101000

      Example

      Input:
      6
      2 1
      1 2
      1 3
      2 2
      3 2
      2 3
      Output:
      1
      4
      9
      11
      26
      46

      Explanation

      Here is list of all possible pair of initial sequence (a,b) on each case:

      Case 1: {[(0,0),(0,0)]}

      Case 2: {[(0),(0)],[(0),(1)],[(1),(0)],[(1),(1)]}

      Case 3: {[(0),(0)],[(0),(1)],[(0),(2)],[(1),(0)],[(1),(1)],[(1),(2)],[(2),(0)],[(2),(1)],[(2),(2)]}

      Case 4: {[(0,0),(0,0)],[(0,0),(0,1)],[(0,0),(1,1)],[(0,1),(0,0)],[(0,1),(0,1)],[(0,1),(1,0)],[(0,1),(1,1)],[(1,0),(0,1)],[(1,1),(0,0)],[(1,1),(0,1)],[(1,1),(1,1)]}

      Case 5: {[(0,0,0),(0,0,0)],[(0,0,0),(0,0,1)],[(0,0,0),(0,1,1)],[(0,0,0),(1,1,1)],[(0,0,1),(0,0,0)],[(0,0,1),(0,0,1)],[(0,0,1),(0,1,0)],[(0,0,1),(0,1,1)],[(0,0,1),(1,1,0)],[(0,0,1),(1,1,1)],[(0,1,0),(0,0,1)],[(0,1,0),(1,0,1)],[(0,1,1),(0,0,0)],[(0,1,1),(0,0,1)],[(0,1,1),(0,1,1)],[(0,1,1),(1,0,0)],[(0,1,1),(1,0,1)],[(0,1,1),(1,1,1)],[(1,0,0),(0,1,1)],[(1,0,1),(0,1,0)],[(1,0,1),(0,1,1)],[(1,1,0),(0,0,1)],[(1,1,1),(0,0,0)],[(1,1,1),(0,0,1)],[(1,1,1),(0,1,1)],[(1,1,1),(1,1,1)]}

      Case 6: {[(0,0),(0,0)],[(0,0),(0,1)],[(0,0),(0,2)],[(0,0),(1,1)],[(0,0),(1,2)],[(0,0),(2,2)],[(0,1),(0,0)],[(0,1),(0,1)],[(0,1),(0,2)],[(0,1),(1,0)],[(0,1),(1,1)],[(0,1),(1,2)],[(0,1),(2,2)],[(0,2),(0,0)],[(0,2),(0,1)],[(0,2),(0,2)],[(0,2),(1,0)],[(0,2),(1,1)],[(0,2),(1,2)],[(0,2),(2,0)],[(0,2),(2,1)],[(0,2),(2,2)],[(1,0),(0,1)],[(1,0),(0,2)],[(1,1),(0,0)],[(1,1),(0,1)],[(1,1),(0,2)],[(1,1),(1,1)],[(1,1),(1,2)],[(1,1),(2,2)],[(1,2),(0,0)],[(1,2),(0,1)],[(1,2),(0,2)],[(1,2),(1,1)],[(1,2),(1,2)],[(1,2),(2,1)],[(1,2),(2,2)],[(2,0),(0,2)],[(2,1),(0,2)],[(2,1),(1,2)],[(2,2),(0,0)],[(2,2),(0,1)],[(2,2),(0,2)],[(2,2),(1,1)],[(2,2),(1,2)],[(2,2),(2,2)]}

      Other Info

      Test case (n and k) is generated randomly using this rule:

      • Probability that n>k or n<=k is ~50% each.
      • Maximum n and k is random log-uniform.
      • Minimum n and k is random uniform.

      Click here if you want to know my program speed and other detail.

      Explanation about my Algorithm complexity:

      My 3.8KB of C code with O(min(n,k)^3) complexity got AC in 32.17s.

      Other sumbission like O(min(n,k)^4) in fast language, and O(min(n,k)^3) in slow language is all TLE. That's why this problem has "Hard" label.

      Sorry for slow language user, I think it's impossible to solve this problem unless O(min(n,k)^2) exists. I recommend to try Medium version first, or learn fast language :-P

      About complexity, I've proved using math that no algo with complexity better than O(min(n,k)^2), this is the lower bound. My best algo for now is O(min(n,k)^3), this is the upper bound. So the optimal algo lies between that lower and upper bound. I still don't have proof that my algo is optimal, so there is possibility that there is an algorithm that better than O(min(n,k)^3).

      Btw, if I found around O(min(n,k)^2) by myself, I'll set "Extreme" version (level 10000+) of this problem. But if there is someone who solve this problem in around O(min(n,k)^2), of course he/she has honor to set "Extreme" version of this problem.

      Time limit ~3× my program top speed.


      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-06-23
      Time limit:100s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Modified Swap (Original) problem









      SPOJ Problem Set (classical)

      15252. Humans Life Code

      Problem code: MOSTYCOD

      Imagine you are a Human Being ..
      So you have some parameters , and those paramters contain values.

      If you can imagine this,you can understand the Fact that Humans Store Their Parameters
      In A Big Array ... (Actually The Array Is Of Size 00963999206048 bit)
      [We will not discuss the meaning of the parameters here]

      If You want to know what is the value of some parameter
      you should go throw your mind .. surfing the internal array until reach the place for the parameter.

      The Most Important Thing To Know .. is WHERE ARE YOU NOW !
      And If We Suppose That Your parameters will not change until you consider to do this
      (Actually Thats Happend By surfing the internal array until reach the parameter Place
      And Then Change It
      And The Most Important Thing To Know Here..Is What Is The value stored Before Change
      (But Why?
      Because Humans Can Only Change Their Parameters By Increasing/Decreasing Its values
      (You Should Know That Humans Born (you don't have to know how or why) with initial value of ZERO
      For Every Place in their internal array)))

      The only way to know where are you (In the Internal Array)
      and what Is the Value there IS to follow you from Born
      to the point you are in now (you know humans lives on Average 00963113324820 ms on their planet Earth (The Average Brain Life)
      and it's a little bit hard to follow them from the millisecond Zero To The millisecond 00963113324819 )...

      Let's Talk A little About Humans Lifes

      It's Not So Complicated,As They Always move on ,(actually they can't stop the time until now :D Or even Go Back)..
      they have an Internal Stack To Save A Check Points In their LIFE ..

      These Check Points are the moments they call (Taking Decisions)
      These Points Make two Branches In Humans Lifes (One Branch is to go on and
      complete their life,executing every thing they supposed to do until reach the Memory Time,

      Thats Also Make Two Branches one Is to Skip Memory Time And Go On
      And The Other is (the Only Time They Go Back) they pop the last check point
      in their internal stack and go back to it,repeating every thing they've done from that moment)
      (Second Branch IS That They DO NOTHING UNTIL they reach the memory time(discussed before)
      and as they have No Memories They Skip The Memory time(never go back) and go on forward)

      To Simulate Humans Life We Can write Mosty's Code.
      What is Mosty's code?
      Denote The Only 11 Actions Humans Do As Follow:
      BORN denotes Born ...(where human starts his life with empty stack and zero_value Places in intenral array of parameters)
      DIE denotes Die  ...(where human End his life and rise/fall to paradise/Hell respectively ...
      (actually it's a temporary pleasure/pain until the Judge Day Which We Will Not Discuss Here
      (Which after it comes the endless pleasure/pain depends of what he done during his Short Life))
      ENTER denotes Enter His Internal Array
      (Note: Humans Never Die When They Are in Their Internal Array (until they goes out)
      Except in One situation will be Discussed later.)
      EXIT denotes Exit His Internal Array
      (Note : ignore any actions out of The Internal Array)
      (Note : when We Enter The Intenal array for the first time,So we are in place zero
      Else we stay in the last place we were in)
      DEEP denotes moving Deeper In Mind (internal array)
      (Note: if we were in the Deepest Place In mind then,we went deeper,we reach the zero place(as a modular Mind))
      FLOAT denotes moving Up Through the Mind (internal Array)
      (Note: if we were in Place Zero,Then We Floated Up We reach The Deepest place in mind)

      INCREASE denotes increase the value stored in place(that we are in now) by one.
      DECREASE denotes decrease the Value Stored in place(that we are in now) by one

      CHECKPOINT denotes moments of(Take A Decision) (described before)
      MEMORY denoted Memory time when you human decide to go back or continue your life.

      (Note: humans take a decision of executing their LifeCode included
      After The CHECKPOINT AND before its associated MEMORY
      IF and Only IF The Value He had in the last visited place in his mind was not ZERO
      Else he will skip his LifeCode Included in that partition until he skips the associated Memory)

      There is another 2 Actions(about interacting each other)We Will Not Discuss here.

      Following One Human At Time You Are Going To Write A Program which Print
      the values Of all Visited Places In His Mind (ONLY VISITED(ONLY))
      using this form
      PlaceNumber --> ItsValue

      When to print ?
      As you know values changes over his life ... so we will Define The Action '*****'
      Which Denotes To The Moment Of 'Self Evaluation'

      The Input Is a part of One Human Life
      But You Can Suppose these things :
      1-The Human already Born , and he is old enough to enter his MIND .
      2-he has already entered his mind(internal array).
      3-He Has an initial values in his mind (you will get them in input).
      4-he has initial place (also you will get it).
      5-The Human Will Not Exit His Internal Array During The Analyziz.
      6-The LifeCode (in this version)Contains only The Following Actions:
      [DEEP,FLOAT,INCREASE,DECREASE,CHECKPOINT,MEMORY,*****]
      7-*****.


      Input Form:

      First Line gives M P A S (separated by spaces)
      M : The Number Of already visited places (so you will get their values in the second line)...[0<M<50].
      P : The Last Place this Human Were In his mind...[0<=P<M].
      A : The Number Of Actions You Will Analyze...[0<A<1000].
      S : The Number Of 'Self Evaluation' action will appeare ...[0<=S<100].

      [Note : for every 'Self Evaluation' action you should print the value of all visited places(as discussed later)]
      Second Line Initiate The Values Of The First M value (from 0 to M-1) of internal array.
      Then Comes The A action Of this Human,7 in each line except the last one contain less.
      The Values V[0] V[1] ... V[M-1] are 32 bit integers (so that 0-1=-1 and 2147483647+1=-2147483648)
      [note that A includes S].

      Outputform:

      for Every 'Self Evaluation' action you should print the values in places of internal array
      using this form
      PlaceNumber --> ItsValue
      You Should Print a jasmine flower before PlaceNumber
      when PlaceNumber == The Last Place we've visited .

      [what the hell is jasmine flower ? '*' ]
      [note the spaces before and after the arrow]
      [Note: You can suppose that Humans Never Float in Mind When they are in place zero
      or So that WILL  KILL HIM (the only way to die during a mind trip)]

      EXAMPLES:

      Example1(Easy):
      Input:

      1 0 7 1
      5
      DEEP CHECKPOINT MEMORY FLOAT INCREASE DECREASE *****

      Output:
      *0 --> 5
      1 --> 0
      [the only place we've changed is 0 but we visit 1 also]
      [note that we haven't enter the check point]
      [note the Jasmin Flower]

      Example2(medium):
      Input:
      5 2 15 4
      0 1 2 3 4
      INCREASE INCREASE CHECKPOINT DECREASE DEEP ***** INCREASE
      INCREASE FLOAT MEMORY ***** DEEP ***** DECREASE
      *****

      Output:
      0 --> 0
      1 --> 1
      2 --> 3
      *3 --> 3
      4 --> 4

      0 --> 0
      1 --> 1
      2 --> 2
      *3 --> 5
      4 --> 4

      0 --> 0
      1 --> 1
      2 --> 1
      *3 --> 7
      4 --> 4

      0 --> 0
      1 --> 1
      2 --> 0
      *3 --> 9
      4 --> 4

      0 --> 0
      1 --> 1
      *2 --> 0
      3 --> 11
      4 --> 4

      0 --> 0
      1 --> 1
      2 --> 0
      *3 --> 11
      4 --> 4

      0 --> 0
      1 --> 1
      2 --> 0
      *3 --> 10
      4 --> 4

      Exmple3(HARD):
      input:
      1 0 6 0
      1
      CHECKPOINT DEEP FLOAT INCREASE DECREASE MEMORY
      output:
      AUTISM

      [the last example not exists in this version :p
      (actually I couldn't prevent myself from delete it as an example (btw it's true))]
      Example3(HARD)[real one]:
      Input:

      1 0 82 11
      0
      INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
      INCREASE INCREASE CHECKPOINT DECREASE DEEP INCREASE INCREASE
      INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE DEEP
      DEEP DEEP INCREASE INCREASE INCREASE INCREASE INCREASE
      FLOAT FLOAT FLOAT FLOAT MEMORY DEEP CHECKPOINT
      DECREASE DEEP INCREASE DEEP INCREASE FLOAT FLOAT
      MEMORY DEEP DECREASE ***** DEEP DECREASE DECREASE
      DECREASE ***** ***** FLOAT INCREASE INCREASE INCREASE
      INCREASE ***** DEEP DEEP ***** FLOAT FLOAT
      INCREASE INCREASE INCREASE INCREASE ***** DEEP DEEP
      ***** FLOAT DECREASE DECREASE ***** FLOAT *****
      DEEP INCREASE ***** INCREASE *****

      Output:

      0 --> 0
      1 --> 0
      *2 --> 71
      3 --> 72
      4 --> 45

      0 --> 0
      1 --> 0
      2 --> 71
      *3 --> 69
      4 --> 45

      0 --> 0
      1 --> 0
      2 --> 71
      *3 --> 69
      4 --> 45

      0 --> 0
      1 --> 0
      *2 --> 75
      3 --> 69
      4 --> 45

      0 --> 0
      1 --> 0
      2 --> 75
      3 --> 69
      *4 --> 45

      0 --> 0
      1 --> 0
      *2 --> 79
      3 --> 69
      4 --> 45

      0 --> 0
      1 --> 0
      2 --> 79
      3 --> 69
      *4 --> 45

      0 --> 0
      1 --> 0
      2 --> 79
      *3 --> 67
      4 --> 45

      0 --> 0
      1 --> 0
      *2 --> 79
      3 --> 67
      4 --> 45

      0 --> 0
      1 --> 0
      2 --> 79
      *3 --> 68
      4 --> 45

      0 --> 0
      1 --> 0
      2 --> 79
      *3 --> 69
      4 --> 45

      [if you noticed that S don't give the actual value of 'Self Evaluation'
      you don't have to print more than 100 of it]
      [as This human is not full trained in mind trips he will not go deeper than 10000 place
      also he can't make a nested CHECKPOINTES of a depth more than 100]

      last Example :

      input:
      10 9 180 1
      0 0 0 0 0 0 0 0 0 13986
      CHECKPOINT CHECKPOINT CHECKPOINT DECREASE DEEP INCREASE FLOAT
      CHECKPOINT DECREASE DEEP INCREASE FLOAT CHECKPOINT DECREASE
      DEEP INCREASE FLOAT CHECKPOINT DECREASE DEEP INCREASE
      FLOAT CHECKPOINT DECREASE DEEP INCREASE FLOAT CHECKPOINT
      DECREASE DEEP INCREASE FLOAT CHECKPOINT DECREASE DEEP
      INCREASE FLOAT CHECKPOINT DECREASE DEEP INCREASE FLOAT
      CHECKPOINT DECREASE DEEP INCREASE FLOAT CHECKPOINT DECREASE
      DEEP INCREASE FLOAT FLOAT INCREASE DEEP DEEP
      CHECKPOINT DECREASE MEMORY FLOAT CHECKPOINT DECREASE DEEP
      DEEP INCREASE FLOAT FLOAT MEMORY MEMORY MEMORY
      MEMORY MEMORY MEMORY MEMORY MEMORY MEMORY MEMORY
      MEMORY DEEP DEEP CHECKPOINT DECREASE FLOAT FLOAT
      INCREASE DEEP DEEP MEMORY FLOAT FLOAT MEMORY
      FLOAT CHECKPOINT DECREASE DEEP DEEP DEEP INCREASE
      FLOAT FLOAT FLOAT MEMORY DEEP DEEP CHECKPOINT
      INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
      INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
      INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
      INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
      INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
      INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE
      INCREASE INCREASE INCREASE INCREASE INCREASE INCREASE CHECKPOINT
      DECREASE FLOAT FLOAT INCREASE DEEP DEEP MEMORY
      MEMORY DEEP CHECKPOINT DECREASE FLOAT INCREASE DEEP
      MEMORY FLOAT MEMORY FLOAT FLOAT CHECKPOINT *****
      CHECKPOINT DECREASE MEMORY FLOAT MEMORY

      Output:

      0 --> 0
      1 --> 0
      2 --> 0
      3 --> 0
      4 --> 0
      5 --> 0
      6 --> 0
      7 --> 0
      8 --> 54
      9 --> 56
      10 --> 57
      11 --> 51
      *12 --> 49
      13 --> 0
      14 --> 0
      15 --> 0

      0 --> 0
      1 --> 0
      2 --> 0
      3 --> 0
      4 --> 0
      5 --> 0
      6 --> 0
      7 --> 0
      8 --> 54
      9 --> 56
      10 --> 57
      *11 --> 51
      12 --> 0
      13 --> 0
      14 --> 0
      15 --> 0

      0 --> 0
      1 --> 0
      2 --> 0
      3 --> 0
      4 --> 0
      5 --> 0
      6 --> 0
      7 --> 0
      8 --> 54
      9 --> 56
      *10 --> 57
      11 --> 0
      12 --> 0
      13 --> 0
      14 --> 0
      15 --> 0

      0 --> 0
      1 --> 0
      2 --> 0
      3 --> 0
      4 --> 0
      5 --> 0
      6 --> 0
      7 --> 0
      8 --> 54
      *9 --> 56
      10 --> 0
      11 --> 0
      12 --> 0
      13 --> 0
      14 --> 0
      15 --> 0

      0 --> 0
      1 --> 0
      2 --> 0
      3 --> 0
      4 --> 0
      5 --> 0
      6 --> 0
      7 --> 0
      *8 --> 54
      9 --> 0
      10 --> 0
      11 --> 0
      12 --> 0
      13 --> 0
      14 --> 0
      15 --> 0

      ________________________________________________________________________

      Thanks For Mitch Schwartz for his last problems where the idea has come from.


      Added by:Mostafa 36a2 (Al3ayesh)
      Date:2013-06-23
      Time limit:7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Go Deeper and Deeper in Mind..









      SPOJ Problem Set (classical)

      15256. Partition function (EASY)

      Problem code: PARCARD1

      You need to output the number of distinct ways of representing n as a sum of natural numbers (with order irrelevant) for all integer n from 0 to 10000 inclusive.

      First numbers of output must be:

      1 1 2 3 5 7 11 15 22 30 42 56 77


      Added by:Michael Kharitonov
      Date:2013-06-24
      Time limit:1s
      Source limit:10000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15257. Partition function (HARD)

      Problem code: PARCARD2

      You need to output the number of distinct ways of representing n as a sum of natural numbers (with order irrelevant) for given integer n.

      Input

      n, 0 ≤ n ≤ 108

      Example

      Input:
      2013
      Output:
      6805659785780163657391920602286596663406217911

      Added by:Michael Kharitonov
      Date:2013-06-24
      Time limit:30s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15259. Large Knapsack

      Problem code: LKS

      The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items.

      Just implement 0/1 Knapsack.

      Input

      First line contains two integers K and N, where K in the maximum knapsack size and N is the number of items. N lines follow where ith line describes ith item in the form vi and wi where vi is the value and wi is the weight of ith item.

      Output

      Output a single number - maximum value of knapsack. (All operations and the answer are guaranteed to fit in signed 32-bit integer.)

      Time limit changed to 2s on 02.07.11.

      Example

      Input:
      
      10 3
      10 3 7 3 8 8 4 6
      4
      Output: 11

      Constraints:
      K <= 2000000
      N <= 500
      Vi <= 10^7
      Wi <= 10^7

      Added by:Shikhar Sharad
      Date:2013-06-24
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15267. FRIEND CIRCLE

      Problem code: FRNDCIRC

      Lucy has made too many friends but she does not know how many friends are in her circle. Assume that every relation is mutual. If Lucy is Patty's friend, then Patty is also Lucy's friend. Your task is to help Lucy in keeping track of each person's circle size.

      Input Specification

      The first line of input contains one integer T (T<=10) specifying the number of test cases to follow. Each test case begins with a line containing an integer N (N<=100000), the number of new relations. Each of the following N lines contains couple of strings denoting the names of two people who have just formed relation, separated by a space. Names will have no more than 20 characters.

      Output Specification

      Print a line containing one integer, the number of people in the combined circle of two people who have just become friends.

      Input 

      1
      4
      Lucy Patty
      Patty Alice
      Alice Mira
      Tiffany Jayden 

      Output

      2
      2 3 4 2

      Added by:Vamos
      Date:2013-06-26
      Time limit:0.100s-0.579s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15270. A plus B

      Problem code: ICKAPLSB

      You only need to print the sum of two digits. Note that the only available language is ICK.

      Input

      Two digits a and b from {0,1,2,3,4,5,6,7,8,9}, separated by a space.

      Output

      a+b

      Example

      Input:
      5 5
      
      Output:
      10

      Added by:Mostafa 36a2 (Al3ayesh)
      Date:2013-06-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:ICK









      SPOJ Problem Set (classical)

      15285. Defend The Rohan

      Problem code: ROHAAN

      Kingdom of Rohan is under attack! There are N vital army stations. King will decide what army should be guarding what station, to get the best strategic advantage against Sauron attacks. All armies are already in some stations, but not necessarily the stations required by the king. As a result armies will have to be moved. Distances between any pair of stations are known. They are not necessarily symmetrical, because road from station A to B could be different than road from B to A. When a army moves, it doesn't have to take a direct road and instead can choose to cross other stations, if that results in a shorter path.

      Given the distances between stations and king's relocation orders, find the minimum total travel distance for all the armies.

      Input

      First line contains an integer T, number of test cases. Then the description of T test cases follow. Each test case starts with an integer N, which is the total number of army stations. Next N lines have N integers each, description of distances. b'th integer on line a is the distance from station a to station b. Description of kings orders follows. In a first line, a single integer R, number of orders. Next R lines will contain two integers s and d each, describing an order to move an army from station s to d.

      Constrains:

      1 <= T <= 50

      1 <= N, R <= 50

      1 <= distance <= 10^6

      1 <= s, d <= N

      Output

      Print a single line for each test case. A string "Case #t: " without quotes, where t is the number of test case, starting from 1. Following the string, you must print the total distance armies must travel during relocation.

      0 <= total distance <= 10^7

      Example

      Input:
      1
      3
      0 1 1
      1 0 1
      1 9 0
      2
      2 1
      3 2
      
      Output:
      Case #1: 3
      

      Added by:Syntax Terror
      Date:2013-06-27
      Time limit:1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      15310. Peter Quest

      Problem code: VPL2_BC

      Is Peter’s birthday! And his friends are preparing a big party, however, Peter is obsessed with a variation of the famous game Minesweeper, moreover, Peter hates losing, so if any of you or your friends can beat him in the game, he will get angry and will attend the party that everyone is organizing for him.

       

      This new mode of Minesweeper consists in building the gameboard given the mines, so, if the matrix has size of (2x2) and there is a mine in the position (0,0) of the matrix, the resultant gameboard will be *1 11 Your task is to beat Peter and celebrate his birthday before its too late! Please have in consideration that:

      • The cell (i,j) where there is a mine will be denoted as ’*’

      • The cell (i,j) where there is no mine will be denoted as ’-’

      • The cell (i,j) where there is N mines adjacent to it, will be denoted as a number from 1 to 8 (depending on the number of adjacencies)

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow the descriptions of T test cases.

      For each test case, you will have a line with three numbers N , M , K, denoting, respectively, the size of the matrix, formed by N columns and M rows, and K mines. Then, K lines will follow, each containing two numbers Ki and Kj denoting the position where the mine is in the board.

       

      Output

      For each test case you should print the string "Scenario #i:" where i represents the test case you are analyzing (starting from 1), then, in the next line, you shall print the gameboard as specified.

       

       

      INPUT

      OUTPUT

      3

      3 2 2

      0 0

      1 1

      3 3 3

      0 0

      1 1

      2 2

      8 8 10

      0 1

      5 0

      2 5

      4 5

      2 6

      5 6

      6 6

      5 7

      6 7

      7 7

      Scenario #1:

      *2

      2*

      11

      Scenario #2:

      *21

      2*2

      12*

      Scenario #3:

      1*1-----

      111-1221

      ----1**1

      ----2331

      11--1*32

      *1--13**

      11---2**

      -----13*

       

      Constraints - Subtask 1 (10%)

      • 1 ≤ T ≤ 10

      • 1 ≤ N ,M ≤ 8

      • 1 ≤ K ≤ min(8,N *M )

      Constraints - Subtask 2 (20%)

      • 1 ≤ T ≤ 10

      • 1 ≤ N ,M ≤ 128

      • 1 ≤ K ≤ min(128,N *M )

      Constraints - Subtask 3 (30%)

      • 1 ≤ T ≤ 10

      • 1 ≤ N ,M ≤ 1024

      • 1 ≤ K ≤ min(1024,N *M ) 

      Constraints - Subtask 4 (40%)

      • 1 ≤ T ≤ 10

      • 1 ≤ N ,M ≤ 6144

      • 1 ≤ K ≤ min(100000,N *M ) 


      Added by:Venezuelan Programming League
      Date:2013-06-29
      Time limit:5s-10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15312. Annoying Coins Quest

      Problem code: VPL2_BE

       

      Little Tita has always been annoyed by coins, she’s so annoyed that has devised a formula to assign an annoyment level to each transaction. The formula is quite simple, each coin c has a transfer annoyment value (Tc ) and a keep annoyment level (Kc ), then, each transaction has a total annoyment level (A) defined as the sum of the transfer annoyment (AT ) and the kept annoyment (AK ). Where:

       

       

      Given the list of coins that exist, the cost of a transaction and the list coins Tita has; find the minimum total annoyment level that Tita can guarantee for the transaction assuming the seller has an infinite amount of coins of each type and is not at all thinking about Tita’s annoyment level formula.

       

      Input

      The first line contains an integer T , which specifies the number of test cases. Then, will follow the descriptions of T test cases.

      Each test case will start with two integer N , the number of coin types that exist, and C, the cost of the transaction. The next N lines describe each coin type by with three integers Vi , Ti and Ki which represent the value, transfer annoyment and keep annoyment, respectively. Finally, a line with N integers Ai represent the amount of coins Tita has of each type, in the same order as the coins description.

       

      Output

      For each input case you must print a single line with the string Scenario #i: x, where i is the number of the test case (starting at 1), and x is the minimum annoyment level that Tita can guarantee for the transaction or −1 if the transaction cannot be made.

       

      INPUT

      OUTPUT

      3

      3 11

      2 1 10

      10 20 20

      3 1 1

      2 1 0

      4 11

      2 1 10

      10 20 20

      3 1 1

      1 10 1

      2 1 0 0

      2 3

      4 1 1

      3 1 1

      1 0

      Scenario #1: 24

      Scenario #2: 42

      Scenario #3: -1

       

       


      Added by:Venezuelan Programming League
      Date:2013-06-29
      Time limit:2s-5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15328. Hunter x Hunter

      Problem code: HXH

      Gon and Killua are two very talented hunters, and they are also very skilled fighters, however it is well known that Killua is faster and smarter than Gon, and Gon is stronger and is way more decided than Killua. That makes them almost the perfect team (they just need more time to become the most skilled hunters that ever lived) and they are so good as a team that they decided to fight and defeat many enemies (as much as they can) so they made a plan, as the enemies are in a N x N grid Gon decided to start at position 0,0 of this grid and Killua at position n-1,n-1. To maximize the number of defeated enemies Gon moves only to the Right and Down, and Killua to the Left and Up, they count how many enemies they defeated and stop when both of them are in the same cell and they give each other a high five. So if they complete the ride without doing this they will be mad, so that will not be a solution.

      However Killua wants this to be perfect, so he is tracing a new plan, but he does not know the best ride, as you are an amazing programmer he asked you for your help and you need to give him the maximum amount of enemies they can defeat together and then give each other a high five, only with this information the super brain of Killua will figure out the rest.

       

      Remember, the ride will not finish if they do not give each other that high five.

      The grid has this properties:

      ‘#’ is an obstacle that neither Gon nor Killua can pass through

      ‘.’ Is a walkable area

      ‘*’ is an enemy

      Also they move at the same time, if any of them cannot move, it will not be a valid move. They never stand still.

      Input

      The input consist on several test cases represented by T each of them start with an 2<=N<=500 the size of the grid and the grid itself.

       

      Output

      Just show the maximum number of enemies that both can defeat, and then give each other a high five. If this cannot be done print -1

       

      Input test:

      1

      5

      ..*..

      .*..*

      #...*

      ..*..

      .....

      Output test:

      3

       

      They could defeat all 5 if they weren’t going to give each other a high five, but as they do and they never stand still, they will defeat only 3 and then give a High five, Killua defeats 2 and Gon 1.

       


      Added by:Rodolfo Miquilarena
      Date:2013-07-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      15336. Hello Intercal!

      Problem code: ICKHELLO


      All you need to do Is to print "HELLO-INTERCAL" ,Of cource using INTERCAL.

      Input

      no input.

      Output

      HELLO-INTERCAL

      Example

      Input:

      Output:
      HELLO-INTERCAL


      Added by:Mostafa 36a2 (Al3ayesh)
      Date:2013-07-02
      Time limit:7s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:ICK









      SPOJ Problem Set (classical)

      15360. World Record Lunch

      Problem code: WRLUNCH

      A group of people is trying to beat the world record for the largest number of people having lunch at the same time. In order achieve this goal, they are using the country's largest bridge and they have decided to arrange the tables following the shape of the letter 'S'.

      The table layout can be described by 4 integers: NH, NV, H and V. The two first integers, NH and NV, represent respectively the number or rows and number of columns in the layout. The last two integers represent respectively the number of tables in each row and column. For a given layout, the tables are numbered consecutively, starting with table #1 in the top-right corner. The following figure illustrates several possible layouts:

      Thousands of groups of people are expected to come, and the organizers have to define where to seat everyone. Each group needs a certain number of tables and they do not share tables with other groups. Furthermore, a group wants their tables to be together and not split among rows and columns, that is, they want a set of consecutive tables either on the same row or on the same column. If this condition cannot be met, the group prefers to go away and have lunch at another place. The groups also enjoy having some privacy and prefer unoccupied adjacent tables, that is, no one at the table exactly before the first table of the group, and no one at the table exactly after the last table of the group. If this happens, we say that the group found a private place.

      Whenever a group arrives, the organization must decide where to seat that group based solely on the table occupation at the moment, without taking into account further groups that may be coming. Since a group will always be seated on consecutive tables, the position of a group can be defined by the index of the first table of the group. So, when a group arrive, the organization wants the following:

      • If there is a suitable private place for the group, then choose the lowest possible index guaranteeing privacy;
      • If no privacy can be ensured, but there is space for the group, then choose the lowest possible index with space for the entire group;
      • If there is no space available on a single row or column where the group would fit, then the organizers must send the group away.

      An example would be the following. Imagine a layout with NH=3, NV=2, H=5 and V=3 (the first layout give on the figure above). And now imagine that groups needing 5, 2, 3, 5, 4 and 2 tables arrive, in that order. This is what happens:

      In the beginning all tables are empty
      Group 1 needs 5 tables. It is put on index 1.
      Group 2 needs 2 tables. It is put on index 7.
      Group 3 needs 3 tables. It is put on index 11.
      Group 4 needs 5 tables. No position is available.
      Group 5 needs 4 tables. It is put on index 14 (with no privacy).
      Group 6 needs 2 tables. It is put on index 9 (with no privacy).

      Can you help the organizers on this task?

      The Problem

      Given a table layout (number of rows, columns and number of tables per row and column) and the description of groups arriving (specifying number of tables needed per group), your task is to calculate where each group should be seated following the rules described above.

      Input

      The first line contains 5 integers NH NV H V N, separated by single spaces. NH and NV indicate respectively the number of rows and columns of the table layout. H and V indicate respectively the number of tables per row and column. N indicates the number of groups arriving.

      Then come N lines, each one indicating Gi, the number of tables the i-th group needs. These lines come in order of arrival of the groups.

      Output

      The output should have exactly N lines, each one indicating where the respective group should seat. If there is a suitable position, the line should contain an integer indicating the index of the first table of the group. If no position is available, the line should contain the string "no", without the quotes.

      Restrictions

      The following limits are guaranteed for all the test cases that will be used for evaluating your program:

      1 ≤ NH ≤ 10 000   Number of rows
      NH-1 ≤ NV ≤ NH   Number of columns
      3 ≤ H,V ≤ 1 000   Number of tables in each row/column
      1 ≤ N ≤ 50 000   Number of groups
      1 ≤ Gi ≤ 1 000   Number of tables each group needs

       

      Example Input 1

      3 2 5 3 6
      5
      2
      3
      5
      4
      2
      

      Example Output 1

      1
      7
      11
      no
      14
      9
      

      Input Explanation 1

      It is the example given before in the problem statement.

       

      Example Input 2

      2 2 3 3 3
      3
      3
      1
      

      Example Output 2

      1
      5
      9

      Input Explanation 2

      In the end the tables would look like this:

      A few notes:

      • This is the first problem I add to SPOJ, hope you like it :)
      • The time limit is at least 6x the runtime of my C++ solution with no low-level optimizations or fast input/output. I have a Java solution passing within these time limits.
      • I'm not proficient enough in languages like Python to ensure the time limit is ok for those languages. I can increase the limits if needed.

      Added by:Miguel Oliveira
      Date:2013-07-06
      Time limit:1s-7s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem, used in CIIC 2013. Special thanks to Pedro Ribeiro









      SPOJ Problem Set (classical)

      15376. Running Median

      Problem code: RMID

      You will be given some integers in non decreasing order.
      and each time the median is queried you have to report and remove it.
      Take the smaller element as median in case of even elemenets.
       Input Specification:
      The input contains many test cases. Read until End Of File. 
      Each test case contains n (n≤100000) positive integers in non-decreasing order, 
      along with m queries indicated by -1, all on separate lines. (See the example.) 
      For a query, print the current median on a single line and remove it from the list. 
      Each test case ends with 0 on a single line, and two test cases will be separated by an empty line. 

      All integers are guaranteed to fit in a signed 32-bit container. 
      A query can only occur if the list is non-empty. 


      Output Specification:
      For each test case output m lines containing the answers to the corresponding queries. 
      Print an empty line after each test case. 
      Input:





      -1 
      -1 



      -1 




      -1 

      Output:






      Added by:jayant mukherji
      Date:2013-07-12
      Time limit:0.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15381. Cut The Rope

      Problem code: BFGCD

      Budi is a rope seller, He initially has two ropes to sell with length a and b where a and b is positive integer less than 10100. One day he meet with strange rich customer, the customer want to buy all rope with equal length only. Budi has an idea to sell all his rope to that customer: cut the rope until all his rope become equal length. Because Budi want maximum profit, he need to minimize the "cut" operation. But the customer doesn't like waiting, so budi must calculate and do "cut" operation quickly. The customer can wait 60 seconds only, Budi can cut the rope in exactly 10 seconds, so Budi have 50 seconds to calculate number of "cut" operation needed. Help Budi to calculate number of "cut" operation and length of each rope after cutting process done. But unfortunately your modern calculator isn't working, so the only way to do is using brainf**k calculator, with 8 valid commands only. Will you help Budi?

      Input

      First line of input there is an integer T ≤ 1000 denoting number of test case.

      Next T lines there're two positive integer a and b denoting length of rope that Budi has initially. Separated by a space (ASCII:32).

      Each line is terminated with newline character (ASCII:10). 

      Output

      For each case, output two number: first number is minimum number of cut operation, and second number is length of each rope after cutting process done.

      Example

      Input:
      4
      1 42
      42 1
      42 42
      12345 67890
      Output:
      41 1
      
      41 1
      0 42
      5347 15

      Other Info

      Input: generated 99.9% random with average digit is about 74.8 digits
      Output: Average digit for "cut" operation is about 34.7 digits, and length of rope after cutting process done is about 49.0 digits.
      This problem is using custom judge, so you can see the detail after you get AC/WA.
      Judge output format is like this: ("Code Length (Valid Command only)")"Cell Used"("BF Command executed").
      Click here to see my submission result for this problem.
      Judge output for my BF code is: (11820)1157(6571171311) meaning that my Valid BF commands = 11820 commands and My code using 1157 BF cell and 6571171311 commands executed.
      You can click (AC/WA) status for more detail.
      My code running time is 6.95s and using 1.9M of memory.
      Time limit is ~7× my BF program speed.


      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-07-15
      Time limit:50s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BF
      Resource:Own Problem, Own Idea, Own Story, Own Custom Judge









      SPOJ Problem Set (classical)

      15382. Factorial (Again!)

      Problem code: FCTRL5

      Have you solved FCTRL problem? 

      In this problem you need to do the same task (given positive integer n < 10100 you need to count number of zeroes at the end of the decimal number of n!), seems easy(?) but this time only Brainf**k language allowed.

      Input

      First line of input there is an integer T ≤ 1000 denoting number of test case.

      Next T lines containing an integer n.

      Each line is terminated with newline character (ASCII:10)

      Output

      For each test case, output number of zeroes at the end of the decimal form of number n!

      Example

      Input:
      6
      3
      60
      100
      1024
      23456
      8735373
      
      Output:
      0
      
      14
      24
      253
      5861
      2183837

      Other Info

      Input: 100% random log-uniform.
      This problem is using custom judge, so you can see the detail after you get AC/WA.
      Judge output format is like this: ("Code Length (Valid Command only)")"Cell Used"("BF Command executed").
      Click here to see my submission result for this problem.
      Judge output for my BF code is: (1340)501(392776170) meaning that my Valid BF commands = 1340 commands and My code using 501 BF cell and 392776170 commands executed.
      You can click (AC/WA) status for more detail.
      My code running time is 0.59s and using 1.6M of memory.
      Time limit is ~16× my BF program speed.


      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-07-15
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BF
      Resource:This Problem









      SPOJ Problem Set (classical)

      15383. Transform the Expression (Again!)

      Problem code: BFONP

      Have you solved ONP problem? Especially using brainf**k? This problem will give you extra points if you can solve ONP using brainf**k. Note that this problem has larger constraints.

      The task is: "Transform the algebraic expression with brackets into RPN form (Reverse Polish Notation). Two-argument operators: +, -, *, /, ^ (priority from the lowest to the highest), brackets ( ). Operands: only letters: a,b,...,z. Assume that there is only one RPN form (no expressions like a*b*c)."

      Input

      t [the number of expressions ≤ 1000]

      expression [length = See: "Other Info" part]

      [other expressions]

      Output

      The expressions in RPN form, one per line.

      Example

      Input:
      3
      (a+(b*c))
      ((a+b)*(z+x))
      ((a+t)*((b+(a+c))^(c+d)))
      
      Output:
      abc*+
      
      ab+zx+*
      at+bac++cd+^*

      Other Info

      Input: I deliberately not tell the input length, constraints, distribution, etc. You can guess it from judge output for my BF program (BF Cell Used) ;-) And of course I gernerate it randomly (But I can't tell the distribution).
      This problem is using custom judge, so you can see the detail after you get AC/WA.
      Judge output format is like this: ("Code Length (Valid Command only)")"Cell Used"("BF Command executed").
      Click here to see my submission result for this problem.
      I have two solutions for this problem:
      1) ID 9658441 (otimized): Judge output for my BF code is: (471)4320(606116310) meaning that my Valid BF commands = 471 commands and My code using 4320 BF cell and 606116310 commands executed.
      2) ID 9658572 (golfed): Judge output for my BF code is: (295)4320(888371635) meaning that my Valid BF commands = 295 commands and My code using 4320 BF cell and 888371635 commands executed.
      You can click (AC/WA) status for more detail.
      My code running time is 0.68s (optimized solution) and 1.47s (golfed solution) and both using 1.6M of memory.
      Time limit is ~14× my BF program top speed.


      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2013-07-15
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BF
      Resource:This Problem









      SPOJ Problem Set (classical)

      15429. Counting Ids

      Problem code: UCV2013A

      Little Willy just took a compilers course and is trying to implement his own compiler. First he wants to build a table with all the possible ids that a program could have. He knows that his language supports up to N different characters and any id can be up to L characters long. For example, when N = 2 (lets say characters can be 0 or 1), and L = 3, he could have the following ids: {0, 1, 00, 01, 10, 11, 000, 001, 010, 011, 100, 101, 110, 111}.

      You have to write a program that can help Willy find out the size of the table. Since the answer can be really big, you must print it modulo 1000000007 (10^9+7).

      Input

      The input contains several test cases. Each test case will consist of a single line containing two integers N and L. N is the number of characters that can be part of an id and L is maximum lenght supported by the language (1 <= N <= 65535, 1 <= L <= 10^5).

      End of the input is indicated by a test case with N = 0, L = 0 that should not be processed.

      Output

      For each test case output a single line containing the number of possible ids modulo 10^9+7.

      Example

      Input:
      2 3
      128 32
      0 0 Output: 14
      792805767
       

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Héctor Navarro









      SPOJ Problem Set (classical)

      15430. Alice in Amsterdam, I mean Wonderland

      Problem code: UCV2013B


      This is a fact that not many people know, but Alice lived in Amsterdam. Yes, there you go. And as many kids of the time, she used to go for some medicinal mushrooms to the drug store (the pharmacies, the coffee shops didn't exist yet). Usually, between the regular mushrooms, a magical one could be found, producing as expected, deep and vivid hallucinations. During one of those hallucinations, Alice was transported to a "wonderland", where many weird things happened. One thing was particularly dazzling for her: even though everything looked pretty familiar, the distance between monuments of the city was sometimes negative!!! Although, zero distance between two different monuments means a direct path doesn't exist. A loop from a given monument right back to it can be of length zero (with means that it can be reached instantly like in real life) or negative, like for regular paths. Alice also thought that she saw some positive distances for loops, but we should treat those cases as zero distance.


      Now, as a very smart girl as she is, she figured out a way to find the shortest path between any two monuments. Unfortunately, as expected, Alice forgot it when she got sober again. She was only able to remember that, in some cases, she could get stuck in a cycle path with negative distance. In such cases, there will always be a cheaper path to get to the same monument. This was one of the few things that had perfect sense for her: Your shortest path will be shorter if you take that cycle again and again, to infinity. Alice, has been trying to figure optimal distances all over again, but she can't. She doesn't want to trip again, she has been clean for longer than a year (good for her!!). Would you be so kind to help her?


      Given a list of monuments in a city, and their relative distances, find the shortest paths between some pairs of monuments.

      Input

      Each case, starts with one line containing N, the number of monuments in the test case (1 <= N <= 100). Next N lines will each contain one string K and N integers Kj, separated by single spaces. K is a name of a monument and will consist of at most 20 alphanumeric characters. Each integer Kj (0 <= j < N) in line i describes the distance from monument i to j (-2^30 <= Kj <= 2^30). Next line will contain a single integer Q (1 <= Q <= N^2). It will be followed by Q lines, each with a pair of integers (U, V), indicating the start and destination monument for the path that is queried (0 <= U, U < N).
      End of the input is indicated by a test case with N = 0 and should not be processed.

      Output

      For each test case, print a line "Case #tc:" (without quotes), where tc is the case number, starting from 1. Next Q lines should describe query results. If the optimal distance can be infinitely small, print only "NEGATIVE CYCLE". In other cases, start the line with "start_name-destination_name" followed by the actual result. If the destination can't be reached, print "NOT REACHABLE", otherwise print the integer distance.

      Example

      Input:
      2
      Nieuwkerk -1 1
      Oudekerk 1 0
      4
      0 0
      0 1
      1 1
      1 0
      3
      Nieuwkerk 0 -5 0
      Oudekerk 10 0 0
      Pierteck -100 -100 0
      9
      0 0
      0 1
      0 2
      1 0
      1 1
      1 2
      2 0
      2 1
      2 2
      0 Output: Case #1:
      NEGATIVE CYCLE
      NEGATIVE CYCLE
      NEGATIVE CYCLE
      NEGATIVE CYCLE
      Case #2:
      Nieuwkerk-Nieuwkerk 0
      Nieuwkerk-Oudekerk -5
      Nieuwkerk-Pierteck NOT REACHABLE
      Oudekerk-Nieuwkerk 10
      Oudekerk-Oudekerk 0
      Oudekerk-Pierteck NOT REACHABLE
      Pierteck-Nieuwkerk -100
      Pierteck-Oudekerk -105
      Pierteck-Pierteck 0
       

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Ignacio Calderón









      SPOJ Problem Set (classical)

      15431. Farmer Cream

      Problem code: UCV2013C

      Farmer Cream is a businessman that wants to live in the suburbs. He recently bought a little farm in Creamville and wants to earn money from it. After the sell, Farmer Cream has D money a remaining to spend. He's in negotiations with an important fi rm of farming but he thinks they're not being honest (they're trying to steal some money). He knows the number of fences F in the farm but he doesn't know the number of plots P to farm. The fi rm is off ering a budget B per plot, so he needs to multiply the budget per the number of plots to know the total amount of money to spend. He needs to know if he accepts the contract, for that, he
      needs to have at least M money to live after the buy. Otherwise, the firm is trying to bankrupt Farmer Cream and take over the farm.

      In order to do this. Farmer Cream needs your help. Assuming the fences are lines y = ax + b he only knows three things about them.

       

      1. There is no point in the farm where 3 or more fences collides. So, in one point of the farm there'll be zero, one or two fences.
      2. There are no parallel fences in the farm. So if we have two fences represented by y1 = a1x1 + b1 and y2 = a2x2 + b2 we assume that a1 <> a2.
      3. All the fences collide with each other

       

      Example with 3 fences and 7 plots

      In the example, there are 3 fences and 7 plots.

      Input

      The input contains several test cases, each one corresponding to a di fferent situation. Each test case consists of a single line with four integers D F B M (1 <= F,B,M <= 10^6) and (1 <= D <= 10^18) separated by a single space. D represents the remaining money of Farmer Cream, F represents the number of fences, B represents the budget in Bsf per plot and M represents the minimum amount of money that Farmer Cream needs to live.


      The end of input is indicated by a test case with D = F = B = M = 0.

      Output

      For each test case, you'll print: "The firm is trying to bankrupt Farmer Cream by X Bsf." where X represents the diff erence between money to spend plus the money he needs to survive and the money Farmer Cream has. Otherwise, you'll print "Farmer Cream will have Y Bsf to spend." where Y represents the money Farmer Cream will have to spend.

      Example

      Input:
      160 1 70 30
      500 3 50 100
      250000 40 300 5000
      0 0 0 0 Output: The firm is trying to bankrupt Farmer Cream by 10 Bsf.
      Farmer Cream will have 150 Bsf to spend.
      The firm is trying to bankrupt Farmer Cream by 1300 Bsf.

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Fernando Crema









      SPOJ Problem Set (classical)

      15432. Distributing V-Energy

      Problem code: UCV2013D


      As you probably know there is a new kind of energy called V-energy which is more afordable than electricity, and has some really interesting properties. The Universal Company on V-Energy has just reached your city and is currently planning the location of the distribution centers. You are given a map of the city, the list of the location of the distribution centers, and they need you to report which is the minimum ammount of energy that would reach a building of the city, and how many buildings share that ammount of energy

      V-Energy has the following properties:

       

      •  If a buiding has K units of V-Energy it will consume C units and distribute K - C to every building it is connected to. If K < C the building will consume K units and will not distribute any units of energy
      •  If a building receives V-Energy from di fferent sources it will only consume and distribute the energy with maximum value. For example, if a building receives K = 8 units of energy,and C = 3 it will consume 3 and distribute 5. But, if later the same building receives K = 6 units of energy, it will not consume or distribute this energy since previously it received a larger ammount of energy. If later on the same building receives K = 15 units of energy, it will consume 3 units, and distribute 12 units to its neighbors

      As you know, your city is a grid, with buildings on every intersection of the streets. Since V-Energy propagates only through streets, the streets map of the city is perfect for your job. Avenues run horizontally while streets run vertically. Note that sometimes a street or avenue can be blocked. The next figure shows a possible view of a city where street 1 is blocked between
      avenues 1 and 2, and avenue 2 is blocked between streets 0 and 1.

       

      Streets and avenues sample

      Input

      The input contains several test cases. Each case starts with a line containing the values K and C (ammount of V-energy each distribution center has and ammount of V-energy each building consumes). (0 <= C,K  <= 10000). The next line contains two values N and M denoting the number of avenues and streets on the city (1 <= N,M <= 1000). The following line will have one value B which denotes the number of street and avenues segments that are blocked and cannot distribute V-energy (0 <= B<=  N*M-N-M). The following B lines will have four values T I J1 J2. T indicates the type of the segment, can be either 'A' of 'S' to denote an avenue segment or a street segment. I denotes the street or avenue index (0 <=I < N). If it is an avenue segment then J1, J2 are the indexes of the starting street and ending street where the avenue is blocked. If it is a street segment, J1, J2 are the indexes of the starting and ending avenues where the street is blocked (0 <= J1 < J2 <= M). The next line will have the
      number D of deposits (0 <=  D <= min(1000,N*M)). The following D lines will have a pair Ai Si indicating that on the intersection of avenue Ai with street Si there will be a distribution center. (0 <= Ai < N, 0 <= Si < M).


      The end of input is indicated by a test case with K = C = 0.

      Output

      For each test cases you have to print a line containing two numbers Q and P indicating the minimum amount of energy that reaches a building on the city, and the number of building with that amount of energy.

      Example

      Input:
      2 1
      2 3
      0
      2
      0 0
      0 2
      12 2
      3 3
      2
      A 2 0 1
      S 1 1 2
      1
      2 0
      0 0 Output: 0 1
      2 1

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Héctor Navarro









      SPOJ Problem Set (classical)

      15433. Greedy Walking

      Problem code: UCV2013E

      Reginald is an N-dimensional traveler who wants to return to Filipistonia's Kingdom. He has an Obsessive-compulsive disorder in the way he travels so he can only do it following particular rules:

      1. Every step is exactly one unit long.
      2. He only moves in one dimension at a time.
      3. He only travels along the positive direction for each dimension.

      For example, when traveling on a two-dimensional place. He can travel along either the X or the Y axis at any given time, but never on both at the same time. Moreover, since he only travels along the positive direction and every step is one unit long, his only possible moves are (+1, 0) and (0, +1).

      Greedy Walking example

      As you can see, he is a Greedy Walker: once he makes a decision he assumes it is the correct and he never goes back.


      Given a starting position in an N-dimensional space (x1i, x2i, ... ,xni) your task is to count the number of diff erent travels he can make to position (x1f, x2f, ... , xnf) modulo 1000000007.

      Input

      The input contains several test cases, each one corresponding to a single travel. Each test case consists of a single line with one integer (1 <= N <=  50) followed by two lines each one with N integers, fi rst line will be initial position and second line will be target position.


      You can assume that 0 <= xki <= x1f <= 500 for all k, 1 <= k <= N and Sum(xki-xkf) <= 500.

      The end of input is indicated by a test case with N = 0.

      Output

      For each travel output a single line with one integer, the number of diff erent travels that exist from the initial position to the final position modulo 1000000007.

      Example

      Input:
      2
      2 1
      5 5
      4
      0 0 0 0
      1 2 3 4
      5
      1 2 3 4 5
      8 5 6 4 8
      5
      0 0 0 0 0
      100 100 100 100 100
      0 Output: 35
      12600
      19219200
      257055440

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Fernando Crema









      SPOJ Problem Set (classical)

      15434. Life on Fornax

      Problem code: UCV2013F


      NASA's Ultrasonic Crawling Vessel, UCV for short, has arrived to galaxy UDFj - 39546284 in the Fornax constellation and has found a peculiar type of bacteria-like lifeform. As you may imagine a plan to collect samples a bring them back to earth has been set in motion. However, it would be rather unfortunate if they are all dead by the time the UCV gets back, the trip would take approximately 13.42 x 10^9 years travelling at light speed. Therefore, its necessary to pick a number of bacterium so that there are at least some of them alive when the UCV arrives back.


      The UCV has studied the reproduction cycle of the bacterium inside a cryogenic pod and their behavior when released from the pod, but it lacks the algorithm to compute the fi nal number for such a long period of time. Fortunately, it's been designed with a wormhole plugin installation mechanism that allows to upload algorithms in a matter of only a few years.


      When the bacterium are inside the cryogenic pod, they follow a very simple reproduction cycle. Every year the following three phases, in order, occur:

      1. Aging phase: Each bacteria becomes a year older.
      2. Reproduction phase: Each bacteria gives birth to a new bacteria, this is slightly different to earth bacteria in the sense that the new and old bacterium are no identical. The new bacteria is 0 years old while the old bacteria is at least 1 year old.
      3. Passing phase: Each bacteria that reaches maturity, exactly M years old, dies.

      Fox example, this one reproduction cycle given a 0 years old bacteria and a 1 years old bacteria if maturity is reached at 2 years old.

      Reproduction cicle

      As you can see, during cryogenic reproduction, there's no fear of bacterium extintion, the number of births is at least as much as the number of deaths. However, when the pod is opened the bacterium enter into a strange iterative reduction phase, in each step of the reduction the oldest R bacterium die immediately; this process ends when there are fewer than R bacterium left. Note that the biggest problem arises when at some iteration there are exactly R bacterium left because they all die at that moment.

      NASA ha asked you to write the algorithm that will be uploaded to the UCV to determine the number of bacterium that will exist after the pod is opened here on earth.

      Input

      The input contains several test cases, each one corresponding to a single simulation. Each test case starts with a line with three integers, the maturity age (1 <=  M <= 50), the number of years for the UCV to come back (0 <= Y <=  10^12) and the reduction size (1 <= R <= 10^9); separated by a single space. The following line contains M integers, they
      represent the number of 0, 1, ...,M - 1 years old bacterium placed inside the cryogenic pod.


      The end of input is indicated by a test case with M = Y = R = 0.

      Output

      For each simulation output a single line containing a single integer, the number of bacterium that will be alive after the reduction process has nalized.

      Example

      Input:
      2 1 4
      1 1
      2 1 2
      1 1
      2 2 2
      1 1
      2 2 5
      1 1
      6 0 100000
      0 1 2 3 4 5
      6 1000000000000 100000
      0 1 2 3 4 5
      0 0 0 Output: 3
      1
      1
      0
      15
      21809
       

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Carlos Guía









      SPOJ Problem Set (classical)

      15435. Schedules

      Problem code: UCV2013G

      PEPE the singer has released a new song. He wants to control how many times his songs is played on RUMBA FM radio station. PEPE has hired two companies (A and B) to perform this task. Every day, they give him a schedule indicating the time when the song has been played on the radio. Song always takes the same number of seconds to play, so end times are not important. We are only interested in start times.


      On the first day PEPE received both schedules. They were almost identical. He verified that each entry of A corresponds to exactly one entry in B. He simply took a pencil, and he marked one entry in A, and then the corresponding entry in B. He folled with this approach as long as unmarked entries exist. The second day PEPE again received both schedules, but he found that the number of entries in both schedules is not the same. Moreover, the times did not match at all due to a human error. He said, "Oh Gosh!, I have to conciliate both schedules, finding the best possible match between them". He only trusts the entries that can be matched in both schedules. But how to match them? PEPE started by deciding how many seconds of error (difference) he is able to tolerate for two matched entries. Then he tried to fi nd the largest number of possible matches. For equally large machings, he is interested in smallest average time difference in seconds. Unfortunately, it may take too long since his new song is vere popular, having many hits in RUMBA FM. So, we need your help to perform this task automatically.

      Input

      The input consists in several test cases. Each test case starts with a line containing three integer numbers Na, Nb, and S, separated by single spaces. Na and Nb are the number of entries in A and B respectively (1 <= Na, Nb <= 200), and S is the tolerance in seconds (0 <= S <= 7200). The second line contains Na time stamps in the format hh:mm:ss separated by single spaces. The third line contains Nb time stamps in same format as the previous one. Note that all start times are in the same day.


      The end of the input is an empty test case, where Na = Nb = S = 0 and should not be processed.

      Output

      For each test case, the output is a single line containing an integer K and floating point number V rounder to one decimal place. K is the largest number of matches between schedule A and schedule B. V is the average time difference in seconds between the K matched entries. In case there is no possible match, your program should instead print "No matches"

      Example

      Input:
      4 2 120
      03:00:00 03:00:59 07:40:00 12:40:04
      02:59:14 12:41:45
      3 2 60
      03:00:59 07:40:00 12:40:04
      02:59:14 12:41:45
      0 0 0 Output: 2 73.5
      No matches

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Rhadamés Carmona









      SPOJ Problem Set (classical)

      15436. Slick

      Problem code: UCV2013H

      A maritime accident has caused oil to spill onto the seas of Felipistonia, which is a major natural disaster. The Felipistonia's government wants to clean up this mess before more damage occurs. To do this, they fi rst have to know how serious was the accident and the amount of oil that has been spilled into the sea. The only instrument the Felipistonia's government has to get
      information of the magnitude of this disaster, is the use of satellite images. With these images they can estimate how much money they have to spend to clean this mess. For this, the number of slicks in the seas and the size of each slick must be know. A slick is a patch of oil floating on water. Unfortunately, the Felipistonia's people are not very bright, so they have hired you
      to help them process the image.


      An example of an image obtained by the satellites is shown in Figure 1(a). This image can be transformed to 0's and 1's as seen in Figure 1(b). Given this binary matrix, your job is to count the number of slicks in the ocean and their corresponding size. Two adjacent pixels in the image are considered to be in the same slick if they are in the same row or the same column.

       

      (a) A satellite image of the spilled oil. (b) The representation of the image in a binary matrix


      Figure 1: (a) A satellite image of the spilled oil. (b) The representation of the image in a binary
      matrix

      Input

      The input contains several test cases, each one corresponding to a di erent satellite image. The first line of each case contains two integers that indicate the number of rows (N) and columns (M) in the image (1 <= N,M <= 250). Then N lines follows with M integers each, containing the information of the image.


      The end of input is indicated by a test case with N = M = 0. This case should not be processed.

      Output

      For each image, output the number of slicks in the sea. Additionally, output the size of each slick in ascending order and the number of slicks of that size.

      Example

      Input:
      10 10
      1 1 1 1 1 1 1 1 1 1
      1 1 1 1 0 0 0 0 0 0
      1 1 1 0 0 0 0 1 1 1
      1 1 0 0 1 0 0 1 1 1
      1 0 1 0 0 1 1 0 0 0
      0 0 0 0 0 0 0 0 0 0
      0 0 0 0 0 0 0 0 0 0
      1 1 1 1 1 1 1 1 1 1
      0 0 0 0 0 0 0 0 0 0
      1 1 1 1 1 1 1 1 1 1
      0 0 Output: 7
      1 2
      2 1
      6 1
      10 2
      20 1
       
       

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Francisco Sans









      SPOJ Problem Set (classical)

      15437. Tambourine

      Problem code: UCV2013I

      Little HH loves tambourines. He loves them so much that now he wants to build them. A tambourine is a musical instrument shown in Figure 1(a). As you can see in Figure 1(b) the tambourine is just a big circle of radius R with N smaller circles of radius r (r < R).

       

      Tambourine


      Figure 2: (a) A tambourine. (b) The radius of the circles is shown. (c) There is a 2N sides regular polygon inscribed in the outter circle


      HH knows the radius of the small circles (r), he also knows the number of small circles that he has (N). And he knows that the small circles should be centered on the center of the even sides of a 2N sides regular polygon inscribed in the big circle (the sides of this polygon each measuring 2r), as shown on Figure 1(c). Now HH wants you to help him fi nd the radius R of the big circle.

      Input

      The input contains several test cases. Each test case consists of two values r and N as described previously. (0 < r  100), (2 <= N <= 10000).


      The end of input is indicated by a test case with r = N = 0.

      Output

      For each test case you must print a number (rounded up to two decimal places) showing the radius of the big circle to build the tambourine.

      Example

      Input:
      1 4
      2 4
      1 8
      0 0 Output: 2.61
      5.23
      5.13

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Héctor Navarro









      SPOJ Problem Set (classical)

      15438. Valences

      Problem code: UCV2013J

      Mr. White has found a way to maximize the purity of crystals based on certain chemical compounds. He has observed that each compound is made of molecules that are linked together following the structure of a complete binary tree where every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Each node of the tree stores the valence of a molecule and is represented as an integer number. Mr. White uses an electronic microscope that dumps the molecule structure as a stream of integer numbers and would like to have your help on automatically obtaining the total valence of only the leaves of the given tree. For example, the sequence 4-3-2-6-0-3 represents the tree shown in the fi gure and the total valence of the leaves is 9.

       

       

      Sample Tree

      Input

      The input contains several test cases, each one corresponding to a particular compound. Each test case consists of a single line starting with an integer N (1  <= N  <= 1000000), followed by N integer numbers Vi representing the valences of each molecule separated by blank spaces (0 <= Vi <= 100).


      The end of input is indicated by a test case with N = 0.

      Output

      For each compound output a single line with the sum of the valences of the leaves of the tree.

      Example

      Input:
      6 4 3 2 6 0 3
      7 1 1 1 2 1 2 1
      0 Output: 9
      6
       

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Walter Hernández









      SPOJ Problem Set (classical)

      15439. Zombie Outbreak

      Problem code: UCV2013K

      As many books, movies and video games had shown us, a zombie outbreak was inevitable. However, all hope is not lost. As usual you've encountered a young girl that has been bitten but not transformed. Therefore, you've escorted her to a medial facility so her blood can be studied and a cure manufactured.

      Unfortunately, the medical facility, for obvious reasons, has not been resupplied in a while. The scientists there have asked you to pick several tools, viruses and whatnots, from N places in the city.

      Now that you have to go out again, you have created a map with the N + 1 locations: the medical facility (location 0) and the other N where the scientists need you to pick something up (numbered from 1 to N). You've also came up with M two-way paths between some of the locations and the probability to encounter a zombie pack on each of those paths. Note that this is isn't science fiction. If you encounter a zombie pack, you will not survive.

      You certainly want to fetch all the items and come back alive. You want to compute the maximal probability of picking every item and coming back to the medical facility (safe and sound) if you take a closed walk (cycle that allows node repetitions).


      Input

      The input contains several test cases. Each test case begins with two integers, the number of places you have to go to (1 <=  N <= 16) and the number of paths you came up with (1 <= M <= N^2), separated by a single space.

      The next M lines contain 2 integers and a real number separated by spaces. Two integers ui and vi (0 <= ui, vi <=  N and ui<>vi) are the locations this path connects. Real number pi (0 <= pi <= 1) represents the probability that you will encounter a zombie pack along this path.

      You may assume that, for all i <> j, probabilities pi and pj are independent from each other.

      The end of input is indicated by a test case with N = M = 0 and should not be processed


      Output

      For each test case output a single line with a single real number: the probability of getting back to the medical facility alive with all items. Round the result to exactly three places after decimal point. If there's no way to pick all items, you should output 0.000.


      Example

      Input:
      2 3
      0 1 0.3
      0 2 0.4
      1 2 0.2
      2 3
      0 1 0.3
      0 2 0.5
      1 2 0.1
      2 2
      0 1 0.1
      0 1 0.9
      2 3
      0 1 0.92
      0 2 0.92
      1 2 0.92
      2 3
      0 1 0.92
      0 2 0.92
      1 2 0.93
      0 0 Output: 0.336
      0.397
      0.000
      0.001
      0.000

      Added by:Hector Navarro
      Date:2013-07-22
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Local UCV 2013. Carlos Guía









      SPOJ Problem Set (classical)

      15453. Yet Another Electronic Device!!!

      Problem code: KCARRY



      Fascinated as he is by the uncanny world of electronics, our friend MKS now decides to launch his own creation --> A N-Digit Carry Finder(an analogue of a N-Bit Binary Adder) which can be used to find the number of times we can have a non-zero carry while adding two numbers(A=AnAn-1...A2A1 and B=BnBn-1...B2B1) having exactly N digits.

      It consists of 'N' Full Decimal Adders. The i-th Full Adder takes as input three digits Ai,Bi and Ci-1 and outputs a digit Ci(0 or 1), which is the carry generated on adding the digits Ai and Bi and Ci-1.(Ci=1 if Ai+Bi+Ci-1 >9, otherwise 0).

      This Ci is now provided to the next (i+1-th) Full Adder in order to be added with the digits Ai+1 and Bi+1 and also to the accumulator which as the name suggests accumulates the sum of all Cj(1<=j<=i).

      Note: C0=0 always and 0<=Ai,Bi<=9.

      For Example: Adding two numbers , A=4567 and B=734(or B=0734), the addition proceeds as shown and the accumulator gets a final value of 3.

      In the 1st Adder, A1=7,B1=4,C0=0 and A1+B1+C0=11. Therefore Carry C1=1.

      In the 2nd Adder, A2=6,B2=3,C1=1 and A2+B2+C1=10. Therefore Carry C2=1.

      In the 3rd Adder, A3=5,B3=7,C2=1 and A3+B3+C2=13. Therefore Carry C3=1.

      In the 4th Adder, A4=7,B4=0,C3=1 and A4+B4+C3=8. Therefore Carry C4=0.

      The Value in the Accumulator=C1+C2+C3+C4=3.

      http://www.spoj.com/content/utk1369:utk_kcarry

      Your Task is to find the number of ways of getting a value K in the accumulator while adding two numbers containing  at most N digits each. Note that we are adding the numbers in their base 10 representation. Since the total number of ways can be very large, print your answer modulo 1000000007(10^9 +7).

      Input

      The first line of input contains an integer T. Then T lines follow containing two space seperated integers N and K.

      Output

      Print the required answer modulo 1000000007(10^9 +7) in the ith line corresponding to the ith Test case .

       

      Constraints:

      1<=T<=500.

      1<=N<=1000.

      1<=K<=N.


      Example

      Input:
      4
      1 1
      2 1
      2 2
      3 3
      Output:
      45
      4500
      2475
      136125

      Explanation

      Example case 1.

      The carry appears when adding 
      1 and 9, 2 and 9, 3 and 9 ... 9 and 9=9 cases.
      2 and 8,3 and 8,4 and 8 ... 9 and 8=8 cases.
      3 and 7,4 and 7,5 and 7 ... 9 and 7=7 cases.
      .
      .
      .
      9 and 1=1 case.
      There are (9+8+7+6+5+4+3+2+1+0)=45 cases in total and in each case, the carry appears exactly once.


      Added by:Utkarsh Raj
      Date:2013-07-23
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Based on a problem appeared in Codechef COOK36









      SPOJ Problem Set (classical)

      15454. How to Handle the Fans

      Problem code: AKVQLD03

      Trey Parker and Matt Stone, the creators of “South Park” are having some problems handling their fans. The number of fans is so huge that can’t even count them properly. So they hired “N” employees for counting the fans. All the “N” employees had their own separate offices and they were located in a straight line with positions numbered as 1, 2, 3 … up to N. Fans can come to the office of any employee at any time and tell them how they feel about the show and if they are lucky enough, they may get to meet Trey Parker and Matt Stone.

      All the employees keep on updating Trey and Matt about the number of fans currently in their offices, so at each moment, they will have a list of “N” positions and the number of fans in each of these positions. Trey and Matt suddenly start taking a walk from office at position “A” to position “B” to meet their fans, but before they start walking they want to know the sum of all the fans in the offices from position “A” to “B”. But counting them one by one is taking a lot of time, so now they hired you, an awesome software engineer to do this task. Your task is to find the sum of all the fans present in the offices between positions “A” to “B” ("A" and "B" inclusive). Let’s see if you could do it fast enough.

      Input

      The first line of Input contains two integers “N” and “Q”. “N” is the no. of employees hired by Trey and Matt. “Q” is the no. of queries to be followed.

      Each of the next “Q” lines contain a query. A query can be of two types:

      “add P F” – this means that “F” no. of fans came to the office at Position “P”

      “find A B” – this means that Trey and Matt wants to know the sum of fans present at offices at positions “A” to “B”

      Output

      For each query of the type “find A B”, output the sum of fans present at offices at positions “A” to “B” in a different line.

      Constraints

      1 <= N <= 10^6

      1 <= Q <= 10^5

      1 <= A < B <= N

      1 <= P <=N

      1 <= F <= 10^4

      Example

      Input:
      
      10 10
      find 1 5
      
      add 5 8
      add 6 2
      find 4 5
      find 4 6
      add 2 4
      find 2 6
      add 6 7
      find 1 6
      find 7 10
      
      Output:
      0
      
      8
      10
      14
      21
      0

      Added by:Ankit Kumar Vats
      Date:2013-07-24
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Self









      SPOJ Problem Set (classical)

      15460. Selling Art

      Problem code: SELLINGA

      To the best of her friends’ knowledge, Irina is a great artist. That is why she decided to expose her work and conquer the world. Well, just sell it alright. To help her, her friends executed a decent strategy. For a whole month they went to “The Manége”, an arts exhibition hall in Saint Petersburg. They wrote down on a piece of paper the times at which collectionists enter and leave. Then they consolidated the data and realized that the times at which collectionists enter and leave is the same for every day. For example, collectionist A enters at time eA and leaves at time lA every day from Sunday to Saturday.


       

      To maximize exposure on any given day, she should arrive at the time the first collectionist enters and leave when the last to leave collectionist leaves, of course. This is impossible because she works every day and her boss won’t allow a day off. She can take several short breaks, fortunately.


       

       

      Her friends told her that as soon as she enters the Manége at a time t, all the collectionists currently present will see her work. Because of this, she realizes she can take k breaks. So, she can take a break, enter at a time t and go back to work and this will guarantee her that all currently present  collectionists will take a look at her work.

       

      She’s quite an artist but unfortunately not good with numbers. Knowing the times at which each collectionist enters and leaves the exhibition hall, she wants to know the minimum number of breaks k she needs to take in order to guarantee exposure to all collectionists. Help her. Write an awesome program for her.

       

      Note: actually, this problem is from a parallel universe so times are not the same as in ours. In this universe, the first second of a day is 0 and the last second of a day is 399,999.

       

      Input description

       

      The first line of input contains N (1 <= N <= 2 * 10^5), the number of collectionists attending the Manége on this day. Then follow N lines. The i-th line contains two space-separated positive integers (si,fi)  (0 <= si < fi <= 399 999), the seconds at which the i-th collectionist enters and leaves, respectively.

       

      Output description

       

      First print k, the minimum number of breaks Irina needs to take, on a single line. Then print k lines. On the i-th line print the time at which Irina needs to show up for the i-th break.

       

      If there are several answers, print the one with earliest break times, in order.

       

      Sample cases

       

      Sample Input

      Sample Output

      3

      0 5

      1 4

      2 6

      1

      2

      3

      0 1

      2 3

      4 5

      3

      0

      2

      4

       

      In the first sample case, three collectionists are present. The first collectionist arrives at second 0 and leaves at second 5. The second collectionist arrives at second 1 and leaves at second 4. The third collectionist arrives at second 2 and leaves at second 6. Irina can choose to arrive at seconds 2, 3, 4 and be guaranteed to have all three collectionists see her work. However, she chooses to arrive at second 2 because it is the earliest time.

       

      In the second sample case, she must take 3 breaks: no more than one collectionist is present at any given time.


      Added by:kojak_
      Date:2013-07-25
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Olimpiada de Programación PUCMM ACM-ISC 2013









      SPOJ Problem Set (classical)

      15498. Kawigi quote

      Problem code: KIMO4

      Thursday 25/7/2013, a friend of mine (Goodname) posted in our facebook group (Virtual Contests) a link of Kawigi's topcoder profile.

      He was amazed by Kawigi's quote as he tested it in Ideone to find it printing "C++Sucks". We all were amazed by this quote.

      But in a few minutes some other friend of mine (Mosa) commented on the post with this Ideone. Wow! he got it, but the fact that he is kind of greedy, he didn't want to tell us the secret. Now we want to think like Mosa to be able to solve this problem.

      Given a string your task is to find the values of m[0] and m[1] so that when we run this code we get the given string.

      Code

      #include <stdio.h>

      int primes [] = {2,3,5,7,11};

      double m[2] = {8242465576917890.0 ,494};

      int main() {
        m[1]--?m[0]/=primes[((int)m[1]+1)%5],main():printf((char*)m);
      }

      // this code prints the string "123".

      Input

      The first line of the input file contains an integer T (T <= 50) which is the number of test cases to follow.

      Each test case will be on a single line consisting of at most 6 alphanumeric characters (A-Za-z0-9).

      Output

      For each test case, print the values of m[0] and m[1], separated by a space.

      It's guaranteed that the solution will always exist. If there're multiple solutions, print any.

      Example

      Input:
      4
      123
      abdou
      mcMosa
      kimo3

      Output: 8242465576917890.0 494
      6966198460426549.0 487
      4484456159639948.0 483
      21357815651012032.0 488

      Special Thanks:

      -Mitch Schwartz for discovering issues with the problem.

      -Mosa Osama for writing the special judge of the problem, and I have to say Mosa's not greedy. ;)

       

      Added by:abdelkarim
      Date:2013-07-26
      Time limit:2s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:owner









      SPOJ Problem Set (classical)

      15506. Helping Igor

      Problem code: IGOR

      Dr Samuel has been working in one of his grim (and useless) experiments in order to take control of the humanity.

      Recently, he has been working in a hypnotic bomb, and he plans to launch it in the center of the city. Once it falls, all the inhabitants will be under his control, due to the properties of its principal element, the Samuelanium.

      Amusingly, the Doctor himself created this element, and he does not know its behavior! He has commanded Igor, his faithful sidekick (and slave) to describe it.

      Samuelanium’s behavior is pretty strange. According to Igor’s Notes:

      -Its atoms are only composed by electrons and protons and it has a chain-like shape.

      -On its sides there are two strange portals. They can suck the proton-electron chain in only one direction. Once a particle enters in a portal, it comes back from the other portal with its charge changed.

      -If the first particle in the chain is a proton, the charge of the last particle changes.

      For example, suppose we have the chain "+-+".

      As you can see, the first particle is a proton, so the last particle must change its charge, becoming "+--". Then, the chain is sucked by the left portal. The proton comes out from the right portal, having changed it charge, becoming "---"(as an electron). This occurs in one second.

      So, if the chain is represented as "+-+" at time 0, it will be represented as "---" at time 1.

      Doctor Samuel wants to know the state of this chain, having passed some seconds from its initial state.

      Unfortunately, Igor is exhausted. Can you help Igor and (ironically) help Doctor Samuel to control the humanity and conquer the whole world?

      Input

      Your program will be tested with t experiments.

      Every experiment begins with two integers, n and k. n represents the length of the Samuelanium chain, and k represents the number of queries that Samuel demands.

      Next, there will be a string of length n, composed only of '+' and '-'. '+' represents a proton, and '-' an electron. This chain represents its initial state (time 0).

      You must assume that the portal that sucks the chain is on the left side.

      Then, there will be k lines, with an integer ki, representing the time query you have been asked for.

      Output

      For each test case you must print one line containing "Experiment #i:", being i the ith case you are analyzing.

      Then, k strings, representing the chain in a given moment.

      Remember, protons are represented with '+' and electrons with '-', and there are no neutrons.

      Example

      Input:
      

      1

      3 4

      +-+

      0

      1

      2

      4

      Output:

      Experiment #1:

      +-+

      ---

      --+

      +++

      Constraints:

      1<=t<=15

      1<=n<=14

      10<=k<=1000

      0<=ki<=10^9


      Added by:Samuel Nacache
      Date:2013-07-29
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      15541. Simplified Hangul

      Problem code: SHANGUL

      Bob is an American boy and a huge fan of K-Pop ("Korean-Popular"), a popular music genre in South Korea. The songs are usually performed by boybands and girlbands, and they usually dance pre-determined choreographies and sing pre-determined lyrics.

      Bob already learned some choreographies, but he can't understand the lyrics very well. That's why he is studying the Korean language, in particular the Korean alphabet, Hangul. Bob has some images containing lyrics written in Korean, and needs to know how these texts would sound for an English speaker. Help him by creating a program that reads a image containing Korean text and outputs how it sounds.

      In this problem, we'll consider a very simplified version of Hangul. There are only 7 letters in this alphabet. Their drawing and sounds are given below:

       

      To form a word, the letters are written in sequence, from left to right. The word's sound is the concatenation of its letters' sound, in order. So, according to the given table, the word    , for instance, sounds like "gangnan".

      It's also possible to replace a letter in a word by two letters, one on the top of another, forming a block. The sound of a block is the concatenation of the sound of the top letter and the bottom letter. So, for instance, the block  sounds like "ua", and the word  sounds like "uaneoi".

      You are given a matrix that represents a black-and-white image containing a single word. The white pixels represent the background of the image, while the black ones indicate the word itself. Find out how the word would sound like.

      (PS: The problem setter is not a Korean speaker. Sorry for possible mistakes.)

      Input

      The first line of each test case contains two integers n and m (5 ≤ n ≤ 40, 7 ≤ m ≤ 520), the number of rows and columns of the image. The next n lines contain m characters each, and represent the image. The character '.' indicates a white pixel, while the character '#' represents a black pixel.

      Restrictions:

      • The first and last rows and columns of the image will always be blank;
      • There will be at least one letter in the image;
      • All letters in the image will be valid;
      • The length of each stroke may vary, but its width will always be 1 pixel;
      • The length of all vertical strokes in "a" and "eo" will always be odd, and the horizontal stroke will always intersect the vertical one on its midpoint;
      • The length of all horizontal strokes in "o" and "u" will always be odd, and the vertical stroke will always intersect the horizontal one on its midpoint;
      • The sequence of letters/blocks that form the word will be separated by at least one blank column;
      • There won't be any letter bellow another letter, except when a block is formed. This indicates that the word was written without linebreaks;
      • In a block, the bottom edge of the top letter and the top edge of the bottom letter will be separated by white pixels;
      • In a block, the leftmost pixel of both letters will be in the same column;
      • The letters/blocks that form the word may not be horizontally aligned;
      • The blocks and words may not make sense in (real) Korean.

      The last test case is followed by a single line containing two zeros.

      Output

      For each test case, print a string indicating how the given word sounds.

      Example

      Input:
      5 29
      .............................
      .###.#..#...###.#....#...#...
      ...#.##.#.....#.#....##..#...
      ...#.#..###...#.###..#...###.
      .............................
      19 38
      ......................................
      ..#...................................
      ..#...................................
      ..#................#..................
      ..###########......#..................
      ..#................#..................
      ..#................#..................
      ..#................#..................
      ...................#..................
      ...................#..................
      ..#................#..................
      ..#...................................
      ..#......................#............
      ..#......................#............
      ..#......................#............
      ..####...................#............
      .........................#............
      ...................#############......
      ......................................
      16 34
      ..................................
      ................................#.
      ....#######.....................#.
      .......#........................#.
      .......#...............##########.
      .......#........................#.
      .......#........................#.
      .......#........................#.
      .......#..........................
      ..................................
      ....#...........#.................
      ....#...........#......#..........
      ....#####.......#......#..........
      ....#...........#####..#..........
      ....#..................#..........
      ..................................
      0 0 Output:
      gangnan
      anio
      uaneoi

      Added by:Ricardo Oliveira [UFPR]
      Date:2013-08-01
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:UFPR Training Session









      SPOJ Problem Set (classical)

      15551. Do You Even Lift

      Problem code: DYEL

      Summer's coming up in a few months, so you decide to hit the gym to put on some muscle. When you arrive, you're confronted with dozens of machines, free weights, barbells, stationary bikes and more. All of this is quite confusing to a newcomer, so you just stand there confused, checking your cellphone a few times, and leave.

      After this less-than-stellar experience, you decide to do some research online. You learn that people train in things called "programs", which are instructions to determine how much weight to lift on a particular day. These are always of the form "Lift twice what you lifted three days ago, plus three times what you lifted 7 days ago", or similar. In general, such a "program" tells you that the weight you need to lift today is some combination of the weights you've lifted previously. The program also gives you some initial weights, for when the formula doesn't make sense.

      Being very clever, however, you decide that the advice you find during your research is for suckers. You won't even bother with known programs like Starting Strength, StrongLifts 5x5, or even CrossFit. What you'll do is much cleverer: You'll go to the gym, find the most jacked bro in there, and imitate his program. To figure out his program, you'll record what he lifts each day he goes to the gym, for a few days.

      Since you are lazy, of all the possible programs he could be following which would match your observations, you want only the shortest one (the one that mentions as few days back as possible). Can you find it?

      Input

      The input consists of multiple test cases, and starts with a positive integer T. T test cases follow.

      Each test case starts with a number K, the number of days you've watched the bro lift weights for. After that come K nonnegative integers W_i, denoting the weight he lifted each day, from oldest lifts to most recent ones. You are assured that the bro is indeed following a program.

      Output

      For each test case, output a single line, consisting of N space separated non-negative integers D_i, if the program says each day you should lift the sum of (D_i times the weight you lifted i days ago), for 1 ≤ i ≤ N. N is the length of the shortest solution you found and should not be printed

      Example

      Input:
      5
      10 48 64 96 128 192 256 384 512 768 1024
      8 3 3 2 25 136 782 4479 25659 
      8 3 3 24 87 381 1578 6639 27807
      14 3 3 1 2 4 8 16 32 64 128 256 512 1024 2048 
      8 16909 42737 110373 281321 722813 1848097 4739349 12131737
      Output:
      0 2
      5 4 1
      3 5
      2 0 0
      1 4

      Constraints

      1 ≤ T ≤ 5 * 10^3
      1 ≤ K ≤ 44
      K = 0 (mod 2)
      0 ≤ W_i < 2^63
      In every program, K ≥ 2N.
      Warning: You may need to use very big integers.

      Added by:Federico Lebrón
      Date:2013-08-04
      Time limit:0.5s-6s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Federico Lebrón









      SPOJ Problem Set (classical)

      15553. Hamsters

      Problem code: STC00

      Byteasar breeds hamsters. Each hamster has a unique name, consisting of lower case letters of the English alphabet. The hamsters have a vast and comfortable cage. Byteasar intends to place a display under the cage to visualize the names of his hamsters. This display is simply a sequence of letters, each of which can be either lit or not independently. Only one name will be displayed simultaneously. The lit letters forming the name have to stand next to each other, i.e., form a contiguous subsequence.

      Byteasar wants to be able to display the names of the hamsters on at least M different positions. However, he allows displaying the same name on multiple different positions, and does not require to be able to display each and every hamster's name. Note that the occurrences of the names on the display can overlap. You can assume that no hamster's name occurs (as a contiguous fragment) in any other hamster's name. Bytesar asks your help in determining the minimum number of letters the display has to have.

      In other words, you are to determine the minimum length of a string (consisting of non-capital letters of the English alphabet) that has at least M total occurrences of the hamsters' names (counting multiplicities). (We say that a string S occurs in the string T if S forms a contiguous fragment of T.)

      Input

      The first line of the standard input holds two integers N and M (1<=N<=200, 1<=M<=109), separated by a single space, that denote the number of Byteasar's hamsters and the minimum number of occurrences of the hamsters' names on the display. Each of the following N lines contains a non-empty string of non-capital letters of the English alphabet that is the hamster's name. The total length of all names does not exceed 105 letters.

      Output

      The first and only line of the standard output should hold a single integer - the minimum number of letters the display has to have.

      Example

      For the input data:

      4 5
      monika
      tomek
      szymon
      bernard

      the correct result is:

      23

      The shortest display could be, for example: szymonikatomekszymonika. It has 5 occurrences of the hamsters' names in total: szymon and monika occur twice each, tomek just once, and bernard does not occur in it at all.


      Added by:Tooru Ichii
      Date:2013-08-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:POI XVII









      SPOJ Problem Set (classical)

      15554. Niceness of the string

      Problem code: IITKWPCA

         The niceness of a string s (s comprises of a-z, A-Z and space characters only) is calculated using steps given below.

         1. First seperate out the string into continous non zero length string without space. eg. Let us take s = "now do it now". You can break this into four small strings as "now", "do", "it" and "now". Call the set of these small strings to be G.

         2. Now reverse all the strings in G. eg. "won", "od", "ti", "won".

         3. Finally you calculate number of distinct strings in you set. in this case answer is 3. as "won", "od" and "ti" are set of distinct strings. Note that "won" comes twice but counted only once.

          So you have to find niceness value of a string s.

          Note that given string s can contain more than one continous spaces. eg. "now      do it now     ". Niceness value of this is also same as above given example.

      Input

      T: number of test cases. (T <= 100)

      for next T lines, every line contains one string s (size of string >= 1 && <= 10^4)

      Output

      For every test case, output niceness value of given string s.

      Example

      Input:
      4
      now do it now
      now do it now
      I am good boy
      am am
      Output:
      3
      3
      4
      1

      Added by:praveen123
      Date:2013-08-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15555. Check the coprimeness

      Problem code: IITKWPCB

          Find largest non-negative number less than or equal to floor (N/2) which is coprime to N.

          Two number a and b are considered to coprime if gcd (a, b) = 1.

      Input

          T : numbr of test  cases (T <= 1000)

          For next T lines, every line contains n >= 1 && n <= 10^12;

      Output

          For each test case, output as described in the problem statement.

      Example

      Input:
      4
      3
      4
      5
      100

      Output:
      1
      1
      2
      49

      Added by:praveen123
      Date:2013-08-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15556. Count right angle triangles

      Problem code: IITKWPCC

          You are given n points in a 2D plane. You are asked these an inherently simple questions about them.

          You  have to find out number of right angle triangles (having base and height parrallel to axis) with the property that length of base and height is same.

      Input

      First Line will n: number of points. (n <= 10^5).

      For next n lines  each line will contain two integers x and y.  (-10^8 <= x, y <= 10^8). 

      Output

      You have to output a single line containing the answer to question.

       

      Example

      Input:
      5
      0 0
      1 0
      2 0
      0 1
      0 2
      Output:
      2

      Added by:praveen123
      Date:2013-08-05
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15557. Partition the sticks

      Problem code: IITKWPCD

      You are given a set of N sticks and are required to partition them into groups of exactly 3 sticks each. While doing so, you can leave out any number of sicks out of these groups (in particular, no groups may be formed). One condition needs to be met: sticks in each group need to form a triangle. A triangle can be constructed if sum of any two sticks lengths is greater than the third length.

      Your are required to partition the sticks so that the sum of triangle areas from all the groups is maximized.


      Input

      Very first line of the input contains integer T: number of test cases (1 <= T <= 5).

      For each test case, first line contains integer N: number of sticks. (1 <= N <= 15).

      Second line contains N space separated integers: the lengths li of the sicks. (1 <= li <= 10^3, 1 <= i <= N). 


      Output

      For each test case, output the maximal area in a separate line. Round value to exactly 6 decimal places. Always print exactly 6 decimal places.


      Example

      Input:
      3
      3
      7 8 5
      4
      7 8 6 3
      3
      7 2 1

      Output:
      17.320508
      20.333163
      0.000000

      Added by:praveen123
      Date:2013-08-05
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:









      SPOJ Problem Set (classical)

      15558. Let us play with strings

      Problem code: IITKWPCE

          Feluda likes palindromes very much. He is so fond of palindromes that if you give him any string, he will try to break it into continous palindromes.
          As Feluda is a smart boy, he will do try to break the string into minimum no of such continuous palindromes. You have to help Prabhu. Find out the answer for the problem if he is given a string s.

      Input

      T : number of test cases (T <= 100)
      next T lines contain a string s (length of s <= 2000)

      Output

      For every test case print one line having answer as given in the problem statement.

      Example

      Input:
      4
      abacdc
      ababa
      ababbacababbad
      abcd
       
      Output:
      2
      1
      5
      4

      Added by:praveen123
      Date:2013-08-05
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15559. Help Feluda with mathematical equations

      Problem code: IITKWPCF

          Feluda likes numbers very much but hates prime numbers too much. For a fixed n, you gave Feluda eqution x^2  + y^2 + n = (x + y) ^ 2. Now you only want positive integral solution of x and y. Feluda being an intelligent person gave you all the pairs of (x, y) but he missed the pairs which had x as a prime number.

          For all the solution that Feluda gave you, we want you to just print those values in the following format: first print the number of such x's, then the possible values x sorted in increasing order in a line seperated by single space. If no such numbers exist, then print a 0 in the line.

      Input

      T : number of test cases (T <= 100)
      For next T lines each line contain n (n <= 10^12)

      Output

      For every test case print as stated in the problem statement.

      Example

      Input:
      3
      4
      24
      100
      Output:
      1 1
      24
      4 1 4 6 12
      4 1 4 6 12
      4 1 10 25 50

      Added by:praveen123
      Date:2013-08-05
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15560. Help the old King

      Problem code: IITKWPCG

           Once upon a time there lived a king in a far far country. In the country, there are n cities and m roads. He was severly attacked by his enemy. The enemy damaged all the cities of King's country. As the roads between the cities had been damaged, the King wanted to repair those. So he decided to launch a tender for this.

           As King's country is a well managed country. By well managed country, we mean that it is possible to go from each city to any other city. But now as the city has been destroyed by enemies, all the roads are broken, the king will like to rebuild the roads in such a way that it is still a well manged country.
          
          Cost of repairing the road in the country is really wierd, it is not addition of costs but it is instead multiplication of those. What it means that if the king decides that he should repair 5 roads, then total cost of repairing those roads will be multiplication of all the 5 costs.

           As the King's treasure has been damaged by the attack of foreign city, he would like to spend minimum amount of money and that the will want that his country still remains well managed country. Surprisingly the company that was given tender had a rule that all the costs will be in powers of two, as they were really love with binary numbers.

           As value of the total cost can be really large. We do not want to know the actual cost, instead output number of divisors of the number.

      Input

      T: number of test cases (T <= 5)
      n and m (n <= 10^5 && m <= 2 * 10^5)

      Next m lines will have a, b, c, which denotes that cities a and b are connected with road of cost c.

      (c >= 2 && c <= 10^18 && c will always be power of 2) (1 <= a <= n) and (1 <= b <= n)

      Output

      For each test case, output a single line containing a number as stated in the problem..

      Example

      Input:

      4

      2 1

      1 2 16

      3 2

      2 3 32

      1 2 16

      3 3

      2 3 32

      1 2 16

      1 3 64

      5 5

      1 2 2

      2 3 2

      1 3 4

      3 4 16

      3 5 8

      Output:

      5

      10

      10

      10


      Added by:praveen123
      Date:2013-08-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15561. Find Number Of Pair of Friends

      Problem code: IITKWPCH

          You are given n numbers. Any two number are called friends if they have some digit common. eg. (11, 12) and (15, 4561) are friends but (33, 556) is not.

          Find out no of pairs which are friends.

          (Formally speaking Let us assume the n numbers be are stored in array a[]. You have to find out number of i and j pairs such that i < j and a[i] and a[j] are friends.).

      Input

      T : no of test cases (T >= 1 && T <= 7) 
      For each test case, you will be given two lines, first line will contain n <= 10^6
      then in next n line each line will contain a single integer representing a[i] (a[i] >= 1 && a[i] <= 10^18)

      Output

      For every test case print a line
      containing number of such pairs as mentioned in the problem statement.

      Example

      Input:
      4
      2
      12 13
      3
      10 12 24
      3
      5 6 7
      4
      10 11 211 3

      Output:
      1
      2
      0
      3


      Added by:praveen123
      Date:2013-08-05
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:general problem









      SPOJ Problem Set (classical)

      15562. Find Lexicographically Smallest Permutation

      Problem code: IITKWPCI

      You are given n numbers a1, a2, , , an. You have to permute the numbers in such a way that resulting permutation should be lexicographically smallest . But there is a problem, you can not swap every pair of numbers. You can only swap the position i and j if they are good position. You will be given m pairs of i and j's which will denote good positions.

      So complying to restrictions posed here, find the lexicographically smallest permutation of a1, a2, , , an.

      Definition:  (a1, a2. ... an) is lexicographically smaller than (b1, b2. .. bn) if first index i where ai and bi differs, ai < bi satisfies.

      eg. (1, 2, 3, 4) is smaller than (2, 1, 3, 4)

      Input

      T : number of test cases (T <= 10)

      Next Line will contain n and m. (1 <= n <= 10^3 and 0 <= m <= min (n * (n - 1) / 2, 10^5).

      Next Line will contains a1, a2, , , an. (a[i] >= 1 && a[i] <=10^6)

      For next m lines, each line will contain i, j seperated by space which will denote that you can swap ai and aj.

      Output

      For each test case, output n numbers representing the permutation of a1, a2, , , an according to problem statement.

      Example

      Input:
      2
      3 1
      3 2 1
      2 3
      4 2
      2 4 3 1
      1 3
      3 4
      Output: 3 1 2
      1 4 2 3

      Added by:praveen123
      Date:2013-08-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15563. Check the string Powers

      Problem code: IITKWPCJ

      Feluda likes strings and mathematics very much. As Feluda is still a child, he was only recently introduced to concept of powers. Being a novice guy, he thinks about powering strings as well as numbers. He defines A^n (A powered to n) to be A + A + ... + A which is a concatenation of n copies of A. For example "bhupkas"^2 = "bhupkasbhupkas".

      He wants to check if given two strings A and B, can he find such positive integers n and m so that A ^ n = B ^ m. We are only interested in YES/NO answer, no need to give n and m values.


      Input

      First line contains integer T: number of test cases (T <= 100).

      Single line per test case containing strings A and B. Both will be non-empty, of lengths of at most 10^5, composed only of lower case letters.


      Output

      For each test case, output "YES" if it possible to find integers n and m so that A ^ n = B ^ m or "NO" otherwise (quotes for clarity).


      Example

      Input:
      3
      a a
      ab ba
      praveen praveen
      
      Output:
      YES
      NO
      YES

      Added by:praveen123
      Date:2013-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:









      SPOJ Problem Set (classical)

      15565. Find Distances In A Plane

      Problem code: IITKWPCL

          Feluda loves reading city maps a lot. Now he has got a map of a city where each house is denoted with its x and y coordinate. As he is interested in estimating how good is arrangement of city, Should he would ask you these two questions.

         1. What is minimum distance between any two houses ?

         2. What is maximum distance between any two houses ?

      Now given n points in a plane, You have to answer these two questions? As Feluda is scared by precision of decimal number representation in computers, you should tell Feluda the square of these distances.

      Input

      First line will contain n : no of houses. (n >= 2 && n <= 10^5)

      Then next n lines where each line will contain x and y coordinate of house seperated by a single space. (-10^9 <= x , y <= 10^9).

      Output

      Output one line containing squares of minimum and maximum distance respectively seperated by single space. 

      Example

      Input:
      10
      0 0
      5 1
      9 2
      12 3
      14 4
      15 5
      16 7
      17 10
      18 14
      19 19
      Output:
      2 722

      Added by:praveen123
      Date:2013-08-06
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15566. Coprime Again

      Problem code: IITKWPCM


           As You had known upto now that Feluda is very good in mathematics, Now he decided to understand the properties of coprime numbers. Two numbers are called coprime if greatest common divisor of those numbers is 1. One day feluda was reading mysterious book in which he found this problem.

          For a given positive integer n, Find out product of all the numbers from 1 to n excluding those which are not coprime to n. As this product can grow very large and Feluda being a small child gets scared from large numbers. Hence he wants that you should output the product modulo n.

         Help little Feluda to solve this problem.

      Input

      T : number of test cases. (T >= 1 && T <= 10^4)

      For next T lines, you are given an integer n such that 1 <= n <= 10 ^ 18.

      Output

      For each test case, output one line as stated in the problem statement.

      Example

      Input:
      2
      2
      5
      Output:
      1
      4
      For Who are going TLE and want to solve easier version. Please go to http://www.spoj.com/problems/IITKWPCQ/

      Added by:praveen123
      Date:2013-08-06
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15567. Playing With Balls

      Problem code: IITKWPCN

          There are W white balls and B black balls in a bag. A magician is performing tricks by drawing balls from the bag.

          In each step, the magician randomly removes any two balls from the bag. If the drawn balls are of the same color, he will put one white ball in the bag, otherwise he will put a black ball in it. The two drawn balls from the bag from the ball are discarded.

          He keeps on doing the above tricks until there is only one ball remaining in the bag.

          Given W and B, you have to determine the probability that the color of last ball remaining in the bag is black. You should print the answer with accuracy of upto 6 decimal digits.

      Input

          T : no of test cases (1 <= T <= 10^4)

          For every test case W and B  are given (0 <= W <= 10^8 and 0 <= B <= 10^8 and W + B != 0)

      Output

          For each test case, output the probability as stated in the problem statement.

      Example

      Input:
      2
      1 1 1 2
      Output:
      1.000000
      0.000000

      Added by:praveen123
      Date:2013-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15568. Fire Extinguishers

      Problem code: STC01

      Byteasar has had a new palace built. It consists of N chambers and N-1 corridors connecting them. Each corridor connects exactly two chambers. The rooms are numbered from 1 to N. There is only a single entrance to the palace, which leads to chamber no. 1. For each chamber there is exactly one route leading to it from the entrance, without turning back on the way. In other words, the chambers and the corridors form a tree - a connected acyclic graph.

      The fire marshal who is to approve the building demands placing fire extinguishers inside. The following are his exact requirements:

      • The fire extinguishers should be placed in (some) chambers, and one chamber may store any number of extinguishers.
      • Each chamber has to be assigned one fire extinguisher, though it may be stored in another chamber.
      • Each fire extinguisher can be assigned to at most S different chambers.
      • For each room its assigned extinguisher is within the range of K corridors.

      Byteasar has a week spot for lavish palaces, so it is no surprise he has very little money now, right after completion of another splendid palace. Therefore he is interested in the minimum number of fire extinguishers sufficient for satisfying fire marshal's demands.

       

      Input

      The first line of the standard input contains three integers N, S and K separated by single spaces, 1 <= N <= 100000, 1 <= S <= N, 1 <= K <= 20. Each of the following N-1 lines holds two integers separated by a single space. Line no. i+1 contains the numbers Xi Yi denoting the corridor connecting chambers no. Xi and Yi.

      Output

      The first and only line of the standard output is to hold one integer - the minimum number of fire extinguishers that have to be installed in palace.

      Example

      For the input data:

      12 3 1
      1 12
      3 8
      7 8
      8 9
      2 12
      10 12
      9 12
      4 8
      5 8
      8 11
      6 8
      

      the correct result is:

      4

      Added by:Tooru Ichii
      Date:2013-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:POI XVI









      SPOJ Problem Set (classical)

      15569. Antisymmetry

      Problem code: STC02

      Byteasar studies certain strings of zeroes and ones. Let S be such a string. By Sr we will denote the reversed (i.e., "read backwards") string S, and by SI we will denote the string obtained from S by changing all the zeroes to ones and ones to zeroes.

      Byteasar is interested in antisymmetry, while all things symmetric bore him. Antisymmetry however is not a mere lack of symmetry. We will say that a (nonempty) string S is antisymmetric if, for every position i in S, the i-th last character is different than the i-th (first) character. In particular, a string S consisting of zeroes and ones is antisymmetric if and only if S=SIr. For example, the strings 00001111 and 010101 are antisymmetric, while 1001 is not.

      In a given string consisting of zeroes and ones we would like to determine the number of contiguous nonempty antisymmetric fragments. Different fragments corresponding to the same substrings should be counted multiple times.

      Input

      The first line of the standard input contains an integer N (1 <= N <= 500000) that denotes the length of the string. The second line gives a string of 0 and/or 1 of length N. There are no spaces in the string.

      Output

      The first and only line of the standard output should contain a single integer, namely the number of contiguous (non empty) fragments of the given string that are antisymmetric.

       

      Example

      For the input data:

      8
      11001011

      the correct result is:

      7

      Antisymmetric fragments are: 01 (occurs twice), 10 (also twice), 01011100, and 001011.


      Added by:Tooru Ichii
      Date:2013-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:POI XVII









      SPOJ Problem Set (classical)

      15571. Difference

      Problem code: STC04

      A word consisting of N lower-case letters of the English alphabet ('a'-'z') is given. We would like to choose a non-empty contiguous (i.e. one-piece) fragment of the word so as to maximise the difference in the number of occurrences of the most and the least frequent letter in the fragment. We are assuming that the least frequent letter has to occur at least once in the resulting fragment. In particular, should the fragment contain occurrences of only one letter, then the most and the least frequent letter in it coincide.

      Input

      The first line of the standard input holds one integer N (1 <= N <= 106) that denotes the length of the word. The second line holds a word consisting of N lower-case letters of the English alphabet.

      Output

      The first and only line of the standard output is to hold a single integer, equal to the maximum difference in the number of occurrences of the most and the least frequent letter that is attained in some non-empty contiguous fragment of the input word.

      Example

      For the input data:

      10
      aabbaaabab

      the correct result is:

      3

      Explanation of the example: The fragment that attains the difference of 3 in the number of occurrences of a and b is aaaba.


      Added by:Tooru Ichii
      Date:2013-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:POI XVIII









      SPOJ Problem Set (classical)

      15572. Garden

      Problem code: STC05

      Byteen, Byteasar's wife, simply loves flowers. She has decided to have a garden near their house. Byteen is a perfectionist: she would like her garden to be square with sides parallel to North-South and East-West directions. Moreover, Byteen wants each corner of the garden to contain one of the N apple-trees growing nearby.

      Byteasar has learned about his wife's plans just before the final match of the World Cup in soccer. He knows that his wife is keen about the garden and, therefore, that it must be created instantly. To save some time, he asked her what exactly is her dream location of the garden - he knows that Byteen will surely check all the possibilities before making a final decision. Help Byteasar to find out how much time he has left, assuming that checking a single location for the garden takes Byteen exactly one second.

      Input

      The first line of the input contains one integer N, 1 <= N <= 105, the number of apple-trees growing near Byteen's and Byteasar's house. For simplicity, the locations of trees are given in a Cartesian coordinate system. Each of the following N lines contains two space-separated integers Xi and Yi, -106 <= Xi, Yi <= 106, the coordinates of the i-th apple-tree. No pair of coordinates appears in the input twice.

      Output

      Your program should print a single integer: the number of seconds Byteen will spend on checking all possible locations of the garden, each location containing apple-trees in all its corners.

      Example

      For the input data:

      6
      0 0
      0 1
      1 0
      1 1
      3 0
      3 1

      the correct result is:

      1

      Added by:Tooru Ichii
      Date:2013-08-06
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ONTAK 2010









      SPOJ Problem Set (classical)

      15573. Keyboard

      Problem code: STC06

      Byteman has received an extraordinary keyboard as a gift. The keyboard is a rectangle consisting of N rows and M columns with N*M keys placed on it. Moreover, all keys except the one in the top left corner are covered with domino tiles of size 1 x 2, so there are (N*M-1)/2 domino tiles in total. At any time, Byteman can move onto the free key one of the domino tiles adjacent to it by the shorter side. He can also press keys, but only if they are not covered.

      Byteman would like to test (i.e., press) all the keys corresponding to vowels, that is, the letters aeiou or y. What is the minimum number of tile moves necessary to do that?

      Input

      The first line of the input contains two integers N and M (1 <= N,M < 70) that describe the dimensions of the keyboard. The next N lines contain M lowercase letters of the English alphabet each, describing the rows of the keyboard. Each of the next N lines contains M characters describing placement of the domino tiles: . (ASCII code 46) denotes an uncovered key, - (ASCII code 45) denotes a key covered by a domino tile placed horizontally and | (ASCII code 124) - a key covered by a tile placed vertically.

      Output

      If it is not possible for Byteman to press all the keys corresponding to vowels, your program should output just the single word "NIE" (i.e. no in Polish). Otherwise output the minimum number of tile moves that Byteman must make in order to press all the requested keys.

      Example

      For the input data:

      3 3
      ytr
      hgf
      dsa
      .--
      |||
      |||

      the correct result is:

      2

      Added by:Tooru Ichii
      Date:2013-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ONTAK 2010









      SPOJ Problem Set (classical)

      15574. Railway

      Problem code: STC07

      A railroad siding consists of two (dead-end) sidetracks 1 and 2. The siding is entered by track A, and left by track B.

      There are N cars on track A, numbered from 1 to N. They are arranged in such a way that they enter the siding in the order a1, a2, a3, ..., aN. The cars are to be transferred to the siding, so that they leave it by track B in the order 1, 2, 3, ..., N. Each car is to be transferred once from track A to one of the sidetracks 1 or 2, and later (possibly after some transfers of the remaining cars) once from that sidetrack to the track B. The sidetracks are long enough to store even the longest trains, so there is no need to worry about their capacity.

      Input

      The first line of the standard input holds one integer N (1 <= N <= 105) that denotes the number of cars for transfer. The second line stores the numbers a1, a2, a3, ..., aN that are a permutation of 1, 2, 3, ..., N (i.e., each ai belongs to {1, 2, 3, ..., N}, and all these numbers are unique), separated by single spaces.

      Output

      The first line of the standard output should contain the word TAK (yes in Polish) if there is a way of transferring the cars so that they enter track B in the order 1, 2, 3, ..., N, or the word NIE (no in Polish) if it is impossible. If the answer is TAK, the second line should give, separated by single spaces, the numbers of sidetracks (1 or 2) to which successive cars a1, a2, a3, ..., aN are moved in a correct transfer. If there are several ways of making the transfer, choose lexicographically smallest.

      Example

      For the input data:

      4
      1 3 4 2

      the correct result is:

      TAK
      1 1 2 1

      And for the input:

      4
      2 3 4 1

      the correct result is:

      NIE



      Added by:Tooru Ichii
      Date:2013-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:POI XVII









      SPOJ Problem Set (classical)

      15575. Kangaroos

      Problem code: STC08

      Byteasar, who is interested in wildlife photography, is planning a trip to Australia. He has started preparing his photographic equipment for taking pictures of kangaroos, and has to decide what items to pack. His equipment includes an extensive collection of photographic lenses with varying characteristics for different angles of view and focusing abilities. The best quality of pictures of animals, such as kangaroos, is achieved when the distance between the camera and the animal is within the optimal range of the lens.

      Byteasar's trip passes through a sequence of access points for wildlife observation and photography. The Australian guides gave Byteasar a detailed description of these observation points-in particular, the distances at which kangaroos can be expected.

      Obviously, not all the lenses from Byteasar's large collection will fit in his luggage, so some decisions must be made. Since Byteasar wishes to keep his lens-changes to a minimum, he wants to find-for each of the lenses-the longest contiguous sequence of observation points on the trip for which that lens is suitable. A lens is suitable for a given observation point if there exists a distance from the range of expected distances that lies within the optimal range of that lens.

      Input

      The first line of the standard input contains two integers, N and M (1 <= N <= 50000, 1 <= M <= 200000), where N is the number of observation points on the trip and M is the number of lenses in Byteasar's collection.

      The next N lines describe the access points for wildlife observation and photography on Byteasar's trip. Each of these lines contains two integers, Ai and Bi (1 <= Ai <= Bi <= 109), indicating that at the i-th observation point kangaroos can appear at a distance of Ai to Bi bytean feet, inclusive.

      The next M lines describe the lenses. Each of these lines contains two integers, Li and Ri (1 <= Li <= Ri <= 109), indicating that the i-th lens works best for kangaroos that are at a distance from Li to Ri bytean feet from the camera, inclusive.

      Output

      The standard output should consist of M lines containing exactly one integer each. The i-th output line indicates the number of observation points in the longest contiguous segment of the trip where the i-th lens can be used by Byteasar. The lenses are numbered according to their order in the input file.

      Example

      For the input data:

      3 3
      2 5
      1 3
      6 6
      3 5
      1 10
      7 9

      the correct result is:

      2
      3
      0

      Added by:Tooru Ichii
      Date:2013-08-06
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:PA 2011









      SPOJ Problem Set (classical)

      15576. Aesthetic Text

      Problem code: STC09

      Let us consider a text consisting of N words numbered from 1 to N. We represent any of its decompositions into K lines by a sequence of numbers (a1, a2, a3, ..., ak-1), such that the words with numbers from 1 to a1 are in the first line, the words with numbers from a1+1 to a2 are in the second line, and so on, and finally, the words with numbers from aK-1 to N are in the last, K-th line.

      Each word has a certain length (measured in the number of characters). Let length(x) denote the length of the word no. x. Furthermore, every two subsequent words in a line are separated by a space of width of a single character. By length of the line we denote the sum of lengths of the words in this line, increased by the number of spaces between them. Let line(w) denote the length of the line no. w. I.e., if the line no. w contains the words with numbers from i to j inclusive, its length is:

      line(w)=length(i)+length(i+1)+...+length(j)+(j-i)

      As an example, let us consider a text consisting of 4 words of lengths 4, 3, 2 and 5, respectively, and its decomposition (1, 3) into 3 lines. Then the length of the first line is 4, second - 6, and third - 5:

      XXXX (1st line)
      XXX XX (2nd line)
      XXXXX (3rd line)

      We shall refer to the number

      |line(1)-line(2)|+|line(2)-line(3)|+...+|line(K-1)-line(K)|

      as the coefficient of aestheticism of a decomposition of the given text into K lines. Particularly, if the decomposition has only one line, its coefficient of aestheticism is 0.

      Needles to say, the smaller the coefficient, the more aesthetical the decomposition. We shall consider only these decompositions that have no line whose length exceeds some constant M. Of all such decompositions of a given text into any number of lines we seek the one most aesthetical, i.e. the one with the smallest coefficient of aestheticism. The aforementioned examplary decomposition's coefficient is 3, and that is exactly the minimum coefficient of aestheticism for M = 6 and M = 7.

       

      Task

      Write a programme that:

      • reads from the standard input the numbers N and M and the lengths of the words,
      • determines the minimum coefficient of aestheticism for those decompositions, whose every line is of length not exceeding M,
      • writes the result to the standard output.

       

      Input

      The first line of the standard input contains the numbers N and M, 1 <= N <= 2000, 1 <= M <= 1000000, separated by a single space. The second, last line of the standard input contains M integers, denoting the lengths of subsequent words, 1 <= length(i) <= M for i = 1, 2, 3, ... M, separated by single spaces.

      Output

      The first and only line of the standard output should contain exactly one integer: the minimum coefficient of aestheticism for those decompositions, whose every line's length does not exceed M.

       

      Example

      For the input data:

      6 4
      4 3 2 5

      the correct result is:

      3

      while for the following input data:

      4 2
      1 2

      the correct result is:

      0

      Added by:Tooru Ichii
      Date:2013-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:POI XIII









      SPOJ Problem Set (classical)

      15577. Blockade

      Problem code: STC10

      There are exactly N towns in Byteotia. Some towns are connected by bidirectional roads. There are no crossroads outside towns, though there may be bridges, tunnels and flyovers. Each pair of towns may be connected by at most one direct road. One can get from any town to any other-directly or indirectly.

      Each town has exactly one citizen. For that reason the citizens suffer from loneliness. It turns out that each citizen would like to pay a visit to every other citizen (in his host's hometown), and do it exactly once. So exactly N*(N-1) visits should take place. That's right, should. Unfortunately, a general strike of programmers, who demand an emergency purchase of software, is under way. As an act of protest, the programmers plan to block one town of Byteotia, preventing entering it, leaving it, and even passing through. As we speak, they are debating which town to choose so that the consequences are most severe.

      Task

      Write a programme that:

      • reads the Byteotian road system's description from the standard input,
      • for each town determines, how many visits could take place if this town were not blocked by programmers,
      • writes out the outcome to the standard output.

       

      Input

      In the first line of the standard input there are two positive integers: N and N (1 <= N <= 100000, 1 <= M <= 500000) denoting the number of towns and roads, respectively. The towns are numbered from 1 to N. The following M lines contain descriptions of the roads. Each line contains two integers Xi and Yi (1 <= Xi, Yi <= N) and denotes a direct road between towns numbered Xi and Yi.

      Output

      Your programme should write out exactly N integers to the standard output, one number per line. The i-th line should contain the number of visits that could not take place if the programmers blocked the town no. i.

      Example

      For the input data:

      5 5
      1 2
      2 3
      1 3
      3 4
      4 5

      the correct result is:

      8
      8
      16
      14
      8

      Added by:Tooru Ichii
      Date:2013-08-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:POI XV









      SPOJ Problem Set (classical)

      15609. Spiky Mazes

      Problem code: SPIKES

      Jarmtin is interested in cultures and the history behind them. Of course this interest has a reason: as he studies the choivans’ past he discovers the hidden entrances of mazes he knows contain valuable information.  However there is a catch: the mazes contain spiky traps! Jarmtin is quite the agile type, but there is a limit to everyone, thus he will only be able to avoid a number of traps. This motivates the question can he make it through the mazes?

      Jarmtin is interested in cultures and the history behind them. Of course this interest has a reason: as he studies the choivans’ past he discovers the hidden entrances of mazes he knows contain valuable information.  However there is a catch: the mazes contain spiky traps! Jarmtin is quite the agile type, but there is a limit to everyone, thus he will only be able to avoid a number of traps. This motivates the question can he make it through the mazes?

       

      Input

      The first line of a test case contains three integers n, m and j. n (2<=n<=40) the number of rows, m (2<=n<=40) the width of each row and j (0<=j<=20) the number of times Jarmtin can avoid spikes. Then n lines containing m characters; The character ‘x’ will be used for the place of the treasure, ‘@’ for an entrance (which is also an exit), ‘#’ for walls, ‘.’ for a safe walking tile and ‘s’ for spikes. Note that you cannot walk into walls and the maze is completely surrounded by walls outside what you can see. There is always at least one entrance/exit and always an x where the treasure is.

       

      Output

      You should output “SUCCESS” if Jarmtin can make it in and out alive, and “IMPOSSIBLE” if there is no way you can make it out alive.


      Sample Input / Output

      Example 1:

      Input:

      3 3 2

      #@#

      #s#

      #x#

       

      Output:

      SUCCESS

       

      Example 2:

      Input:

      4 4 3

      ####

      @.s#

      ##.#

      #xs#

       

      Output:

      IMPOSSIBLE

       

      3 3 2
      #@#
      #s#
      #x#

       

       


      Added by:Laurens
      Date:2013-08-10
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Self created problem









      SPOJ Problem Set (classical)

      15620. Postering

      Problem code: POSTERIN

      All the buildings in the east district of Byteburg were built in accordance with the old arbitecture: they stand next to each other with no spacing inbetween. Together they form a very long chain of buildings of diverse height, extending from east to west.

      The mayor of Byteburg, Byteasar, has decided to have the north face of the chain covered with posters. Byteasar ponders over the minimum number of posters sufficient to cover the whole north face. The posters have rectangular shape with vertical and horizontal sides. They cannot overlap, but may touch each other, i.e. have common points on the sides. Every poster has to entirely adjoin the walls of certain buildings and the whole surface of the north face has to be covered.

      Task

      Write a programme that:

      • reads the description of buildings from the standard input,
      • determines the minimum number of posters needed to entirely cover their north faces,
      • writes out the outcome to the standard output.

       

      Input

      The first line of the standard input contains one integer N (1 <= N <= 250000), denoting the number of buildings the chain comprises of. Each of the following N lines contains two integers Di and Wi (1 <= Di, Wi <=109), separated by a single space, denoting respectively the length and height of the i-th building in the row.

       

      Output

      The first and only line of the standard output should contain one integer, the minimum number of rectangular posters that suffice to cover the north faces of the buildings.

       

      Example

      Input
      5
      1 2
      1 3
      2 2
      2 5
      1 4
      
      Output
      4
      

      Added by:Tooru Ichii
      Date:2013-08-11
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:POI XV









      SPOJ Problem Set (classical)

      15621. Tie the Rope

      Problem code: TIEROPE

      Sailor Crow'n-beard has many pieces of rope. Every piece has a different value and it is well known that money equals quality. Crow'n-beard wants you to create a program that given pieces of rope, creates a rope with the length as close as possible to his desired length (but never too short) while maximizing the quality.

      Input

      Input describes a single test case. The first line contains two integers N (1 ≤ N ≤ 80) and L (1 ≤ L ≤ 10000): the number of rope pieces Crow'n-beard and the desired length respectively. Then N lines will follow, each with two integers: the length Li (0 ≤ Li < 2^31) followed by the value Vi (0 ≤ Vi ≤ 26843545) of the piece of rope. It is guaranteed that the sum of Li is never less than L.

      Output

      You should output the maximal total quality you can reach. Remember that the priority is to get the smallest total length that is still at least equal to L. Only then output the best total quality amongst equal length solutions.

      Sample

      Input:
      4 4
      20 2
      1 4
      3 4
      4 7
      
      Output:
      8

      Added by:Laurens
      Date:2013-08-11
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      15627. Create Collections

      Problem code: IITKWPCO


        Little Feluda likes to play very much. As you know he only plays with numbers. So he is given n numbers. Now tries to group the numbers into disjoint collections each containing two numbers. He can form the collection containing two numbers iff small number in the collection is exactly half of large number.

        Given n numbers, Find out how many maximum number of collections he can form ?

      Input

      T: number of test cases. (1 <= T <= 100).

      For each test case:

      First line will contain n :  (1 <= n <= 100)

      Then next line will contain n numbers single space seperated. Range of each number will be between 1 and 10^6.

      Output

      For each test case, output maximum number of collections that can be formed.

      Example

      Input:
      2
      2
      1 2
      3
      1 2 4
      Output:
      1
      1

      Added by:praveen123
      Date:2013-08-12
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      15631. On the Plus Side

      Problem code: PLUS

      A man called Gerit Teeman was fascinated by the plus symbol and, to be honest, this symbol is actually quite interesting!

      Begin by drawing an one. This will be the center of the plus symbol. Above this center draw the number two, below three, to the left four and the the right five. If you then 'replace' the center (either up, down, left or right), do the same, but when a place is already filled you leave it untouched.

      To illustrate this we pick the place with the number two: Above it draw a two, the bottom is already filled so we leave it untouched, to the left we draw a four and the the right we draw a five. See the picture below:
      example

      It is not hard to see that the sum of the first plus symbol is 15 (the first symbol only containing 1 is NOT a plus symbol). The sum of the second symbol is already more difficult, summing up to 26. Now here comes the catch: depending on which number you pick to expand on, the number on positions can change. If we would have picked five to expand on instead of two, we will get the following:
      example

      As you can see the numbers differ from that of the first example. This time the sum is 25! On top of that, there can be multiple 'replaces', generating more number in the symbol. Your task is, depending on which way you expand to, give the sum of all the elements of plus symbol that you would obtain.


      Input

      First line contains an integer T (1 <= T <= 100) number of test cases. Each of the next T lines contains a string with letters 'L', 'R', 'U', 'D' and 'S' (separated by commas) which respectively mean left, right, up, down and stop. You should expand to the given direction, based on your last created expansion's center. Stop means you should finish and output the total sum to that point. The number of letters in the string will never exceed 10000.

      Note that the first example was created by the string "U,S" and the second by the string "R,S".


      Output

      For each test case output a single integer in a separate line: the total sum of all numbers contained in the created symbol.


      Sample:

      Input:
      2
      U,S
      S
      
      Output:
      26
      15
      

      Added by:Laurens
      Date:2013-08-12
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Self created problem









      SPOJ Problem Set (classical)

      15634. Lennys Lucky Lotto Lists

      Problem code: GNYR04C

      Lotto is a lottery, typically with an accumulating jackpot, in which participants play numbers of their choice in a random drawing. Lenny likes to play the lotto in Lincoln county Louisiana. In the game, he picks a list of n numbers in the range from 1 to m. If his list matches the drawn list, he wins the big prize, a lifetime supply of large lemons.

      Lenny has a scheme that he thinks is likely to be lucky. He likes to choose his list so that each number in it is at least twice as large as the one before it. So, for example, if n = 4 and m = 10, then the possible lucky lists Lenny could pick are:

          1 2 4 8
          1 2 4 9
          1 2 4 10
          1 2 5 10
      

      Thus Lenny has 4 lists to choose from.

      Your job, given n and m, is to count how many lucky lists Lenny has to his disposal.


      Input

      The first line of input is a single non-negative integer, which is the number of data sets to follow. All data sets should be handled identically. The next lines, one per data set, contain two integers, nand m. It is guaranteed that 1 <= n <= 10 and 1 <= m <= 2000 and n <= m.


      Output

      For each data set, print a line like the following:

      Data set in m number

      where i is the data set number (beginning with 1), and number is the maximum number of lucky lists corresponding to the provided values of n and m.


      Example

      Input

      1
      4 10

      Output

      Data set 1: 4 10 4

      Added by:abdelkarim
      Date:2013-08-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM Regionals 2004 North America - Greater NY









      SPOJ Problem Set (classical)

      15636. Histology Assistant

      Problem code: GNYR04I

       

      An application to assist in the analysis of tissue samples is to work as follows. A digital microphotograph of a stained tissue sample is scanned to identify stained pixels. For each region of stained pixels, an outline of the region is obtained. The outline is then analyzed for shape indicators of disease and the outlines (color-coded for possible disease) are overlaid on the microphotograph as it is displayed to the pathologist.

      This problem is to write a program, which processes a bitmap of stained and unstained pixels, finds regions of stained pixels and, for each region, outputs the outline of the region. Regions with fewer stained pixels than a minimum size are ignored. Only the outer boundary is computed (interior holes are ignored).

      A pixel is adjacent to another pixel if the second pixel is directly above, directly below, directly left or directly right of the first pixel. Two stained pixels are connected if there is a sequence of stained pixels starting with one of the pixels and ending with the other for which each pixel in the sequence is adjacent to the next. A regionof stained pixels is a set of stained pixels, all of which are connected to a single stained pixel. A stained pixel is a boundary pixel of its region if at least one of the pixels adjacent to it is not stained. (All pixels immediately outside the bitmap are considered unstained so that pixels on the edge of the bitmap are boundary pixels.) In the example below, there are 4 regions (stained pixels are `X', unstained are `.').

       

                         ........................................
                         .XX.....................................
                         ..X.................XXX......XXX........
                         .....................XXX....XXX.........
                         .......XXX............XXX..XXX..........
                         .....XXXXXXX...........XXXXXX...........
                         ....XXXXXXXXX...........XXXX............
                         ...XXXX...XXXX...........XX.............
                         ..XXX.......XXX.........................
                         ..XXX.......XXX........XXXXXXX..........
                         .XXX.........XXX.......XXXXXXX..........
                         .XXX.........XXX.......XXXXXXX..........
                         .XXX.........XXX.......XXXXXXX..........
                         ..XXX.......XXX...........X.............
                         ..XXX.......XXX...........X.............
                         ...XXXX...XXXX.........XXXXXXX..........
                         ....XXXXXXXXX..........XXXXXXX..........
                         .....XXXXXXX...........XXXXXXX..........
                         .......XXX.............XXXXXXX..........
                         ........................................
      

      Outlines are to be specified as the left most point of the top most line of the region, a count of boundary pixels and a sequence of moves from one boundary pixel to the next clockwise using the codes (up = A, up right = B, etc.):

       

                   H  A  B
                   G     C
                   F  E  D
      

      Rows are numbered from top to bottom beginning with 1. Columns are numbered from left to right beginning with 1. For example the outline of the 'v' shaped region above would be:

      3 21 22
      CCDDDCBBBCCFFFFFGHHHHH

      input

      Input is a sequence of problem instances. Each problem instance begins with a line containing 3 decimal numbers: row-count,column-count and minimum-number-of-pixels. This line is followed by row-count lines of column-count characters. Each character is either a period (.) for an unstained pixel or an upper-case `X' for a stained pixel. The input ends when the row-count is 0. Row-countwill be at most 47, column-count will be at most 63 and minimum- number-of-pixels will be at least 2.

       

      output

      For each problem instance, the output begins with a line starting with a decimal integer giving the number of components of at leastminimum-number-of-pixels stained pixels. This is followed by the description of the boundary of each component. The boundaries are to be listed in the order that a first pixel of the component appears while scanning across lines from left to right with line scanned from top to bottom. For each component, the output begins with a line giving the row number of the start pixel, thecolumn number of the start pixel and the number of pixels in the boundary as decimal integers separated by a single space. This line is followed by lines of direction codes `A' through `H'. Each line shall have 40 characters except the last line.

       

      input sample

      20 40 4
      ........................................
      .XX.....................................
      ..X.................XXX......XXX........
      .....................XXX....XXX.........
      .......XXX............XXX..XXX..........
      .....XXXXXXX...........XXXXXX...........
      ....XXXXXXXXX...........XXXX............
      ...XXXX...XXXX...........XX.............
      ..XXX.......XXX.........................
      ..XXX.......XXX........XXXXXXX..........
      .XXX.........XXX.......XXXXXXX..........
      .XXX.........XXX.......XXXXXXX..........
      .XXX.........XXX.......XXXXXXX..........
      ..XXX.......XXX...........X.............
      ..XXX.......XXX...........X.............
      ...XXXX...XXXX.........XXXXXXX..........
      ....XXXXXXXXX..........XXXXXXX..........
      .....XXXXXXX...........XXXXXXX..........
      .......XXX.............XXXXXXX..........
      ........................................
      12 40 4
      .X.X.X.X.X.X......XX...XXXXXXXXXXXXXXXX.
      .XXX.XXX.XXX......XX..XXXXXXXXXXXXXXXXXX
      .X...X...X........XX..XX.............XXX
      .X.X.X.X.X.X......XX..XX...XXXXXXXX...XX
      .XXX.XXX.XXX......XX..XX..XXXXXXXXXX..XX
      .X...X...X........XX..XX..XX......XX..XX
      .X.X.X.X.X.X......XX..XXX........XXX..XX
      .XXX.XXX.XXX......XX..XXXXXXXXXXXXXX..XX
      .X...X...X........XX...XXXXXXXXXXXX...XX
      .X.X.X.X.X.X......XXX................XXX
      .XXXXXXXXXXX......XXXXXXXXXXXXXXXXXXXXXX
      ...................XXXXXXXXXXXXXXXXXXXX.
      0 0 0

      output sample

      3
      3 21 22
      CCDDDCBBBCCFFFFFGHHHHH
      5 8 36
      CCDCDDDEDEEFEFFFGFGGHGHHHAHAABABBBCB
      10 24 38
      CCCCCCEEEGGFEDCCEEEGGGGGGAAACCBAHGGAAA
      2
      1 2 103
      DBEGFEDBEGFEDBEGFEDBDBAAAAAAAAADBEGFEDBE
      GFEDBEGFEDBDBAAAAAAAAADBEGFEDBEGFEDBEGFE
      DBEGGGGGGGGGGAAAAAAAAAA
      1 19 159
      CEEEEEEEEDDCCCCCCCCCCCCCCCBBAAAAAHHGGGGG
      GGGGGGGFEEEDDCCCCCCCBBHGGGGGFGABCCCCCCCD
      EEEFGGGGGGGGGGGHAAAAAABCCCCCCCCCCCCCCCDE
      EEEEEEEEFGGGGGGGGGGGGGGGGGGGHAAAAAAAAAA

       


      Added by:abdelkarim
      Date:2013-08-13
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM Regionals 2004 North America - Greater NY









      SPOJ Problem Set (classical)

      15637. Mr Youngs Picture Permutations

      Problem code: GNYR04H

      Mr. Young wishes to take a picture of his class. The students will stand in rows, with each row no longer than the row behind it and the left ends of the rows aligned. For instance, 12 students could be arranged in rows (from back to front) of 5, 3, 3 and 1 students.

      X X X X X
      X X X
      X X X
      X
      

       

      In addition, Mr. Young wants the students in each row arranged so that heights decrease from left to right. Also, student heights should decrease from the back to the front. Thinking about it, Mr. Young sees that for the 12-student example, there are at least two ways to arrange the students (numbers represent heights, with 1 meaning the tallest):

       1  2  3  4  5     1  5  8 11 12
       6  7  8           2  6  9
       9 10 11           3  7 10
      12                 4
      

       

      Mr. Young wonders how many different arrangements of the students there might be for a given arrangement of rows. He tries counting by hand starting with rows of lengths 3, 2 and 1 and counts 16 arrangements:

      123 123 124 124 125 125 126 126 134 134 135 135 136 136 145 146
      45  46  35  36  34  36  34  35  25  26  24  26  24  25  26  25
      6   5   6   5   6   4   5   4   6   5   6   4   5   4   3   3
      

       

      Mr. Young sees that counting by hand is not going to be very effective for any reasonable number of students. He asks you to help out by writing a computer program to determine the number of different arrangements of students for a given set of rows.

       

      Input

      The input describes a series of test, each described in two lines. The first line gives the number of rows, k, as a decimal integer. The second line contains the lengths of the rows from back to front (n1,n2,..., nk) as decimal integers separated by single spaces. The problem set ends with a line with a row count of 0. There will never be more than 5 rows and the total number of students, N, (sum of the row lengths) will be at most 30.

       

      Output

      For each test case output a single integer: The number of arrangements of N students into the given rows, so that the heights decrease along each row from left to right and along each column from back to front (assume that all heights are distinct). The results should be in separate lines. The input data will be chosen so that the result will always fit in an unsigned 32-bit integer.

       

      Sample

      Input  

      1
      30
      5
      1 1 1 1 1
      3
      3 2 1
      4
      5 3 3 1
      5
      6 5 4 3 2
      2
      15 15
      0

      Output  

      1
      1
      16
      4158
      141892608
      9694845

      Added by:abdelkarim
      Date:2013-08-13
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM Regionals 2004 North America - Greater NY









      SPOJ Problem Set (classical)

      15648. Commando

      Problem code: APIO10A

      Commando


      You are the commander of a troop of n soldiers, numbered from 1 to n. For the battle ahead, you plan to divide these n soldiers into several com-mando units. To promote unity and boost morale, each unit will consist of a contiguous sequence of soldiers of the form (i, i+1, . . . , i+k).

      Each soldier i has a battle effectiveness rating xi . Originally, the battle effectiveness x of a commando unit (i, i+1, . . . , i+k) was computed by adding up the individual battle effectiveness of the soldiers in the unit. In other words, x = xi + xi+1 + · · · + xi+k .


      However, years of glorious victories have led you to conclude that the battle effectiveness of a unit should be adjusted as follows: the adjusted effectiveness x is computed by using the equation x = ax2 + bx + c, where a,b, c are known coefficients(a < 0), x is the original effectiveness of the unit.

       

      Your task as commander is to divide your soldiers into commando units in order to maximize the sum of the adjusted effectiveness of all the units.

       

      For instance, suppose you have 4 soldiers, x1 = 2, x2 = 2, x3 = 3, x4 = 4. Further, let the coefficients for the equation to adjust the battle effectiveness of a unit be a = −1, b = 10, c = −20. In this case, the best solution is to divide the soldiers into three commando units: The first unit contains soldiers 1 and 2, the second unit contains soldier 3, and the third unit contains soldier 4. The battle effectiveness of the three units are 4, 3, 4 respectively, and the
      adjusted effectiveness are 4, 1, 4 respectively. The total adjusted effectiveness for this grouping is 9 and it can be checked that no better solution is possible.

      Input format:

      First Line of input consists number of cases T.

      Each case consists of three lines. The first line contains a positive integer n, the total number of soldiers. The second line contains 3 integers a, b, and c, the coefficients for the equation to adjust the battle effectiveness of a commando unit. The last line contains n integers x1 , x2 , . . . , xn , sepa-rated by spaces, representing the battle effectiveness of soldiers 1, 2, . . . , n, respectively.

      Constraints:

      T<=3

      n ≤ 1, 000, 000,

      −5 ≤ a ≤ −1

      |b| ≤ 10, 000, 000

      |c| ≤ 10, 000, 000

      1 ≤ xi ≤ 100.

       


      Output format:

      Output each answer in a single line.


      Input:

      3
      4
      -1 10 -20
      2 2 3 4
      5
      -1 10 -20
      1 2 3 4 5
      8
      -2 4 3
      100 12 3 4 5 2 4 2

      Output:

      9
      13
      -19884

       

      (Official dataset of APIO was NOT used in this problem.)


      Added by:Shafaet
      Date:2013-08-17
      Time limit:0.300s-0.800s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:APIO 2010









      SPOJ Problem Set (classical)

      15649. Unequalled Consumption

      Problem code: NWERC05

      The Association of Candy Makers is preparing to launch a new product. Its idea is old with a novel twist: it simply sells boxes of candies. But since people are what they consume and everyone wants to be unique these days, the ACM wants every candy box to be unique, in the sense that no two boxes should contain the same composition of candy types.

      The ACM is only able to make a small number n of different types of candy, but while limited in imagination, it is virtually limitless in resources, so it is able to produce as many as it wants of each type of candy. Furthermore, the candy types have different weights (though some may weigh the same), and in order to simplify pricing matters, the ACM wants all candy boxes to have the same total weight.

      With these restrictions, the ACM will only be able to make a limited number of boxes. For instance, if there are three types of candy, weighing 5, 5 and 10 grams respectively, 4 different boxes can be made with total weight 10 grams (using either two of type 1, or two of type 2, or one of type 3, or one each of types 1 and 2). The ACM would like to be able to make at least one box for everyone in the cosmos. So, given queries in the form of the number of people P in the cosmos, your job is to find the smallest possible total weight w such that P different boxes containing exactly w grams of candies can be made.

      input

      The input consists of several data sets (at most 20). Each data set consists of four lines. The first line contains an integer 1 ≤ n ≤ 5, the number of candy types. The next line contains n integers w1, ..., wn, where 1 ≤ wi ≤ 10 is the weight (in grams) of the i:th candy type. The third line contains an integer 1 ≤ q ≤ 10, the number of queries. The last line of a data set contains q integers P1, ..., Pq, where 1 ≤ Pj ≤ 1015 is the j:th query. Input is terminated by an incomplete data set where n = 0, which should not be processed.

      output

      For the i:th data set, write a line "Set i", followed by q lines giving, for each query Pj, the minimal possible positive weight Wj(in grams) of a candy box. If there is no weight Wj such that at least Pj candy boxes can be made, print "no candy for you"for that query. You may assume that Wj, if it exists, will be at most 100 · Pj.

      intput

      3
      5 5 10
      1
      4
      4
      3 1 4 2
      2
      142 700
      1
      10
      1
      100
      0

      output

      Set 1
      10
      Set 2
      23
      42
      Set 3
      no candy for you
      
      

      becarfull spoj watch you : if i found anyone submit judge solution i will disqualify this submit .


      Added by:abdelkarim
      Date:2013-08-19
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM Europe - Northwestern 2005









      SPOJ Problem Set (classical)

      15650. Dark roads

      Problem code: ULM09

      Economic times these days are tough, even in Byteland. To reduce the operating costs, the government of Byteland has decided to optimize the road lighting. Till now every road was illuminated all night long, which costs 1 Bytelandian Dollar per meter and day. To save money, they decided to no longer illuminate every road, but to switch off the road lighting of some streets. To make sure that the inhabitants of Byteland still feel safe, they want to optimize the lighting in such a way, that after darkening some streets at night, there will still be at least one illuminated path from every junction in Byteland to every other junction.

      What is the maximum daily amount of money the government of Byteland can save, without making their inhabitants feel unsafe?

      Input Specification

      The input file contains several test cases. Each test case starts with two numbers m and n, the number of junctions in Byteland and the number of roads in Byteland, respectively. Input is terminated by m=n=0. Otherwise, 1 ≤ m ≤ 200000 and m-1 ≤ n ≤ 200000. Then follow n integer triples x, y, z specifying that there will be a bidirectional road between x and y with length z meters (0 ≤ x, y < m and x ≠ y). The graph specified by each test case is connected. The total length of all roads in each test case is less than 231.

      Output Specification

      For each test case print one line containing the maximum daily amount the government can save.

      Sample Input

      7 11
      0 1 7
      0 3 5
      1 2 8
      1 3 9
      1 4 7
      2 4 5
      3 4 15
      3 5 6
      4 5 8
      4 6 9
      5 6 11
      0 0
      

      Sample Output

      51


      Added by:abdelkarim
      Date:2013-08-19
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:2009/2010 ACM International Collegiate Programming Contest University of Ulm Local Contest









      SPOJ Problem Set (classical)

      15655. Product of factorials

      Problem code: FACTMUL

      You need to find the product of first n factorials 1! * 2! * ... * n! modulo 109546051211.

      Input

      One integer n (1 <= n <= 10000000)

      Output

      The answer.

      Example

      Input:
      5
      
      Output:
      34560
      

      Added by:Ashot Minasyan
      Date:2013-08-20
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15671. Product of factorials (medium)

      Problem code: FACTMULM

      You need to find the product of the first n factorials, so 1! * 2! * ... * n! modulo p, where p=63303212889375877567328165411288303907410870625225931671654121339922293885519921.

      Input

      An integer T, denoting the number of testcases (T≤10). Each of the T following lines contains a positive integer, where

      n≤ 10^8.

      Output

      Output T lines, the case number followed by the answer. See the sample output for the correct format!

      Example

      Input:
      7
      1
      5
      100
      429
      1000
      1000000
      100000000
      
      Output:
      Case 1: 1
      Case 2: 34560
      Case 3: 30320185692040509343149810686654647278680728299485184027723296362520679295668953
      Case 4: 49116522183503229678644619968184124916695876848076217702050317922528502280661110
      Case 5: 38310494067749735972957877453766730719859042112664856832928508845605975573300554
      Case 6: 59623175509081913319809873890125269865036398088611331352359071382248773213856402
      Case 7: 43046234475587180053977224639514165196068475389708692929440906111909653614719387
      

      Added by:Robert Gerbicz
      Date:2013-08-23
      Time limit:2s-3.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:FACTMUL









      SPOJ Problem Set (classical)

      15728. The Sierpinski Fractal

      Problem code: ULM02

      Consider a regular triangular area, divide it into four equal triangles of half height and remove the one in the middle. Apply the same operation recursively to each of the three remaining triangles. If we repeated this procedure infinite times, we'd obtain something with an area of zero. The fractal that evolves this way is called the Sierpinski Triangle. Although its topological dimension is 2, its Hausdorff-Besicovitch dimension islog(3)/log(2)~1.58, a fractional value (that's why it is called a fractal). By the way, the Hausdorff-Besicovitch dimension of the Norwegian coast is approximately 1.52, its topological dimension being 1.

      For this problem, you are to outline the Sierpinski Triangle up to a certain recursion depth, using just ASCII characters. Since the drawing resolution is thus fixed, you'll need to grow the picture appropriately. Draw the smallest triangle (that is not divided any further) with two slashes, to backslashes and two underscores like this:

       

       /\
      /__\
       /\
      /__\

       

      To see how to draw larger triangles, take a look at the sample output.

      Input Specification

      The input contains several testcases. Each is specified by an integer n. Input is terminated by n=0. Otherwise 1≤n≤10 indicates the recursion depth.

      Output Specification

      For each test case draw an outline of the Sierpinski Triangle with a side's total length of 2n characters. Align your output to the left, that is, print the bottom leftmost slash into the first column. The output must not contain any trailing blanks. Print an empty line after each test case.

      Sample Input

      3
      2
      1
      0
      

      Sample Output

             /\
            /__\
           /\  /\
          /__\/__\
         /\      /\
        /__\    /__\
       /\  /\  /\  /\
      /__\/__\/__\/__\
      
         /\
        /__\
       /\  /\
      /__\/__\
      
       /\
      /__\
      
      

                                                                                       The Sierpinski-Triangle up to recursion depth 7

       

       


      Added by:abdelkarim
      Date:2013-08-28
      Time limit:1s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:University of Ulm Local Contest 2002









      SPOJ Problem Set (classical)

      15733. Hall of Fountains

      Problem code: ULM2H

      The Museum of Modern Art has a really exciting exhibition: a kind of a longish hall composed of a sequence of quadratic-shaped rooms. Each room is equipped with a water fountain. Each fountain is characterized by a number p and acts independent of the others. It will be turned on for exactly p seconds, then it will be turned off for exactly p seconds, then on again, then off again, and so on for good. However, different fountains may have different values of p. And even if they share the same value, they still may perform not identically, for they might have been started at different times.

      You stand in front of the first room, and want to cross the hall to the other end. Each of your steps takes exactly 1 second. You are able to move one room forward (unless you already reached the other end), one room backward (unless you are at the beginning), or just stay at your current position. Calculate the shortest time to reach the other end, if it is possible at all.

      Since you do not want to get wet, you can only move into a room where the water fountain will be off during the second after your step. For example, suppose that the fountain in the next room behaves so, that it is on at times 0, 1, 2, then off at times 3, 4, 5, 6, then on at times 7, 8, 9, 10, then off again (which indicates p=4 with an offset of 7). Then, you can move at time 2 into the room, arriving there at time 3, when the fountain is off. But you cannot move at time 6 into the room, because at time 7 it will be on.

      Input Specification

      The input contains several test cases. Each test case starts with the number of fountains n. Input is terminated by n=0. Otherwise, 1≤n≤100. Then follow n numbers pi denoting the time each fountain is on and off, where 0≤pi≤10. A value of 0 for pi indicates that fountain i is out of order (i.e. constantly off). Then follow n numbers qi denoting the offset of each fountain, where 0≤qi<2*pi, unless the fountain is out of order, in which case qi is meaningless. Otherwise it means that fountain i will be on at time qi, but off just one second before.

      Output Specification

      For each test case output on a line a single number t denoting the shortest time needed to reach the end of the hall (i.e. to enter the place after the last room). Assume, that you are in front of the first room at time 0 (i.e. you can enter the first room at time 1, if the fountain is off at time 1). If it is impossible to go through the hall of fountains, print 0 instead.

      Sample Input

      3
      0 0 0
      0 0 0
      4
      6 3 3 4
      2 3 0 4
      2
      1 1
      0 0
      0
      

      Sample Output

      4
      11
      0
      

      Added by:abdelkarim
      Date:2013-08-28
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:University of Ulm Local Contest 2002









      SPOJ Problem Set (classical)

      15734. California Jones and the Gate to Freedom

      Problem code: ULM02C

      California Jones (the sister of famous Indiana Jones) once again faced a seemingly intractable problem. Her only hope was in you. She knew you were a computer scientist and you might have a clue.

      Jones calls you on the video-phone and tells you the facts: she walked into a trap and now stands in front of a huge gate. On the left side strange signs can be seen while n stones lie on the right side. In front of the gate there are exactly n/2 holes. Says Jones, "I suppose I have to take exactly half of the stones from the right side and put them into the holes." Ancient writings confirm her conjecture. According to the writings it does not matter which hole a stone is placed into. It is only important that the right stones are chosen.

      Nearby, Jones found a stone board, too, but was unable to interpret. It made sense to you though. It was a hint on how to sort the various possibilities of chosing n/2 stones.

      But you couldn't yet figure out about the zeros and the ones. So you asked Jones who replied that "the same symbols I saw on the left side of the gate - only they were somewhat longer sequences. But I haven't met such a primitive civilization yet."

      Now everything was clear to you: the symbols were the representation of a binary number - and it indicated which stones to choose. Simply ingenious! Jones was enthusiastic about you.

      But it was impossible for Jones to calculate for a given binary number the corresponding stones. So she instructed you to write a program to solve the task and help her through the gate to freedom. Five hours later, she would call back.

      Take a thorough look at the figure to the left depicting the stone board, as well as the sample input and output, to figure out how to solve Jones' problem.

      Input Specification

      The input contains several testcases. Each starts with the number of stones n. Input is terminated by n=0. Otherwise, n is even and 2≤n≤32. The next n integers identify the stones. A test case is further subdivided into k (sub-) test cases, k being the next number in the input file. Then follow k times a bit string b (encoding a non-negative integer) and n/2 distinct integers identifying the set of chosen stones. No invalid stones will be chosen and the length of b will not exceed 30.

      Output Specification

      For each (sub-) test case generate a line containing TRUE, if the chosen stones may be laid into the holes, and FALSE otherwise.

      Sample Input

      4
      12 50 74 34
      1
      00
      50 12
      
      8
      45 23 86 43 90 76 12 74
      2
      111001
      86 43 90 74
      010001
      45 86 43 90
      
      4
      12 50 74 34
      2
      101
      34 74
      110
      34 74
      
      0
      

      Sample Output

      TRUE
      TRUE
      FALSE
      TRUE
      FALSE
      


      Added by:abdelkarim
      Date:2013-08-28
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:University of Ulm Local Contest 2002









      SPOJ Problem Set (classical)

      15735. Balanced Food

      Problem code: ULM02B

      Computer scientists live on pizza. Now the doctors say this is no good. We ought to eat more balanced. So you put your really large pizza onto your table and eat slice-by-slice carefully watching that the rest of your meal stays where it is - on the table.

      Since computer scientists love pizza, their favourite table is shaped like a slice of pizza. However, different people may have different-sized tables. Everyone has his own preference for the number of slices a pizza has to be cut to. However, all agree that the slices must have identical size. Write a program to help the poor pizza lovers!

      Input Specification

      The input file contains several test cases. Each test case starts with the number of slices n the pizza is cut to. Input is terminated by n=0. Otherwise, 1≤n≤9. Then follow 9 floating-point numbers px, py, r, tx, ty, ux, uy, vx, vy specifying the coordinates of the center p of the pizza, its radius, and the coordinates of three points t, u, v. They define the three corners of the slice-shaped table in counter-clockwise order, with tbeing the center.

      The pizza is a homogeneous two-dimensional circular object. There is always a cut from its center parallel to the x-axis towards increasing x-values. The remaining pizza stays connected during the whole process, no matter what slices are removed. The distances from t to u, v are equal except for very small rounding errors. Tables are never larger than a half-circle.

      Output Specification

      For each test case output on a line some possible ordering of slices, so that during the whole process of eating the pizza it does not fall down the table. Slices are numbered counter-clockwise starting with 1 directly above the positive x-axis.

      If several such ordering exist, choose the lexicographically first one. 
      If no ordering of slices exists, so that the pizza does not fall down, output a line containing the word "impossible" instead.

      Remark

      A connected, rigid, flat object remains fixed on a convex, flat surface if and only if the object's center of gravity lies above the surface. The x-coordinate, for example, of the center of gravity of an object s can be calculated by (∫sxds) / (∫sds). Likewise, the y-coordinate can be expressed as (∫syds) / (∫sds). Note that the denominator of these expressions gives the area of s.

      Sample Input

      2 (-3.0,-1.0) 1.0 (-3.0,-1.1) (-1.5,0.4) (-4.5,0.4)
      9 (2.0,1.0) 1.0 (0.0,0.0) (1.0,-1.0) (-1.0,1.0)
      0
      

      Sample Output

      2 1
      impossible
      

      Added by:abdelkarim
      Date:2013-08-28
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:University of Ulm Local Contest 2002









      SPOJ Problem Set (classical)

      15736. Breaking String

      Problem code: BRKSTRNG

      A certain string-processing language allows the programmer to break a string into two pieces. Since this involves copying the old string, it costs n units of time to break a string of n characters into two pieces. Suppose a programmer wants to break a string into many pieces. The order in which the breaks are made can affect the total amount of time used. For example, suppose we wish to break a 20 character string after characters 3, 8, and 10 (numbering the characters in ascending order from the left-hand end, starting from 1). If the breaks are made in left-to-right order, then the first break cost 20 units of time, the second break costs 17 units of time, and the third breaks costs 12 units of time, a total of 49 units of time (see the sample below). If the breaks are made in right-to-left order, then the first break costs 20 units of time, the second break costs 10 units of time, and the third break costs 8 units of time, a total of 38 units of time.

      The cost of making the breaks in left-to-right order:

      thisisastringofchars     (original)
      thi sisastringofchars    (cost:20 units)
      thi sisas tringofchars   (cost:17 units)
      thi sisas tr ingofchars  (cost:12 units)
                               Total: 49 units.

      The cost of making the breaks in right-to-left order:

      thisisastringofchars     (original)
      thisisastr ingofchars    (cost:20 units)
      thisisas tr ingofchars   (cost:10 units)
      thi sisas tr ingofchars  (cost: 8 units)
                               Total: 38 units.

      Input:

      There are several test cases! In each test case, the first line contains 2 integers N (2<=N<=10000000) and M (1<=M<=1000, M<N). N is the original length of the string, and M is the number of the breaks. The following lines contain M integers Mi (1<=Mi<N) in ascending order that represent the breaking positions from the string's left-hand end. Read input till EOF.

      (There wont be more than 100 cases)

      Output:

      For each test case, output in one line the least cost to make all the breakings.

      Sample Input:

      20 3
      3 8 10
      20 4
      2 3 8 10

      Sample Output:

      37
      40



      Added by:Shafaet
      Date:2013-08-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Author: Wei, Qizheng, Source: ZOJ Monthly, June 2007









      SPOJ Problem Set (classical)

      15766. Enjoy Sum with Operations

      Problem code: SUMSUM

      You are given N numbers  of the array (N<=100000),all less than 10^8 and greater than 0.
      Now ,you are given 2 queries:
      1. 1 x i : Change the ith number to x . (10^8=>x>=0)
      2. 2 Op i1 i2: Compute the sum of all two elements taken at a time within index i1 to i2(both inclusive) under the operation Op.
      Op could be XOR,OR or AND
      For exp:
      N=4 Query=3
      10 20 30 40--> Initial array
      
      2 OR 1 3
      1 0 1
      2 OR 1 3
      
      Answer:
      
      2 OR 1 3--> (10 OR 20) + (20 OR 30) + (10 OR 30)
      1 0 1   --> Now array becomes 0 20 30 40
      2 OR 1 3--> (0 OR 20) + (20 OR 30) + (0 OR 30)

      Input
      4 3
      10 20 30 40
      2 OR 1 3 1 0 1 2 OR 1 3

      Output

      90
      80

      NOTE: If i1 is equal to i2,alwyas output 0.

      Click here to see my set of problems at Spoj.


      Added by:Devendra Agarwal
      Date:2013-08-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      15769. Enjoy Adding GP to Series

      Problem code: ADDGP

      You are initially given an empty array of Size N (<=100000).(i.e. each element is 0)
      Given R<=10^9 and R>=2 .
      Now you are given 3 types of query:
      1. 0 St i1 i2  --> means add (St, St*R , St*R^2 ,....) GP from i1 to i2 respectively. (Means add the GP with start term St and common ratio R in the 
      series begining from i1 and ending at i2.) 2. 1 i j --> means find the sum of values of the array from index i to index j with modulo 1000000007. 3. 2 i-->reset the ith index array to 0. Queries <=90000
      St>=1 and St<=10e9

      Input
      First Line contains N R Q
      Then Follows Q lines , each line can be of any 3 types described above.

      Output

      Output only second type of Query.

      Input
      2 2 3
      0 2 1 2
      1 1 2
      1 2 2

      Output

      6
      4

      Click here to see my set of problems at Spoj.


      Added by:Devendra Agarwal
      Date:2013-08-30
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      15783. Coder Express 3!!

      Problem code: CODERE3

      Mr Durgeshwara was very impressed by Rahul.But now he was in trouble.He has already fixed his daughter's marriage with Thangabali who was the best coder of his town. He got an idea and arranged a contest between Rahul and Thangabali.They have to solve a problem at the same time and whoever solves first will marry Meenamma. Rahul was not such a good coder and was also getting help from Meenamma.Your task is to help Thangabali to solve the problem to create a twist in story .

      The problem was that there are large number of builing in the town which are of different heights and all the building are in a single line.
      You have to find the maximum possible length of the subsequences of buildings which are possible which are first increasing in heights and then decreasing! Please Note: the heights of the building in the subsequences should be strictly increasing and then strictly decreasing

       

      Input Specification:

      First line contains an integer T( 1 < = T < = 100) that represents the number of test cases.Then follows the T containg the integer N(1 < = N < = 1000) specifying the total number of elements and the next line contains the N integers A1,A2,A3...An (1<= Ai< = 1000)

      Output Specification:

      For each test case, print only one line, the maximum length of such sequence.

      Sample input:

      2
      10
      1 3 5 6 4 8 4 3 2 1
      6
      8 6 3 4 2 1

      Sample Output:

      9
      5

      Explanation

      for first test case the subsequence is : 1 3 5 6 8 4 3 2 1 for second case it is : 8 6 4 2 1


      Added by:http://infotsav.org
      Date:2013-09-01
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:AASF - ABV-IIITM PC-01-9-2013









      SPOJ Problem Set (classical)

      15827. Vending Machine

      Problem code: AUT

      Byteasar studies computer science at the University of Bytetown. There is a snack vending machine at his faculty that sells  types of snacks, numbered  through . Snacks of different types may have different price, since they differ in size and flavor.

      Recently Byteasar discovered that the vending machine is broken. If one buys a snack of type , the vending machine additionally dispenses one snack of each of the types , ..., , provided that snacks of these types are available (if there are no snacks of some of the types , simply no snack of this type is dispensed). Buing snack of type  is possible only if at least one snack of this type is available.

      Byteasar decided to take advantage of the fault he discovered. He would like to find out what is the maximum total value (that is, the sum of prices) of snacks that he can obtain in the vending machine using a given amount of money. He does not have to use all the money.

      Input

      The first line contains a single integer t representing the number of test cases to be solved. The description of t test cases follows.

      The first line of each test case contains two integers  and  (): the number of types of snacks and the amount of money that Byteasar has at his disposal. The second line holds  integers  (), the prices of snacks of respective types. The third line holds  integers  (), the quantities of snacks of respective types that are available in the vending machine.

      Output

      The output should contain one integer per test case: the total price of snacks that Byteasar can obtain in the vending machine using at most units of money.

       

      Example

      Input:
      
      1
      6 8
      7 2 3 5 7 2
      1 3 0 3 2 1
      Output: 
      30
      Task author: Jakub Pachocki

      Added by:acheron
      Date:2013-09-04
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:AMPPZ 2012









      SPOJ Problem Set (classical)

      15847. Equalize the Sectors

      Problem code: SECTORS

      Digo has a cylindrical box which is vertically partitioned into N contiguous sectors which are open from the top. Each Sectorial Compartment initially contains a fixed number of coins. Now Digo wants to fill each Sectorial Compartment with equal number of coins. But the problem is that, at a time he is only allowed to increment any two adjacent sectors with one coin each. Given an initial arrangement, you need to tell whether such equalization is possible or not.

      Every sector i (for all (0 < i < N)) is adjacent to sector (i + 1) and sector N is adjacent to sector 1.

      Input

      In first line, the number of test cases T.

      Each test case consists of a number N, followed by a line containing N space seperated integers where ith integer (Mi) denotes the number of coins in ith sectorial compartment of the box (initially), in clockwise order.

      Output

      For every test case output “YES” for possible and “NO” for which equalization is not possible (Without quotes).

      Constraints

      1 <= T <= 1000

      3 <= N <= 100 (Number of Sectorial Compartments)

      1 <= Mi <= 10^9 (Number of coins in each Sectorial Compartment)

      Sample Input

      2

      3

      1 2 3

      4

      1 2 1 2

      Sample Output

      YES

      NO


      Added by:Surya kiran
      Date:2013-09-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Codeblitz-4









      SPOJ Problem Set (classical)

      15849. Find the Treasure

      Problem code: DIGOKEYS

      A psychic lock-lover called Digo likes playing games with Locks and Keys and also has very good logic.

      One day he buys a set of N boxes, each of them has an index between {1, N} (inclusive) and no two boxes have same index. There is a key inside every box except the Nth box which has great treasure. He eventually finds out that due to a defect in the manufacturing of the keys, most of them could open more than one box.

      The rule is that you are allowed to open only one box with any key. Each box except the first is locked. Now as Digo couldn’t wait long to acquire that great treasure he requests you to find a method to open the last box starting with the key in the first box with minimum number of steps.

      INPUT

      In first line, T no. of test cases.

      For every test case:

      In first line, there is an integer N : (number of locks)

      In next N-1 lines, on the i’th line there is an integer Mi the number of boxes which the key present in the i’th box can open. It is followed by the Mi integers (the indices of those boxes that can be opened by the key present in i’th box).

      OUTPUT

      For every test case:

      one integer q, minimum number of boxes opened.

      In the next line :  the indices of the boxes opened in order separated by space. If there are many solutions print the one which is lexicographically smallest.

      If there is no way to reach the last box print “-1”.

      Each test case is to be followed by a blank line.

      Constraints

      1 <= T <= 10

      2 <= N <= 100000

      1 <= Mi <= 10

      Sample Input

      2

      3

      1 2

      1 3

      4

      2 2 3

      1 1

      2 2 4

      Sample Output

      2

      1 2

       

      2

      1 3


      Added by:Surya kiran
      Date:2013-09-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Codeblitz-4









      SPOJ Problem Set (classical)

      15850. Game

      Problem code: DGAME

      Digo is planning to recruit members for his ACM team, he designs a game in which who ever beats him will be recruited in his team. Darshil is a friend of yours. You have to help him get recruited in Digo's ACM team.

      There are N piles , where ith pile contains either 2*i or 2*i+1 stones. During the game, Darshil and Digo take turns and Darshil takes the first turn. In each turn they can select any pile containing 2 or more stones and then remove an EVEN number of stones from the selected pile. The player who can't make the next move loses the game.

      You have to find:-

      1. Number of ways in which stones can be put in those N piles. (Each way is distinct if any one pile has different number of stones). If number of ways is M then print M % 1000000007.

      2. For each configuration of part-1 Darshil counted the number of ways he can choose the first move such that no matter how optimally Digo plays he wins. Find the integral part of average number of such ways of all the configurations.

      Input Format

      The first line contains an integer T (number of test cases).

      Each of the next T lines contains a single positive integer N.

      Output Format

      T lines containing two space-separated integers - the answers to the first and second parts of the questions.

      Constraints

      1 <= N <= 10^9

      1 <= T <= 10^3

      Sample Input

      3

      1

      2

      3

      Sample Output

      2 1

      4 1

      8 0


      Added by:Surya kiran
      Date:2013-09-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Codeblitz-4









      SPOJ Problem Set (classical)

      15851. Permutations

      Problem code: PSERVICE

      A website provides its users with a variety of services. There are a total of K services available on that website. At present there are M users/clients registered to the website.

      Now each client of this service provider firm is to be allocated a project by the website which makes use of a string A1,A2,A3.............An of N services all of which the website is providing. The order in which the services are executed matters (compiling and then linking is different from linking and then compiling). Also, in a particular project, the same services cannot be executed twice in succession. For example, compiling → linking → compiling is allowed, but linking → linking → compiling is not allowed because 'linking' comes twice in succession.

      All the M clients will start working at the same time and the time taken for the execution of all services is equal. At a time, one service can be accessed by only one client as there is only one server. For eg. If there are 3 clients with projects – A1,A2...An ; B1,B2....Bn and C1,C2....Cn , then Ai, Bi, Ci are pairwise distinct for 1 <= i <= N. You need to find in how many ways in which the M clients can be allocated their projects.

      Input

      First line containing T (number of test cases).

      For each test case one line containing 3 integers N ,M and K.

      Output

      For each test case output a separate line containing the answer modulo 1000000007.

      Constraints               

      1 <= T <= 10

      0 <= N <= 1000000000

      1 <= M <= 100

      0 <= K <= 1000

      Sample Input

      3

      2 2 3

      1 2 3

      2 3 4

      Sample Output

      18

      6

      264

       


      Added by:Surya kiran
      Date:2013-09-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Codeblitz-4









      SPOJ Problem Set (classical)

      15863. Crazy Tank

      Problem code: CRAZY

       Crazy Tank was a famous game about ten years ago. Every child liked it. Time flies, children grow up, but the memory of happy childhood will never go.

      Now you're controlling the tank Laotu on a platform which is H meters above the ground. Laotu is so old that you can only choose a shoot angle(all the angle is available) before game start and then any adjusting is not allowed. You need to launch N cannonballs and you know that the i-th cannonball's initial speed is Vi.

      On the right side of Laotu there is an enemy tank on the ground with coordination (L1, R1) and a friendly tank with coordination (L2, R2). A cannonball is considered hitting enemy tank if it lands on the ground between [L1, R1] (two ends are included). As the same reason, it will be considered hitting friendly tank if it lands between [L2, R2]. Laotu's horizontal coordination is 0.

      The goal of the game is to maximize the number of cannonballs which hit the enemy tank under the condition that no cannonball hits friendly tank.

      The g equals to 9.8.

       

      Input 

      There are multiple test case.

      Each test case contains 3 lines.

      The first line contains an integer N (0N200), indicating the number of cannonballs to be launched.

      The second line contains 5 float number H (1H100000), L1, R1 (0 < L1 < R1 < 100000) and L2, R2 (0 < L2 < R2 < 100000). Indicating the height of the platform, the enemy tank coordinate and the friendly tank coordinate. Two tanks may overlap.

      The third line contains N float number. The i-th number indicates the initial speed of i-th cannonball.

      The input ends with N = 0.

       

      Output 

      For each test case, you should output an integer in a single line which indicates the max number of cannonballs hit the enemy tank under the condition that no cannonball hits friendly tank.

       


      Hint:

      In the first case one of the best choices is that shoot the cannonballs parallelly to the horizontal line, then the first cannonball lands on 14.3 and the second lands on 28.6.

      In the second there is no shoot angle to make any cannonball land between [35,40] on the condition that no cannonball lands between [2,30].

       

      Sample Input 

       

      2
      10 10 15 30 35
      10.0
      20.0
      2
      10 35 40 2 30
      10.0
      20.0
      0
      

       

      Sample Output 

       

      1
      0
      

       


      Added by:Bidhan Roy ( বিধান )
      Date:2013-09-05
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:2012 ACM-ICPC Asia Jinhua Regional









      SPOJ Problem Set (classical)

      15864. SUMMING

      Problem code: SUMMING


      Find the sum of x smallest distinct numbers of the series 2^i*3^j (i and j >= 0)

      the first number of the series is 1 = 2^0*3^0
      the second number of the series is 2 = 2^1*3^0
      the third number of the series is 3 = 2^0*3^1
      the fourth number of the series is 4 = 2^2*3^0
      the fifth number of the series is 6 = 2^1*3^1
      As the sum can be huge print sum % k


      Input

      The input contains 2 numbers x and k
      1<=x<=10^14
      1<=k<=10^8

      Output
      The output contains sum of the 1st x numbers of the series mod k

      Example

      Input:
      1 1000

      Output:
      1

      Input:
      2 1000

      Output:
      3

      Explanation

      3 = (2^0*3^0 + 2^1*3^0) % 1000

      Input:
      4 1000

      Output:
      10

      Input:
      6 2

      Output:
      0

      Input:
      16 1000

      Output:
      300


      Added by:priyamehtanit
      Date:2013-09-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15867. Great Warrior

      Problem code: SNGGW


      This problem is about an imaginary game. First of all, define a War Board that is a N x N square matrix. Each matrix cell represents a warrior and the value written in the cell is the power of that particular warrior.

      Rules for assigning powers of each warrior

      1. First start filling the main diagonal with numbers 1, 2, 3, 4 .... K according to requirement. Starting of filling always be at the top corner.
      2. Now start filling the anti diagonal with numbers k + 1, k + 2, k + 3, k + 4 .... L according to requirement. Starting of filling always be at the bottom corner. Don't forget that in case of filling the anti diagonal if there is any number already filled it will be modified by the current number that is to be filled, if that particular cell was empty.
      3. Now fill all the empty cells, in anti-clockwise spiral filling manner. The first cell to be filled will be 2nd last column of first row.

      5 x 5 War Board

      Image to describe power assignment to each cell

      Description of game
      The greatest warrior W of king Pushyamitra Shunga is having fight with Yavana warriors. W fights with one Yavana warrior Y at a time. Consider the followings
      1. Power_of_W is more than Yavanas.
      2. W can defeat Y if Power_of_W > Power_of_Y - 1
      3. After each win Power_of_W decreases by Power_of_Y
      4. W can move to cells adjacent to it. If Current_Cell_Location_of_W is (i, j) then
      Next_Cell_Location_of_W will be one of (i ± 1, j ± 1) or (i ± 1, j) or (i, j ± 1)
      5. W will win if W defeats Y such that Power_of_Y = 1, otherwise W is defeated.

      What to code
      You have to code to verify whether W wins or get defeated but don't forget the followings -
      1. The one cell location is of W and other cell locations are of Yavanas
      2. Its up to W to choose the Yavana warrior Y to fight with
      3. Its not necessary that W has to defeat all Yavanas, W just want to win

      [All the information required to solve this problem is provided in the description]

      Input

      First line of input is t, total number of test cases (t < 1001). Next t lines contains value of
      N (2 < N < 1000).

      Output

      Output for each test case is single line printing either DWON Final_Power_of_W (If W wins) or DDOWN (If W is defeated).

      Example

      Input:
      1
      5 Output: DWON 15

      Added by:Abhimanyu Singh
      Date:2013-09-06
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Abhimanyu Singh
      My Problems









      SPOJ Problem Set (classical)

      15891. Prime Generator The Easiest Question Ever

      Problem code: SNGPG


      Prime number questions are always being favorite to everyone. This question is extension to the problem PRIME GENERATOR. The question is very very simple and easier than that you cannot imagine. You have to count total number of such primes p in the range [a ≥ 0, b > 0] so that (p2 + 1) or/and (p2 + 2) is/are prime(s).

      Input

      First line of input is t, (t < 100) total number of test cases. Next t lines contains two integers a and b seperated by space.
      a < 50001, b < 100001 and b > a.

      Output

      In each line print total numbers of such prime numbers.

      Example

      Input:
      2
      0 1
      4 5 Output: 2
      0

      [Consider 0 and 1 as prime numbers for this question]

      Added by:Abhimanyu Singh
      Date:2013-09-08
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Abhimanyu Singh
      My Problems









      SPOJ Problem Set (classical)

      15892. Cave

      Problem code: CAVE2

      Byteasar has discovered a cave. It appears that the cave contains n chambers connected with passages in such a way that there exists a single way of getting from any chamber to any other chamber.

      The cave should now be examined more thoroughly, so Byteasar has asked his friends for help. They have all arrived at the cave and they are willing to divide themselves into groups. Each group should examine the same number of chambers, and each chamber should be examined by exactly one group. Additionally, for the groups not to interfere with each others' work, the members of each group should be able to move between the assigned chambers without passing through chambers assigned to other groups.

      How many groups can the explorers be divided into?

      Input

      The first line of the input contains one integer n (2 ≤ n ≤ 3000000) denoting the number of chambers in the cave. The chambers are numbered  through .

      The following n - 1 lines describe connections between the chambers. The i-th of these lines contains an integer ai (1 ≤ ai ≤ i) which represents a passage connecting chambers number i + 1 and ai.

       

      Output

      Your program should output a single line containing all integers k, such that the chambers can be divided into k disjoint sets of equal size, and one can move between any two chambers belonging to the same set passing only through chambers from this set. The numbers should be written in an ascending order and separated with single spaces.

      Example

      Input:
      
      6
      1
      2
      3
      3
      5
      Output:
      1 3 6
      Task author: Jakub Lacki

      Added by:acheron
      Date:2013-09-08
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:AMPPZ 2011









      SPOJ Problem Set (classical)

      15914. Update Sub-Matrix & Query Sub-Matrix

      Problem code: USUBQSUB


      Updating and querying 1 dimensional arrays is a popular question. How about updating and quering sub-matrices of a matrix?

      A sub-matrix will be depicted as (a, b), (c, d). This implies that it will include all the cells (x, y) such that a<=x<=c and b<=y<=d.

      The matrix is indexed from [1..N][1..N], where N is the size.

       

      You are given a matrix of size NxN, with each element initially set to 0. There are M queries and each query can be of one of the two types:

      1 x1 y1 x2 y2: This query asks you to return the sum of all the elements in the sub-matrix (x1, y1), (x2, y2).

      2 x1 y1 x2 y2 K: This query asks you to add K to each element in the sub-matrix (x1, y1), (x2, y2).

      Input

      The first line of input contains N, M.

      The next M lines contain queries in the same forms as stated above.

      You may assume that x1<=x2 and y1<=y2 for all queries.

      Also N<=1000 and M<=105. K<=109

      Output

      The answer to all the queries wherein you need to return the sum of elements in the sub-matrix, i.e., all the queries of type 1.

       

      Sample Test Case

      Input:
      5 5
      2 2 2 4 4 4
      1 1 1 3 3
      2 5 5 5 5 3
      1 1 1 1 2
      1 2 2 5 3
      Output: 16
      0
      24

      Note: Please be careful with certain languages as the output may exceed the range of the data type used to store it.
      Please use 64-bit integers to store the results. For example, long long in C/C++.

      Added by:Pushkar Mishra
      Date:2013-09-11
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (main)

      15961. MAXSET

      Problem code: MAXSET

       

      Krish is teaching Ram Bubble sort .whenever kirsh swaps two elements in the array (while sorting),he ties a rope that connects both the element in the array.
      find the size of the maximal set in the array in which none of the elements are connected with any other element .
      eg : { 1 , 3 ,2 }
      1st iteration of bubble sort :
      2 and 3 swapped so tie 2 with 3 
      {1 ,2,3}
      2nd iteration 
      {1,2,3}
      3rd iteration 
      {1,2,3}
      now ans is 2 .since size of  the maximal set  in which none of the elements is not connected with any other element.
      the possible maximal sets are {1,2} (since 1 and 2 are not tied with a rope) and {1,3}  { since 1 and 3 are not tied with the rope }
      Input :
      First line of input contains T  - No of test cases 
      first line of each test case contains n ( 1 <= n <= 100000 )- number of elements in the array 
      second line  of each test case contains n elements of the array 
      output :
      print the size of the maximal set ( for each test case print a 1new line ) 
      example:
      1
      3
      1 3 2 
      output :
      2

      Ram and Sharav are good programmers  .Ram is teaching Sharav Bubble sort .whenever Ram swaps two elements in the array (while sorting),he ties a rope between the element which are swapped.

      find the size of the maximal set in the array in which none of the elements are connected with any other element after the bubble sort is done .

      eg : { 1 , 3 ,2 }

       

      1st iteration of bubble sort :

      2 and 3 swapped so tie 2 with 3 

      {1 ,2,3}

      2nd iteration 

      {1,2,3}
      no swaps in this iteration so dont tie any element with any other element 

      3rd iteration 

      {1,2,3}
      no swaps in this iteration so dont tie any element with any other element  

      after the end of bubble sort only 2 and 3 are tied together 

      Answer for this example is 2 because the size of  the maximal set  in which none of the elements is not tied with any other element.

      the possible maximal sets are {1,2} (since 1 and 2 are not tied with a rope) and {1,3}  { since 1 and 3 are not tied with the rope }

      Possible subsets for this array are {1} , {2}, {3} ,{1,2} ,{1,3} ,{3,2} {1,3,2},{ }

      out of these valid subsets are {1},{2},{3},{1,2},{1,3} In this valid subsets {1,2} and {1,3} are larger subsets .The size of both the subsets are 2 .so the answer is 2.

      Input :

      First line of input contains T  - No of test cases 

      first line of each test case contains n ( 1 <= n <= 100000 )- number of elements in the array 

      second line  of each test case contains n elements of the array 

       

      output :

      print the size of the maximal set ( for each test case print a 1new line ) 

       

       

      example:

      input : (from the example explained above )

      1

      3

      1 3 2 

       

      output :

      2

      Note : ropes are tied between two elements which are swapped while  executing the sort routine. (bubble sort) .we need the size of the set containing the maximum number of elements which are not connected to any other element in the set .


      Added by:B.R.ARVIND
      Date:2013-09-11
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      15963. Help Donn

      Problem code: HELPDONN

       

      PROBLEM CODE:Enigma Treasure Hunt
      KaushikRamDonn went to Enigma and registered for 
      Treasure Hunt.Following are the rules for Enigma Treasure hunt ,
      Rule 1: Donn has to go from 1st stage to nth stage in a sequential order ( only after completing stage 1 ,he can go to stage 2,then to stage 3). 
      and collect treasures in a bag
      Rule2: Donn will be given only k bags at the time of registration
      Rule3: There are bags capable of holding all possible weights and is infinite in number. Donn is free to choose any bags capable of holding any weight (but all the k bags should be capable of holding the same weight)
      Pandian,the organiser will give the bag ,Euler asked.
      Rule4: once the game is started ,Donn cant exchange his bag .
      Rule5: While going through different stages,if Donn couldnt accomodate the treasure in a bag ,tie the bag and give it to Pandian.(this bag cant be used any more.Then start collecting the treasures in a new bag.
      Rule6: The cost of the bag is directly proportional to the weight it can hold ,so try to reduce the cost.
      Fortunatley ,Donn knows the weights of the treasure in each stage ,Help Donn Choose his bag (maximum bag size needed) .
      Example: 
      Consider there are 3 stages(n= 3) in the Hunt.the weight of the treasures in each of these stages (which is known to donn before the hunt starts)
      are 1,2 and 3. Donn is  allowed to get 2 bags(k= 2) in this example
      n = 3, k= 2
      stages = {1,2,3}
      Donn could accomplish his target if each of his bag can accomodate 3 kg or 5 kg.
      Explanation :
      if the wieght of the bag is 3 - Stage1 weight + stage2 weight = 1+2=3 <=3 in one bag ,stage 3 weight= 3<=3  in another bag.thus they fit in the bags
      if the wieght of the bag is 5 - Stage1 weight = 1<=5 in one bag,stage2 + stage 3 weight= 2+3 =5 <=5 in another bag.thus they fit in the bags
      but consider a bag size of 2 :
      1 + 2> 2 so put stage1 treasure alone in 1st bag
      2 + 3 >2 so put stage2 treasure alone in 2st bag
      now we need one more bag to put in the 3rd treasure.
      This is not possible so u cant choose a bag of size 2
      bag of size >=3 can be used 
      Donn is intelligent and so he wants to pay the minimum cost so Donn will purchase a bag of size 3.Help Donn solve his problem .
      Input:
      0< T <=100 ,no of test cases 
      Each test case contains
      0<N<=1000,no of stages and then a space followed by
      0<k<=1000, no of bags allowed
      the next N lines contains the weights of the treasures in each stage
      output:
      output a single line containing the minimum size of the bag needed.
      Example
      Input:
      1
      3 2
      1
      2
      3
      output :

       

      PROBLEM CODE:Enigma Treasure Hunt

      KaushikRamDonn went to Enigma and registered for 

      Treasure Hunt.Following are the rules for Enigma Treasure hunt ,

      Rule 1: Donn has to go from 1st stage to nth stage in a sequential order ( only after completing stage 1 ,he can go to stage 2,then to stage 3). 

      and collect treasures in a bag

      Rule2: Donn will be given only k bags at the time of registration

      Rule3: There are bags capable of holding all possible weights and is infinite in number. Donn is free to choose any bags capable of holding any weight (but all the k bags should be capable of holding the same weight)

      Pandian,the organiser will give the bag to Donn.

      Rule4: once the game is started ,Donn cant exchange his bag .

      Rule5: While going through different stages,if Donn couldnt accomodate the treasure in a bag ,he will tie the bag and give it to Pandian.(this bag cant be used any more).Then he starts collecting the treasures in a new bag.

      Rule6: The cost of the bag is directly proportional to the weight it can hold ,so try to reduce the cost.

      Fortunatley ,Donn knows the weights of the treasure in each stage ,Help Donn Choose his bag.

       

      Example: 

       

      Consider there are 3 stages(n= 3) in the Hunt.the weight of the treasures in each of these stages (which is known to donn before the hunt starts)

      are 1,2 and 3. Donn is  allowed to get 2 bags(k= 2) in this example

       

      n = 3, k= 2

      stages = {1,2,3}

       

      Donn could accomplish his target if each of his bag can accomodate 3 kg or 5 kg.

      Explanation :

      if the wieght of the bag is 3 - Stage1 weight + stage2 weight = 1+2=3 <=3 in one bag ,stage 3 weight= 3<=3  in another bag.thus they fit in the bags

      if the wieght of the bag is 5 - Stage1 weight = 1<=5 in one bag,stage2 + stage 3 weight= 2+3 =5 <=5 in another bag.thus they fit in the bags

      but consider a bag size of 2 :

      1 + 2> 2 so put stage1 treasure alone in 1st bag

      2 + 3 >2 so put stage2 treasure alone in 2st bag

      now we need one more bag to put in the 3rd treasure.

      This is not possible so u cant choose a bag of size 2

      bag of size >=3 can be used 

      Donn is intelligent and so he wants to pay the minimum cost so Donn will purchase a bag of size 3.Help Donn solve his problem .

       

      Input:

      0< T <=100 ,no of test cases 

      Each test case contains

      0<N<=1000,no of stages and then a space followed by

      0<k<=1000, no of bags allowed

      the next N lines contains the weights of the treasures in each stage
      the weight of the treasure <= 1000 . 

      output:

      output a single line containing the minimum size of the bag needed.

       

       

       

      Example

      Input:

      1

      3 2

      1

      2

      3

      output :

       

       

       


      Added by:B.R.ARVIND
      Date:2013-09-11
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15965. PLAY WITH MATH

      Problem code: ENIGMATH

       

      You have been fed up with competitive programming questions so far ,now it is time to solve little math .
      Assume u have a equation A * x - B * y = 0
      For a given value of A and B , find the minimum value of x and y that satisfies this equation.
      Input :
      first line contains T ,number of test cases  0<= T <=1000
      firstline of each test case contains two space seperated integers A and B. 0<=A,B<=1000000000 
      Ouput :
      For each test case output a single line containing two integers x and y (seperated by a single space )
      Example :
      Input :
      1
      2 3 
      Ouput :
      3 2 
      Note:Be careful with the datatype u choose .Also note the input range carefully.
      negative number cases is avoided to make the problem easy.But look brute force wont pass .

       

       

      You would have been fed up with competitive programming questions so far ,now it is time to solve little math .

      Assume u have a equation A * x - B * y = 0

      For a given value of A and B , find the minimum positive integer value of x and y that satisfies this equation.

      Input :

      first line contains T ,number of test cases  0<= T <=1000
      followed by T lines 

      firstline of each test case contains two space seperated integers A and B. 1<=A,B<=1000000000 

      Ouput :

      For each test case output a single line containing two integers x and y (seperated by a single space ) .Print new line after each test case.

      Example :

      Input :

      1

      2 3 

      Ouput :

      3 2 

      Note: Brute force wont pass the given constraint.

      Negative number cases is avoided to make the problem easy.

       

       

       

       


      Added by:B.R.ARVIND
      Date:2013-09-12
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15980. Ascending Fibonacci Numbers

      Problem code: ASCDFIB

      John is trying to learn the Fibonacci sequence. This is what he has learned so far. The first two terms of the sequence are f(1) = 0 and f(2) = 1.  The next term f(n) is then calculated by adding the previous two terms f(n-1) and f(n-2). Therefore,

      f(1) = 0

      f(2) = 1

      f(3) = f(2) + f(1) = 1 + 0 = 1

      f(4) = f(3) + f(2) = 1 + 1 = 2

      f(5) = f(4) + f(3) = 2 + 1 = 3

      f(6) = f(5) + f(4) = 3 + 2 = 5

      After calculating this for a while, John realized that the values are becoming too big. In order to keep the values small, John changed his algorithm. Instead of calculating f(n) = f(n-1)+f(n-2), he decided he will calculate f(n) = ( f(n-1)+f(n-2) ) % 10^5.

      Now John wants to do some research on his new modified Fibonacci sequence. He will give you an integer A (A<=10^5) and an integer B (B<=10^6). You have to output all the terms from f(A) to f(A+B) in ascending order (non-decreasing order). But printing so many numbers is too much of a hassle. So, if there are more than 100 terms in the output, then only print the first 100.

      Input

      The first line contains an integer T (T<=100), which is the number of test cases.
      Each test case contains two positive integers A and B as mentioned before.

      Output

      For each test case, print case number (Check sample output) and then print the terms from f(A)  to f(A+B) in ascending order (non-decreasing order). If there are more than 100 terms in the output, then only print the first 100.

      Example

      Input:
      

      3 1 3 3 3 100 1 Output:

      Case 1: 0 1 1 2 Case 2: 1 2 3 5 Case 3: 15075 69026

       


      Added by:Mohammad Samiul Islam
      Date:2013-09-13
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15994. Boxes of Chocolate

      Problem code: BOXSCHOC

      Choco-moo has gone to the super market to buy chocolates for his friends. He entered a shop and found that they sell many boxes of chocolates. All the chocolate boxes are lined up on the display and there are exactly N (0 < N <= 100000) chocolate boxes. The i-th number box contains Ai (0 < Ai <= 100000) amount of chocolates inside. Choco-moo loves chocolates and wants to buy all of the boxes, but he won’t. He will only buy boxes that contains amount of chocolates that can be divided by K (0 < K <= 100000) since he has K number of friends and wants to divide the chocolates equally without wasting any chocolates.

      Now, you are given the value N and then N numbers indicating the amount of chocolates inside the N boxes. You have to answer some queries for Choco-moo. You will be given Q (0 < Q <= 100000) queries.

      In each query, Choco-moo will provide you with three integers, A, B  (0 < A<=B <= N) and K. Here A and B are index number and K is the number of friends Choco-moo has. Now you have to find how many chocolate boxes Choco-moo can buy between Ath box to Bth box (inclusive)?

      Input

      The first line contains an integer T (T<=2), which is the number of test cases.

      Each test case starts with a number N. After that N positive numbers follow indicating amount of chocolates inside each box. After that an integer Q is provided indicating number of queries to be answered. Each query has three integers, A, B and K. The ranges of the variables are described in the description.

      Output

      For each test case, print case number (Check sample output) and then for every query print the number of chocolate box Choco-moo can buy for his K friends from Ath box to Bth box (inclusive) in a newline.

      Example

      Input:

      2

      5

      1 2 3 4 5

      2

      1 5 1

      1 5 2

      5

      12 32 5 12 9

      3

      1 5 2

      3 5 3

      2 5 2

      Output: 

      Case 1:

      5

      2

      Case 2:

      3

      2

      2

       

      Explanation: In Case 1: Query 1 Choco-moo buys all the boxes since all boxes are divisible by 1. In query 2 he buys second and fourth box since they are divisible by 2 ( 2 and 4 ).

      Note: Let me know if you think the judge data is weak or there is ambigutiy/mistake in the problem statment. 


      Added by:Mohammad Samiul Islam
      Date:2013-09-14
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      15995. Self Numbers

      Problem code: MCUR98

      Background

      In 1949 the Indian mathematician D.R. Kaprekar discovered a class of numbers called self-numbers. For any positive integer n, define d(n) to ben plus the sum of the digits of n. (The d stands for digitadition, a term coined by Kaprekar.) For example:

       

      d(75) = 75 + 7 + 5 = 87

       

      Given any positive integer n as a starting point, you can construct the infinite increasing sequence of integers n, d(n), d(d(n)), d(d(d(n))), ... For example, if you start with 33, the next number is 33 + 3 + 3 = 39, the next is 39 + 3 + 9 = 51, the next is 51 + 5 + 1 = 57, and so you generate the sequence

       

      33, 39, 51, 57, 69, 84, 96, 111, 114, 120, 123, 129, 141, ...

       

      The number n is called a generator of d(n). In the sequence above, 33 is a generator of 39, 39 is a generator of 51, 51 is a generator of 57, and so on.

      Some numbers have more than one generator: For example, 101 has two generators, 91 and 100. A number with no generators is a self-number. There are thirteen self-numbers less than 100: 1, 3, 5, 7, 9, 20, 31, 42, 53, 64, 75, 86, and 97.

      Problem

      Write a program to output all positive self-numbers less than 1000000 in increasing order, one per line.

      Input

      There is no input.

      Output

      All positive self-numbers less than 1000000 in increasing order, one per line.


      Added by:abdelkarim
      Date:2013-09-15
      Time limit:1s
      Source limit:900B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Mid-Central USA 1998









      SPOJ Problem Set (classical)

      15996. Number Magic II

      Problem code: SNGNM2


      num (> 9) be a positive integer. sum is defined as sum_of_digits_of_num. avg is defined as
      sum / digits_in_num and avg takes only integer values (for example 34 / 5 is equal to 6, i.e. integer part of 6.8). Now digits of num are rearranged by taking avg as pivoting element. Rearrangement is done according the following method -

      [step 1]
      new_num = avg;

      read digits of num
      if (digit > avg)
      place digit at rightmost place in new_num
      else
      place digit at leftmost place in new_num 

      [step 2]
      new_num is again rearranged into two numbers, eve_number (formed by taking digits of new_num at places 2, 4, 6, ...) and odd_number (formed by taking digits of new_num at places 1, 3, 5, ...).

      Remember that counting of digit place starts from leftmost digits as 1, 2, 3, 4...

      [step 3]
      if (eve_number has < 3 digits)
      store the number
      else
      calculate avg and again start from process 1

      if (odd_number has < 3 digits)
      store the number
      else
      calculate avg and again start from step 1
       

      Finally all desired numbers are stored and now we have to find two magical coefficients of num, named as alpha and beta.

      [method digit_sum]
      number = num

      do { 
      number = sum of digits of number
       
      } while (number >= 10)

       dig_sum = number

      [alpha]
      digit_sum(summation_of_stored_numbers)

      [beta]
      digit_sum(summation_of_digit_sum(stored_numbers))

      we will say num is magic number if alpha, beta and |aplha - beta| are digits of num.

      Input

      First line of input is t (< 101), total number of test cases. Each test case has n (< 501) as its first input and next n lines contains num (< 10101). 

      Output

      For each test case, write exactly n lines containing value of alpha and beta; and yes or no according to whether or not num is magic number.

      Example

      Input:
      1
      1
      9874
      Output:
      5 5 no

      Explanation

      num = 9874
      avg = 7 (28 / 4)
      rearrangement of num generates new_num = 47798
      thus eve_num = 79 and odd_num = 478
      now eve_num < 100, so 79 is stored.
      but odd_num >= 100 so repeat the full process.
      Finally stored numbers are N[] = 79, 68 and 47

      Make sure that you have to consider the total number of digits not the value of the number so you should not change the total number of digits of the number at any step 


      Added by:Abhimanyu Singh
      Date:2013-09-15
      Time limit:1s-2s
      Source limit:5000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Abhimanyu Singh
      My Problems









      SPOJ Problem Set (classical)

      16015. Queue (Rookie)

      Problem code: QUE1



      There are 'n' people standing in a Queue. You are given the height of each person and the
      number of people who are taller and standing ahead of him. You have to find the position of
      each person.

      There are 'N' people standing in a Queue. You are given the height of each person and the number of people who are taller and standing ahead of him. You have to find the position of each person.

      Input

      First line conatins a single integer T, the number of test cases. It is followed by T test cases each of which conatins 3 lines. First line of each test case contains a single integer N. Second line contains N integers representing the heights of these N people. Third line also contains N integers denoting the number of taller people standing ahead of him.

      Output

      Output one line for each test case which contains the heights of the N people in the order in which they are standing.

      Constraints

      0 < T <= 100

      0 < N <= 1000

      Expected Time Complexity : O(N2)

      Example

      Input:
      1
      5
      33 11 22 44 55
      0 2 1 1 0
      
      
      Output:
      33 22 11 55 44

      Harder Version : Queue (Pro) [QUE2]

      Added by:Shikhar Sharad
      Date:2013-09-16
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:Directi Interview









      SPOJ Problem Set (classical)

      16016. Queue (Pro)

      Problem code: QUE2


      There are 'n' people standing in a Queue. You are given the height of each person and the
      number of people who are taller and standing ahead of him. You have to find the position of
      each person.

      There are 'N' people standing in a Queue. You are given the height of each person and the number of people who are taller and standing ahead of him. You have to find the position of each person.

      Input

      First line conatins a single integer T, the number of test cases. It is followed by T test cases each of which conatins 3 lines. First line of each test case contains a single integer N. Second line contains N integers representing the heights of these N people. Third line also contains N integers denoting the number of taller people standing ahead of him.

      Output

      Output one line for each test case which contains the heights of the N people in the order in which they are standing.

      Constraints

      0 < T <= 20

      0 < N <= 10000

      Expected Time Complexity = O(NlogN)

      Example

      Input:
      1
      5
      33 11 22 44 55
      0 2 1 1 0
      
      
      Output:
      33 22 11 55 44

      Easier Version : Queue (Rookie) [QUE1]

      Added by:Shikhar Sharad
      Date:2013-09-16
      Time limit:0.100s-0.25s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:Directi Interview









      SPOJ Problem Set (classical)

      16017. The Triangle Game

      Problem code: MCU20A

      In the triangle game you start off with six triangles numbered on each edge, as in the example above.  You can slide and rotate the triangles so they form a hexagon, but the hexagon is only legal if edges common to two triangles have the same number on them.  You may not flip any triangle over.  Two legal hexagons formed from the six triangles are illustrated below.The score for a legal hexagon is the sum of the numbers on the outside six edges.

      Your problem is to find the highest score that can be achieved with any six particular triangles.

      The input file will contain one or more data sets.  Each data set is a sequence of six lines with three integers from 1 to 100 separated by blanks on each line.  Each line contains the numbers on the triangles in clockwise order.  Data sets are separated by a line containing only an asterisk.  The last data set is followed by a line containing only a dollar sign.

      For each input data set, the output is a line containing only the word "none" if there are no legal hexagons or the highest score if there is a legal hexagon.

      Sample Input

      1 4 20 
      3 1 5 
      50 2 3 
      5 2 7 
      7 5 20 
      4 7 50 
      * 
      10 1 20 
      20 2 30 
      30 3 40 
      40 4 50 
      50 5 60 
      60 6 10 
      * 
      10 1 20 
      20 2 30 
      30 3 40 
      40 4 50 
      50 5 60 
      10 6 60 
      $

      Sample Output

      152 
      21 
      none


      Added by:abdelkarim
      Date:2013-09-16
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Mid-Central USA 2000









      SPOJ Problem Set (classical)

      16018. Edge Detection

      Problem code: MCU20E

      IONU Satellite Imaging, Inc. records and stores very large images using run length encoding. You are to write a program that reads a compressed image, finds the edges in the image, as described below, and outputs another compressed image of the detected edges.

       

      A simple edge detection algorithm sets an output pixel's value to be the maximum absolute value of the differences between it and all its surrounding pixels in the input image. Consider the input image below:

      The upper left pixel in the output image is the maximum of the values |15-15|, |15-100|, and |15-100|, which is 85. The pixel in the 4th row, 2nd column is computed as the maximum of |175-100|, |175-100|, |175-100|, |175-175|, |175-25|, |175-175|, |175-175|, and |175-25|, which is 150.

      Images contain 2 to 1,000,000,000 (109) pixels. All images are encoded using run length encoding (RLE). This is a sequence of pairs, containing pixel value (0-255) and run length (1-109). Input images have at most 1,000 of these pairs. Successive pairs have different pixel values. All lines in an image contain the same number of pixels.

      Input consists of information for one or more images. Each image starts with the width, in pixels, of each image line. This is followed by the RLE pairs, one pair per line. A line with 0 0 indicates the end of the data for that image. An image width of 0 indicates there are no more images to process. The first image in the example input encodes the 5x7 input image above.

      Output is a series of edge-detected images, in the same format as the input images, except that there may be more than 1,000 RLE pairs.

      Important Note: A brute force solution that attempts to compute an output value for every individual pixel will likely fail due to space or time constraints.

      Sample Input

      7
      15 4
      100 15
      25 2
      175 2
      25 5
      175 2
      25 5
      0 0
      10
      35 500000000
      200 500000000
      0 0
      3
      255 1
      10 1
      255 2
      10 1
      255 2
      10 1
      255 1
      0 0
      0
      

       

       

      Sample Output

      7
      85 5
      0 2
      85 5
      75 10
      150 2
      75 3
      0 2
      150 2
      0 4
      0 0
      10
      0 499999990
      165 20
      0 499999990
      0 0
      3
      245 9
      0 0
      0
      

       


      Added by:abdelkarim
      Date:2013-09-16
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACM Mid-Central Regional Programming Contest 2000









      SPOJ Problem Set (classical)

      16030. Psycho

      Problem code: PSYCHON


       


      Problem Statement:

      Given an integer N, the number N is called “Psycho Number” . Psycho Number is calculated as follows:

      First, If we factorize N , then we have some prime and their power. Assume that, there are M powers. From M powers , you should count the number of even and odd powers. Then if the number of even power is strictly greater than odd power , then we call the number N is “Psycho Number”, otherwise the number N is call “Ordinary Number”.

      As for example, if N = 67500 then prime factorization, 

      67500 = 22 x 33 x 54

      Count even powers and odd powers . This number have 2 even power(2,4) and 1 odd power ( 3 ). Since even power 2 (2,4) is greater than odd power 1 (3), so the number 67500 is a Psycho Number.

      Input:

      An integer T (1 <= T <= 106) denoting the number of test cases followed by T lines. Each containing a single integer N ( 1 <= N <= 107 ) .

      Output:

      For each case print  “Psycho Number” or “Ordinary Number”.

       

      Sample Input/Output:

      Sample Input

      Sample Output

       2

       3

       4

       Ordinary Number

       Psycho Number

       

       

       

      Note : 0 and 1 is not a psycho number .
      Psycho 2 : Psycho Function
      Psycho 3 :
      Make Psycho 
      Psycho 4 : Psycho34 (easy)

      ____________________________________________________________________________________________
      Problem setter:   Shipu Ahamed, Dept. of CSE

      Bangladesh University of Business and Technology (BUBT)

       


      Added by:Shipu Ahamed
      Date:2013-09-18
      Time limit:0.5s
      Source limit:6000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16033. Tip Top Game

      Problem code: TIPTOP


      Problem Statement:

      Alim and sufian are two good friends. They loves to playing game with number recently they discover a new game name “Tip Top”. The rule of the game is they took a number (N) randomly after that they find the all divisors of N. Then they starting to play the game first alim took a divisor, then sufian so on. The person who took the last divisor will win the game.

      Every time the game started with alim . Now alim wants to know when he will win.

      As you a good programmer your task is to find will alim win or not.

       

      Input:

      Input starts with an integer T ( T ≤ 10), denoting the number of test cases. Each case starts with a line containing an integer N ( 1 N 1018 ) the number.

      Output:

      For each case you have to print “Yes” if alim will win otherwise “No” with case number. See the sample input/output for exact formatting.

      Sample Input/Output:

      Sample Input

      Sample Output

       2
       4
       5

       Case 1: Yes
       Case 2: No


      ____________________________________________________________________________________________
      Problem setter: Ajharul Islam Barid, Dept. of CSE

      Bangladesh University of Business and Technology (BUBT)


      Added by:Shipu Ahamed
      Date:2013-09-18
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16034. Minimum Number

      Problem code: MINNUM


       

        Problem Statement:

      Prana has given a number. Now she wonder what will be the maximum number of digits that the sum of these digits is equals to the given number. After thinking sometimes she laughed at herself, cause the number is infinite.

      Now your task is to find the minimum number of digits that the sum of these digits is equals to the given number.

      Input:

      The input contain a single integer N ( 0 ≤  N ≤ 1031 ). The input is terminated by a line containing -1.

      Output:

      Output a single line the number of digits that the sum of the digits is equals to the given number. See the sample input/output for exact formatting.

      Sample Input/Output:

      Sample Input

      Sample Output

       11

       1

       -1

       2

       1


      Explanation :

      For the first test case given number is 11. Some possible way to make 11 is

      7+4=11 which costs 2 digits.

      2+3+6=11 which costs 3 digits.

      1+2+3+5=11 which costs 4 digits.

      1+2+3+0+5=11 which costs 5 digits.


      So, here first example costs the minimum number of digits which is 2.

      Note: There are no extra new lines between different numbers.

      ____________________________________________________________________________________________
      Problem setter: Abu Sufian, Dept. of CSE

      Bangladesh University of Business and Technology (BUBT)


      Added by:Shipu Ahamed
      Date:2013-09-18
      Time limit:1s
      Source limit:3100B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 PAS fpc PAS gpc









      SPOJ Problem Set (classical)

      16035. Fone Frequencies

      Problem code: OU7

       

      When relay towers for mobile telephones communicate with the mobile phones in their area, there is
      always the possibility of interference. So, when assigning the transmission frequency, the FCC makes
      sure that nearby towers have frequencies that aren't too close. On the other hand, the FCC does not
      want to assign too many different frequencies; they want to save as many as possible for other uses.
      Your job is to find an optimal assignment of frequencies.

      When relay towers for mobile telephones communicate with the mobile phones in their area, there is

      always the possibility of interference. So, when assigning the transmission frequency, the FCC makes

      sure that nearby towers have frequencies that aren't too close. On the other hand, the FCC does not

      want to assign too many different frequencies; they want to save as many as possible for other uses.

      Your job is to find an optimal assignment of frequencies.

      Graph

      In this problem, the frequencies will be integers. Nearby towers must be assigned frequencies that differ

      by at least 2. You'll find an assignment using as few frequencies as possible. For example, consider the

      following two arrangements of towers. Two towers near each other are indicated by the connecting line.

      Note that the following are legal frequency assignments to these two tower configurations. However,

      the second arrangement does not use the fewest number of frequencies possible, since the tower with

      frequency 5 could have frequency 1.

      Frequencies Labelled

      Input

      There will be multiple test cases. Input for each test case will consist of two lines: the first line will

      contain the integer n, indicating the number of towers. The next line will be of the form x1 y1 x2 y2 ...

      xn yn where xi yi are the coordinates of tower i. A pair of towers are considered "near" each other

      if the distance between them is no more than 20. There will be no more than 12 towers and no tower

      will have more than 4 towers near it. A value of n = 0 indicates end of input.

      Output

      For each test case, you should print one line in the format:

      The towers in case n can be covered in f frequencies.

      where you determine the value for f. The case numbers, n, will start at 1.

      Example

      Input:
      5
      0 0 5 7.5 1 -3 10.75 -20.1 12.01 -22
      6
      0 1 19 0 38 1 38 21 19 22 0 21
      0
      
      Output:
      The towers in case 1 can be covered in 3 frequencies.
      The towers in case 2 can be covered in 2 frequencies.
      

      Added by:Chad Mourning
      Date:2013-09-18
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16046. Help Professor

      Problem code: HPPROF

      One day, TA of one of the course at DA-IICT was checking First In-sem exam papers. The exam was of 20 marks. After checking some of the papers, he decided to give marks of those students to his professor but he messed up here. He forgot to put spaces between the marks. So professor got confused.

      Since you are his favourite student, help him determine the number of ways in which this marks can be seperated (by spaces) so that they are valid marks.

      Marks are valid if they are between 0 to 20 and have no leading zeros. For example, 0, 1, 2, 3 ... 20 are valid but 01, 003, 21, 25 are not valid.

      Input

      Input contains only one line, a string of length less than 20 .

      Output

      Output the number of ways in which you can put spaces and interprete them as a valid marks of students.

      Example

      Input1 :
      12
      
      Output1 :
      2

      Input2 :
      111 Output2 : 3
      Input3 :
      101
      Output3 :
      2

      Explaination :
      In the first case, 12 can be interpreted in two ways,
      1) 1 2
      2) 12
      In the second case, 111 can be interpreted as following ways.
      1) 1 1 1
      2) 11 1
      3) 1 11
      In the third case,
      1) 1 0 1
      2) 10 1
      Note that 1 01 can not be valid because 01 has leading zeros.

      Added by:Savan Popat
      Date:2013-09-20
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16048. Help Rarity Collect Crystals

      Problem code: PONY9

      Rarity is collecting special crystals for the upcoming Equestria games. Currently, she is in a gem cave and has found a bunch of crystals.

      To Rarity's discerning eye, crystals have three properties: a color, a reactivity level, and a fashion value. Of course, Rarity wants to collect crystals to maximize the total fashion value.

      Rarity knew she wouldn't have enough room in just one bag for all the crystals, so she brought two.

      Well, it turns out that space isn't the main issue that Rarity has. These special crystals are reactive. In their current environment, they are relatively stable, but once Rarity has put them in her bag and taken them out of the gem cave, if the reactivity levels are too high, the gems will disintegrate, and thus lose all their fashion value.

      There are two ways that reactions can happen:

      1. If there are too many gems of the same color, in the same bag, they'll disintegrate.
      2. If the total reactivity level of the crystals in the same bag is too high, they'll disintegrate.

      Different colors of gems have different reaction limits. Also, it is possible that some colors of gems are simply unstable and will always disintegrate when taken outside the cave.

      Twilight Sparkle had studied these crystals at some point, and discovered a way to stop crystals from reacting. The material is difficult to create, but she has still given Rarity a separate, special bag which can hold only a single crystal, but that crystal won't react no matter what while it is in the bag.

      This is the situation Rarity is in, and she needs your help.

      Input

      You will be given T, the number of test cases to follow.

      Each test case begins with a single line containing the values R and C
      R is the maximum reactivity level allowed in a regular bag without having the crystals disintegrate.
      C is the number of different colors of gems that Rarity currently can see.

      The next C lines will be of the form L N r_1 v_1 r_2 v_2 ... r_N v_N.
      L is the limit for how many crystals of this color can be in the same bag without reacting.
      N is the number of crystals of this color that Rarity can see.
      The next 2*N numbers are pairs indicating the reactivity level and the fashion value of each of the N gems.

      Test cases will follow immediately after each other (see sample input)

      Limits:
      1 <= R <= 100
      1 <= C <= 10
      0 <= L <= 3
      1 <= N <= 10

      For any reactivity level 'r' or fashion value 'v', 1 <= r, v <= 1000

      Note that Rarity's two regular bags are large enough to hold any number of crystals.

      Output

      For each test case, on a separate line, output the maximum fashion value of the crystals that Rarity is able to collect in her bags.

      Example

      Input:
      2
      10 2
      1 2 5 1 5 1
      2 2 6 1 6 1
      5 3
      3 3 1 1 1 1 1 1
      3 3 1 1 1 1 1 1
      3 3 1 1 1 1 1 1
      
      Output:
      3
      9
      

      Final note: The time limit for each test case is at a minimum, x3 my Java solution. There are a few files with the input being 1-2MB.


      Added by:Alex Anderson
      Date:2013-09-21
      Time limit:5s-36s
      Source limit:20000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16062. Count Primes

      Problem code: SNGCP


      Let num(num >= 0) is a positive integer or zero. We can represent num in the following two forms if it is possible to do so -
      1. num = n2 + 2 * n, for non-negative integer n
      2. num = m2 - 2 * m, for non-negative integer m

      Suppose there is num that can be represented in both the forms. Consider this type of number as a magic number. Consider the following 5 cases -
      1. n is the only prime.
      2. m is the only prime.
      3. n and m both are primes.
      4. n is prime.
      5. m is prime.

      Input

      First line of input is t, total number of test cases. For each test case the first line is q, total number of queries. Then there will be (2 * q) lines. First line contains c (referring to case mentioned in the problem description) and second line contains two integers a and b defining the range [a, b] for magic number.
      t < 1001
      q < 5001
      0 < c < 6
      minimum_value_of_a = 0
      maximum_value_of_b = 106

      Output

      For every test case, that has q queries, the output has (q + 1) lines. First line will be simply printing the test case number and then q lines will be printing total number of magic numbers in the given range [a, b] under the specific case mentioned in input.

      Example

      Input:
      2
      3
      1
      5 20
      2
      1 30
      3
      10 18
      2
      4
      1 10
      5
      1 10
      Output: Test Case :#1:
      Query :#1: 1
      Query :#2: 1
      Query :#3: 1

      Test Case :#2:
      Query :#1: 1
      Query :#2: 1

      Added by:Abhimanyu Singh
      Date:2013-09-21
      Time limit:0.300s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Abhimanyu Singh
      My Problems









      SPOJ Problem Set (classical)

      16063. Hackers

      Problem code: TREEBA


       

      Hakeri prisluškuju komunikaciju Mirka i Slavka te pokušavaju razumjeti presretnute poruke. Rjeènik Mirka i Slavka sadr¾i M rijeèi te se svaka poruka koju jedan od njih pošalje drugome sastoji od niza rijeèi iz rjeènika odvojenih razmacima. Meðutim, poruke koje hakeri presreæu su zbog slabe kvalitete njihove opreme izmjenjene na sljedeæi naèin:
      1. U poruku je umetnuto najviše K šumova – proizvoljnih nizova slova. Svaki šum je uvijek umetnut izmeðu dvije rijeèi ili prije prve ili nakon zadnje rijeèi, dakle nikad unutar neke rijeèi.
      2. Svi razmaci izmeðu rijeèi u poruci su izbrisani.
      Na primjer ako Mirko pošalje poruku 'mirko slavko', kada je hakeri presretnu ona mo¾e biti 'mirkoxyzslavko', gdje je niz 'xyz' šum, a rijeèi 'mirko' i 'slavko' se nalaze u rjeèniku. Hakerima je poznat njihov rjeènik te su upravo zaprimili novu izmjenjenu poruku koju ¾ele rastaviti na rijeèi iz rijeènika i šumove. Od svih moguæih naèina na koji se to mo¾e napraviti zanima ih onaj gdje ima najviše moguæe rijeèi iz rjeènika. Napišite program koji za zadani rjeènik, zadani broj K, te zaprimljenu izmjenjenu poruku dobivenu na opisani naèin, odreðuje koliko najviše mo¾e biti rijeèi iz rjeènika u rastavu, te odreðuje jedan (bilo koji) rastav u kojem je najviše moguæe rijeèi iz rjeènika.

      Hackers are eavesdropping communication beetwen Mirko and Slavko and trying to understand the intercepted messages.

      Dictionary from Mirko and Slavko contains M words and every message which one of them send to another consists of a series of words from dictionary separated by spaces.

      However, the messages which hackers are intercepting due to poor quality of their equipment are changed as follows:

      1. In the message are inserted at most K noises - arbitrary strings of letters. Every noise is always inserted between two words or before the first or after the last word and never within a word. 
      2. All spaces between the words in the message are deleted. 

      For example, if Mirko sends a message 'mirko slavko', when hackers intercept it, it can be 'mirkoxyzslavko', where 'xyz' is a noise, and the words 'mirko' and 'slavko' are found in the dictionary.

      Hackers know their dictionary and have just received a new altered message which they want to disassemble to the dictionary words and sounds. Of all possible ways in which they can do that, they are interested in the one which has the most words from the dictionary.

      Write a program that, given the dictionary, the number K, and received a modified message obtained as described above, determines a way in which the most words from dictionary are used.

       

      Input

      The first line contains number T ( 1 ≤ T ≤ 12 ) - the number of test cases.

      The second line contains two integers M (1 ≤ M ≤ 1000) and K (0 ≤ K ≤ 10) - the number of words in the dictionary and the maximum amount of noise in each received message. 

      The third line is the text messages received - a series of lowercase letters of length N (1 ≤ N ≤ 10 000). Each of the following M lines contains a word in the dictionary - a series of at least one and a maximum of 20 lowercase letters.

      Output

      In the first line of output write maximum number of words from the dictionary in disassembled message.

      Example

      Input:
      1
      5 3 
      prisluskujuabcdnassumhakeri 
      mirko 
      nas 
      slavko 
      hakeri 
      prisluskuju
      Output:
      3

      Explanation: One of the messages is 'prisluskuju #### nas ### hakeri' which has two noises, and maximum of three words.


      Added by:Ivan ©ego
      Date:2013-09-21
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Modified task from Croatian regional competition 2013









      SPOJ Problem Set (classical)

      16102. Can you play carrom !!!

      Problem code: CARRHIM

      Carrom board is a very popular game. There are four player in this game in dual player mode. In dual player game the team is pair with opposite side player.

       

      carrom

       

      So, in picture you see the board and the player’s.  Where the player A and the player C in team-1, the player B and the player D in team-2.

      In this game a team is play with one color pawn. So, if team-1 start playing the board they take the white pawn, and the team-2 get the black pawn for the game. If team-1 can cover all the pawn before the team-2 and the red also covered by the time then the team-1 will win. Otherwise team-2 will win if they cover their all pawn in the game.

      Now, There are 9 white pawn and 9 black pawn and one red pawn in the board. The game is played by different rule.

      In my problem of this game the rule like,

      The point for the one pawn is 1 and for red is 5.

      You can assume that which player 1st start playing  the game is start with the white pawn.one team must cover red pawn and this team will get the red point.And you know the penalty rule is If one player cover one pawn of opposite team then the turn goes to the next player.

      Now your task is to find the winner team & points.

      The points count by the remaining of pawn in the board and plus the covered red pawn point by the winning team.

       

      Input

      Input consists of pairs of lines (at most 100 lines). Each pair contains 1 charecter and 3 integer.A first charecter is the player id(A , B , C or D) and three integer is W, B, R (1<= W, B<=9) separated by a space that is number of white, black and red pawn the player cover in his turn.The end of one input occurs when the first sequence starts with an "#" character (without the quotes).

       

      Output

      For each case if the game complete then you have to print a string “Team-1 win and the point is N.” (without the quotes) when team-1 win , Otherwise   “Team-2 win and the point is N.” (without the quotes).

      If the game is incomplete then print a string "Incomplete game." (without the quotes) when a team can not cover all the pawn of his turn.

      N is the total point of winner team. See the sample input/output for exact formatting.

       

      Sample

      Input :

      A 5 1 0

      B 1 2 0

      C 2 1 1

      D 1 0 0

      #

      B 1 1 0

      C 1 2 0

      D 3 1 1

      A 1 2 0

      B 3 0 0

      #

      A 1 1 0

      B 1 5 1

      C 1 1 0

      #

      Output :

      Team-1 win and the point is 10.

      Team-2 win and the point is 8.

      Incomplete game.

       

      Explanation :

      For the first input player A start the game so the team-1 play with the white pawn.
      After all input the team-1 cover all of white pawn also the red pawn.
      and there are 5 black pawn remain in the board.
      so, team-1 win and the point is 5+5=10.

      ____________________________________________________________________________________________________________

       Problem setter: Md. Hashibul Amin Hemel, Dept. of CSE

      Bangladesh University of Business and Technology (BUBT)

       

      
      

       

       


      Added by:hemel
      Date:2013-09-23
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      16113. Trucks Transportation

      Problem code: SUBTLEBA

      The Subtle Balloons Company (SBC) is the main balloon provider for programming contests; it has huge factories and warehouses, as well as an extensive truck fleet to ensure the contestants’ happiness. There are lots of competition sites in Nlogonia, and all of them hired SBC for supplying balloons for their contests. Nlogonia is an archipelago connected by several bridges. Every island of Nlogonia may have several regional sites and may also house several SBC warehouses. When planning the routes for balloon deliveries, SBC faced a problem: for safety issues, every bridge in Nlogonia has some maximum weight limit for vehicles which cross it. And because of the great net weight of the transported merchandise, SBC operations’ chief asked you to write a program to determine the maximum weight allowed to be transported between warehouses and competition sites.

      Input

      The input contains several test cases. The first line of a test case contains three integers  
      N(2 ≤ N ≤ 2 × 104), 
      M(1 ≤ M ≤ 105),
      S(1 ≤ S ≤ 5 × 104

      which indicate, respectively, the number of islands, the number of bridges that connect the islands and the number of sites. The islands are numbered from 1 to N. Each of the next lines describes a bridge. The description of a bridge consists in a line with three integers Aand W(0 ≤ W ≤ 105), indicating respectively the two islands connected by the bridge and the maximum weight allowed in that bridge, in tons. All bridges are two-way roads; every pair of islands is connected by at most one bridge; and it is possible to reach every other island in the archipelago using only bridges (naturally it may be needed to pass through other islands to do so). Each of the next lines describe a competition site and contains two integers and indicating, respectively, the number of the island where this site is and the number of the island where the wharehouse which will be used to deliver the balloons to the site is.

      (1 ≤ A,B,L,H ≤ NA != BL != H)

      Output

      For each site in a test case, in the order they were given, your program must produce a single line, containing a single integer, the biggest weight which can be transported by truck from the warehouse to the site.

      Example

      Input:
      4 5 4
      1 2 9
      1 3 0
      2 3 8
      2 4 7
      3 4 4
      1 4
      2 1
      3 1
      4 3
      4 5 2
      1 2 30
      2 3 20
      3 4 10
      4 1 40
      2 4 50
      1 3
      1 2 Output: 7
      9
      8
      7
      20
      40


      Added by:Chen Xiaohong
      Date:2013-09-25
      Time limit:1s-3s
      Source limit:40000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Enhanced version of Brazil Maratona 2013 J









      SPOJ Problem Set (classical)

      16121. MODIFY SEQUENCE

      Problem code: NITK06

      Suppose we have a sequence of non-negative integers, Namely a1, a2, ... ,an. At each time we can choose one term ai with 0 < i < n and we subtract 1 from both ai and ai+1. We wonder whether we can get a sequence of all zeros after several operations.

      Input

      The first line is the number of test cases T ( 0 < T <= 20).

      The first line of each test case is a number N. (0 < N <= 10000) The next line is N non-negative integers, 0 <= ai <= 109

      Output

      If it can be modified into all zeros with several operations output “YES” in a single line, otherwise output “NO” instead.

      Example

      Input:
      
      2
      2
      1 2
      2
      2 2

      Output:
      NO
      YES

      Explanation:

      It is clear that [1 2] can be reduced to [0 1] but no further to convert all integers to 0. Hence, the output is NO.

      In second case, output is YES as [2 2] can be reduced to [1 1] and then to [0 0] in just two steps.

      Added by:Gaurav Jain
      Date:2013-09-25
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16128. THE INDIAN OCEAN

      Problem code: NITK07

      Salim is a part of THE INDIAN OCEAN BAND. Each musician of the band has already decided what sound will he play (for the sake of simplicity we assume each musician plays only one sound). We say two sounds are in harmony if the frequency of any one of them divides the frequency of the other (that's a pretty restrictive idea of harmony, but THE INDIAN OCEANS are known to be very conservative in music). Salim knows that the notes played by other players are not necessarily in harmony with each other. He wants his own note to improve the music, so he wants to choose his note so that it is in harmony with the notes all the other musicians play.

      Now, this sounds simple (as all the frequencies are positive integers, it would be enough for Salim to play the note with frequency 1, or, from the other side, the Least Common Multiple of all the other notes), but unfortunately Salim's instrument has only a limited range of notes available. Help Salim find out if playing a note harmonious with all others is possible.

      Input

      The first line of the input gives the number of test cases, T. T test cases follow. Each test case is described by two lines. The first contains three numbers: N, L and H, denoting the number of other players, the lowest and the highest note Salim's instrument can play respectively. The second line contains N integers denoting the frequencies of notes played by the other players.

      1 ≤ T ≤ 40.

      1 ≤ N ≤ 104.
      1 ≤ LH ≤ 1016
      All the frequencies are no larger than 1016

      Output

      For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1) and y is either the string "NO" (if Salim cannot play an appropriate note), or a possible frequency. If there are multiple frequencies Salim could play, output the lowest one.

      Example

      Input:
       3
      3 2 100
      3 5 7
      4 8 16
      1 20 5 2
      2 5 10000000000000000
      9999999999999606 9999999999999822
       
      Output:

      Case #1: NO
      Case #2: 10
      Case #3: 6

      Added by:Gaurav Jain
      Date:2013-09-26
      Time limit:1s-60s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16134. Save the cows!

      Problem code: COD1


      There is a green square grid of size nXm with k cows in it.

      The objective of the cows is to escape the field.If any one of the cows escape all cows are set free.

      There is a farmer who tries to restrict the field by putting up fences along the border .Initially the grid is not fenced.

      Cows coordinate and think of a plan to escape.Cows get the first move.Cows and farmer move alternatively.At any move any one of the k cows can move to their neighboring cell(the cell that shares an edge with it).If the cow is already at the edge of the field and the edge is not fenced then it can escape it and hence all cows are set free.After every move of the cows the farmer can fence some edge at the border of the field of length 1 so that no cow is able to escape from that edge anymore.

      The question is:"Will the innocent cows manage to escape?"

      Input

      First line contains T-number of test cases(0<T<=100)

      Each test case contains 3 integers, separated by space: 1≤n,m≤100 — dimensions of the field and 0≤k≤100 — the number of cows. Each of the next k lines contains 2 integers, separated by space: 1≤x≤n, 1≤y≤m — coordinates of the corresponding cow. There could be more than one cow at a cell.

      Output

      Output one word: "YES" — if cows escape, "NO" — otherwise.

      Example

      Input:
      1
      
      2 2 1
      2 2 1 1 2 Output: YES

      Added by:CSI
      Date:2013-09-27
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      16138. Deconnecting

      Problem code: CODGRF


       

      We define a Beta graph as a set of nodes connected by edges such that one node is connected to another node by at most one edge and no node has an edge starting and ending on itself. Each node has a finite number called 'degree' asssociated with it which is the number of edges connecting that node to the rest of the nodes.
      There are n nodes in a given Beta graph.Those nodes with degree=0 are removed from the graph.Then those, who had degree=1 were removed(and so are the edges connecting that node to the rest of the nodes). Then those, who had degree equal to 2,3,...,n-1 were removed(including their edges).
      For any Beta graph with n nodes find the maximum number of nodes that can remain after the above procedure is completed.

      We define a Beta graph as a set of nodes connected by edges such that one node is connected to another node by at most one edge and no node has an edge starting and ending on itself. Each node has a finite number called 'degree' asssociated with it which is the number of edges connecting that node to the rest of the nodes.

      There are n nodes in a given Beta graph.Those nodes with degree=0 are removed from the graph.Then those, who had degree=1 were removed(and so are the edges connecting that node to the rest of the nodes). Then those, who had degree equal to 2,3,...,n-1 were removed(including their edges).

      For any Beta graph with n nodes find the maximum number of nodes that can remain after the above procedure is completed.

       

      Input

      The first input line contains one number t — amount of tests (1≤t≤10^5). Each of the following t lines contains one integer number n (0≤n≤10^5).

      Output

      For each test case output in a separate line the maximum number of nodes that can remain after the above procedure is completed..

      Example

      Input:
      1
      3
      
      Output:
      1

      Added by:CSI
      Date:2013-09-27
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      16139. Naya Shatranj (New Chess)

      Problem code: CODCHESS


      A and B are playing a very interesting variant of the ancient Indian game 'shatranj(also known as chess)' on a 'maidaan'(chessboard) n×n in size.

      They take turns to put game pieces called 'ghoda'(knight) so that no two 'ghodas'(knights) could threat each other.

      A 'ghoda' located in square (a,b) can threat squares (a+1,b+2),(a-1,b+2),(a+1,b-2),(a-1,b-2),(a+2,b-1),(a+2,b+1),(a-2,b-1),(a-2,b+1).

      The player who can't put a new 'ghoda' during his move loses. Find out which player wins considering that both players play optimally well and A starts.

      Input

      The first line contains integer T (1≤T≤10^4) — the number of 'maidaans' (boards), for which you should determine the winning player. Next T lines contain T integers ni (1≤ni≤10^5) — the sizes of the 'maidaans'(chessboards).

      Output

      For each ni×ni board print on a single line "0" if A wins considering both players play optimally well. Otherwise, print "1".

      Example

      Input:
      2
      2
      1
      
      Output:
      1
      0

      Added by:CSI
      Date:2013-09-27
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      16177. Hashcodes and primes

      Problem code: CODHASH


       

      There are n cards arranged in a row.The rth card from the left has rth prime number written on it on one side the other side is blank.Some cards have the blank side up and the others have the number side up.
      Cards with their blank side up are known as 0-cards and cards showing the prime numbers are known as 1-cards
      A hash code is generated from the set of cards in the following way:
      Initial value of hashcode is 1.
      All the 0-cards should be turned upside down to convert them to a 1-card in order to get the final value of hash code.
       At each step a 0-card can be turned upside down if there's at least one 1-card adjacent to it.Once the card is turned the value of the hash code is changed  according to the following equation:
      new value of hashcode=(previous value of hashcode )*((number on the card)^(number of 0-cards left on the table+1))
      Once all the cards on the table are 1-cards we get the final value of hash code.
      Find the total number of distinct hash codes that can be generated for the given arrangement of cards.

      There are n cards arranged in a row.The rth card from the left has rth prime number written on it on one side the other side is blank.Some cards have the blank side up and the others have the number side up.

      Cards with their blank side up are known as 0-cards and cards showing the prime numbers are known as 1-cards

      A hash code is generated from the set of cards in the following way:

      Initial value of hashcode is 1.

      All the 0-cards should be turned upside down to convert them to a 1-card in order to get the final value of the hash code.

      At each step a 0-card can be turned upside down if there's at least one 1-card adjacent to it.Once the card is turned the value of the hash code is changed  according to the following equation:

      New value of hashcode=(Previous value of hashcode )*((Number on the card)^(Number of 0-cards left on the table+1))

      Once all the cards on the table are 1-cards we get the final value of hash code.

      Find the total number of distinct hash codes that can be generated like this for the given arrangement of cards.

       

      Input

      The first line contains 0<T<=1000 (T-number of test cases)

      The first line of every test case contains two integers n and m where n is the number of cards on the table and m is the number of 1-cards on the table, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of the cards that are 1-cards.

      Output

      For every test case print in a separate line the number of  distinct hash codes that can be generated for the given arrangement of cards modulo 1000000007 (10^9 + 7).

      Example

      Input:
      2
      3 1
      1
      4 2
      1 4
      
      Output:
      1
      2

      Added by:CSI
      Date:2013-09-28
      Time limit:4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      16178. Change

      Problem code: TPC07

      How many ways are there to pay n cents? We assume that the payment must be made with pennies (1 cent), nickels (5 cents), dimes (10 cents), quarters (25 cents), and half-dollars (50 cents).

      For example, there are four ways to pay 13 cents, namely (13 pennies), (2 nickels, 3 pennies), (1 nickel, 8 pennies), and (1 dime, 3 pennies).

      Input

      The input will contain multiple test cases. Each test case contains a single line with a single integer n (1 ≤ n ≤ 1000000000).

      The input will be terminated by the end of file.

       

      Output

      For each input integer n, output how many ways are there to pay n cents in a single line.

      Sample Input

      13
      100000000
      

       

      Sample Output

      4
      66666793333412666685000001
      

       

       

       


      Added by:abdelkarim
      Date:2013-09-28
      Time limit:15s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:TJU Programming Contest 2007









      SPOJ Problem Set (classical)

      16179. Platinum Relic!

      Problem code: PTRELIC

      Samuel has found a copy of a classic videogame called Crash Bandicoot!

      Crash Bandicoot is a platform adventure videogame on which the player must complete levels by destroying crates and beating enemies. After completing successfully a level, the player is awarded with some prizes, such as crystals, gems and relics.

      Samuel has already obtained all the crystal and gems of the game, and now he is aiming for the relics. A relic is obtained after completing successfully a Time-Trial challenge on a level.

      However, Samuel knows there are two kinds of relics: Sapphire and Gold. Gold relics are harder to obtain than the sapphire ones, giving that the challenge must be completed going even faster.

      When you start a Relic Challenge, the game tells you the maximum time you can expend in the level in order to obtain the sapphire relic, and after obtaining it, it tells you the gold relic time.

      And Samuel has found a third hidden kind of relic even harder to obtain, the platinum relic! He wants to complete every challenge with this prize. However, Samuel doesn’t like to guess the time limit to obtain the platinum relic, so he hired you to find it quickly.

      Your program must give the game a time in format hh:mm:ss:mss (hours, minutes, seconds and milliseconds respectively), where all the numbers, except hh, must have leading zeros. (By printing it in STDOUT)

      Examples:
      0:04:57:987

      2:14:08:057

      Once you submit a time, the game will answer you with the relic you will win if you beat the level with that time.

      For example, if the Relic challenges are:

      Sapphire: 0:02:00:000

      Gold: 0:01:35:000

      Platinum: 0:01:00:000

      And you submit 0:01:15:000, the game will answer "GOLD". If you submit 0:02:00:000 you will get "SAPPHIRE" and if you submit a time which surpass all the time limits, you will get "NO RELIC" as an answer.

      When you have the answer, you must print "PLATINUM:", followed by a blank space, and then the maximum time Samuel can expend in order to obtain a platinum relic.

      Some levels are absurdly long, so you must not make any assumption of how long a level can be.

      Input

      You will only receive the Sapphire time limit in the format explained above.

      Run Example

      Game: 0:02:00:000

      You: 0:01:45:000

      Game: SAPPHIRE

      You: 0:01:15:000

      Game: GOLD

      You: 0:00:45:567

      Game: PLATINUM

      You: 0:01:00:000

      Game: PLATINUM

      You: PLATINUM: 0:01:00:000

       

      NOTE: the program should clear the output buffer after printing each line. It can be done using fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution - setlinebuf(stdout).


      Added by:Samuel Nacache
      Date:2013-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Based on a Videogame









      SPOJ Problem Set (classical)

      16180. Ratar

      Problem code: RATAR

       

      Unexpected problems with law enforcement have convinced Mirko to take up a less lucrative but less
      morally ambiguous career: he has become the chief organizer of a team computer science contest.
      There are N CS clubs that wish to participate in the contest. The presidents of the clubs are quite
      stubborn and will participate in the contest only if the contest team size makes it possible for all club
      members to participate.
      The contest consists of two rounds: qualifications and finals. All teams that are competing must have
      an equal number of members and all members of one team must belong to the same club. Any
      number of teams from each club can participate in the qualification round, and the best team from
      each club earns a spot in the finals.
      Mirko is aware that, with a new and unproven contest, he needs publicity. For that reason, he wants to
      set the team size such that the number of individual participants in the finals is as large as possible.
      Remember, each club that participates has a right to one team in the finals. Furthermore, at least two
      clubs must participate in the contest, otherwise the contest would be too boring to attract sponsors.
      Determine the maximum possible number of participants in the finals so that Mirko can double check
      his team size choice.

      After Mirko's failed stint as a coach and a passing obsession with Croatian meat delicacies, his weight

      problems have motivated him to work hard as a farmer. He has moved to a village where his friend

      Slavko lives. Farmers in the village share a large common plot of land in the shape of a N×N square,

      divided into N² unit squares. A unit square at coordinates (i, j) brings in the income of Aij, which can

      be negative (for example, if the square has to be maintained but is not cultivated). The farmers always

      divide the common land into smaller rectangular fields with edges parallel to the common land

      edges.

      Slavko is skeptical of Mirko since his failure as a coach, so he insists that both of them are assigned

      land with the same total income, but also thet the two plots share exactly one common corner so

      that the two friends can keep an eye on each other (Slavko knows that Mirko is prone to mischief). The

      common corner must be the only point where the two plots meet, in order to prevent border-related

      arguments.

      You are given a description of the common land plot. Find the total number of plot pairs that satisfy

      Slavko's criteria.

       

      Input

      The first line of input contains the positive integer N (1 ≤ N ≤ 50), the dimensions of the common

      land plot.

      Each of the following N lines contains N space-separated numbers Aij (-1000 < Aij < 1000), the income

      provided by the respective cell.

      Output

      The first and only line of output must contain the total number of plot pairs satisfying the given

      condition.

      Example

      Input:
      3
      1 2 3
      2 3 4
      3 4 8
      Output:
      7

      Added by:Ivan ©ego
      Date:2013-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Matija Buciæ, COCI 2013/2014









      SPOJ Problem Set (classical)

      16184. Megatron and his rage

      Problem code: CODFURY


       

      Infuriated by the Decepticons' defeat after a long epic battle with the Autobots, Megatron, in his rage, has decided to destroy all the planets on his way back to Cybertron from Earth. There are multiple planets between Earth and Cybertron, and each planet has some number of Autobots to guard it from him. Since Megatron is low on ammo, he wants to fight as few autobots as possible (in fact, not more than "M" of them ) on his way back.
      You need to find the maximum number of planets he can possibly destroy in his journey.
      NOTE: Megatron can start his "destruction spree" from any planet, and can only move to the next planet from the planet he's currently on.

      Infuriated by the Decepticons' defeat after a long epic battle with the Autobots, Megatron, in his rage, has decided to destroy all the planets on his way back to Cybertron from Earth. There are multiple planets between Earth and Cybertron, and each planet has some number of Autobots to guard it from him. Since Megatron is low on ammo, he wants to fight as few autobots as possible on his way back.He can defeat no more than "M" autobots in total.

      You need to find the maximum number of planets he can possibly destroy in his journey.

       

      NOTE: Megatron can start his "destruction spree" from any planet, and can only move to the next planet from the planet he's currently on.

       

      Input

      You will receive one integer "T" denoting the number of test cases. (T<=20)

      Then, the next line will contain two non-negative space-separated integers "P" and "M", where P is the number of planets on his way back (P<=50000) and M is the maximum number of Autobots that Megatron can see (M<=1000,000).

      After that, one line containing P integers separated by a single space will denote the number of Autobots present in each planet. (For each planet there will be no more than 1000 autobots).

      Output

      Your output should consist of "T" pairs of space-separated integers, one pair per line, denoting the number of Autobots Megatron will fight and the number of planets he will destroy respectively.

      Example

      Input:
      1
      4 50
      20 5 23 45
      
      Output:
      48 3
      EXPLANATION : 
      Megatron starts at planet 1 (with 20 Autobots) and goes to planet 2, then the 3rd planet, 
      at this point, he has seen 48 Autobots, if he decides to go to planet 4 he will see 93 Autobots…
      so he stops his journey at the 3rd planet.
      
      Megatron, however, could have started at planet 2 with 5 Autobots, then continue up to the 4th planet, then, 
      he would have seen 73 Autobots, but, as he wants to see the minimum Autobots possible and 
      this number of Autobots exceeds what he wants to see, he decides to choose the way from the 1st to the 3rd planet.

      Added by:CSI
      Date:2013-09-30
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      16185. Mining your own business

      Problem code: BUSINESS

      John Digger is the owner of a large illudium phosdex mine. The mine is made up of a series of tunnels that meet at various large junctions. Unlike some owners, Digger actually cares about the welfare of his workers and has a concern about the layout of the mine. Specifically, he worries that there may a junction which, in case of collapse, will cut off workers in one section of the mine from other workers (illudium phosdex, as you know, is highly unstable). To counter this, he wants to install special escape shafts from the junctions to the surface. He could install one escape shaft at each junction, but Digger doesn't care about his workers that much. Instead, he wants to install the minimum number of escape shafts so that if any of the junctions collapses, all the workers who survive the junction collapse will have a path to the surface.

      Write a program to calculate the minimum number of escape shafts and the total number of ways in which this minimum number of escape shafts can be installed.

      Input

      The input consists of several test cases. The first line of each case contains a positive integer N (N$ le$5 . 104) indicating the number of mine tunnels. Following this are N lines each containing two distinct integers s and t, where s and t are junction numbers. Junctions are numbered consecutively starting at 1. Each pair of junctions is joined by at most a single tunnel. Each set of mine tunnels forms one connected unit (that is, you can get from any one junction to any other).

      The last test case is followed by a line containing a single zero.

      Output

      For each test case, display its case number followed by the minimum number of escape shafts needed for the system of mine tunnels and the total number of ways these escape shafts can be installed. You may assume that the result fits in a signed 64-bit integer.

      Follow the format of the sample output.

       

      Example

      Input:
      
      9
      1 3
      4 1
      3 5
      1 2
      2 6
      1 5
      6 3
      1 6
      3 2
      6 
      1 2
      1 3
      2 4
      2 5
      3 6
      3 7
      0
      Output:
      Case 1: 2 4
      Case 2: 4 1

      Added by:acheron
      Date:2013-09-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ICPC WF 2011









      SPOJ Problem Set (classical)

      16207. Football Fever

      Problem code: DCEPC11F


      Kapish is a huge fan of football. He loves anything and everything related to the game and never misses a single match when his favourite team, Manchester United, is playing. Being the coder that he is, one day he decides to create his own, slightly modified version of football, through code.

      The game is played between 2 teams having M players each and continues for N minutes. In each minute of the game, exactly one of the following 5 events will take place:

      1. Team 1 scores a goal
      2. Team 2 scores a goal
      3. A player from team 1 gets a red card
      4. A player from team 2 gets a red card
      5. None of the above

      A player who gets a red card can take no further part in the game. If at any point of time, a team is left with less than 5 players on the field, it will automatically get disqualified, and the other team will be declared as the winner.

      Kapish is very pleased with his new game. However, Pushap, who hates boring draws in football, is not impressed. “Do you even know how many ways are there for this game to end in a draw?” he asks.

      Given N and M, can you help Kapish find out the number of ways for the game to end in a draw? (draw means both teams end up with the same number of goals at the end of N minutes) Since the number of ways can be very large, you need to print the answer mod 1000000007.

      Note 1: Two ways are considered different, if the event(s) of at least 1 minute are different in them.

      Note 2: For the sake of simplicity, you can assume that all the players in a team are identical.

      Input

      First line contains T, the number of test cases.

      Each test case consists of a single line, with 2 space separated integers, N and M.

      Output

      For each test case, output a single line, containing the number of ways mod 1000000007.

      Example

      Input:
      2
      1 11
      2 8
      
      Output:
      3
      11

      Explanation: In the first test case, in the first minute, the occurrence of any of the events 3, 4 and 5 described in 

      the problem can lead to a draw. Hence there are 3 ways for it to end in a draw.

      Constraints

      1<=T<=100

      5 <= M <= 11

      1 <= N <= 100


      Added by:dce coders
      Date:2013-10-01
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      16208. Challenge Accepted

      Problem code: DCEPC11C


      Aman and Arpit are bored of coding. There is no challenge in it anymore, they feel. Bear in mind that even the problems which would appear very difficult for most of you are trivial for them. With ICPC approaching, their teammate, Sameer, is worried by this development. So, to rekindle their interest in coding, he challenges them to a game.

      The game consists of an N*M grid (N rows, M columns). Some of the cells in the grid are occupied by coins. You can assume that all coins are identical. Sameer then gives them another grid of the same size, with a possibly different arrangement of coins. The objective is simple: the initial grid has to be transformed into the final grid, by moving coins. The following rules apply for coin movements:

      1. In one move, exactly one coin can be moved.
      2. A coin can move one cell up, down, left or right in one move, provided that the destination cell is empty.
      3. If the destination cell is occupied by another coin, then the current coin can jump over that particular coin to land in an empty cell. In fact, a coin can jump over any number of consecutive coins until it lands in an empty cell. It cannot jump over an empty cell. Irrespective of the number of coins it jumps over, it is still counted as one move.

      Whoever solves this in minimum number of moves will be the winner and will get a treat from Sameer. Since both Aman and Arpit really want to win, they immediately proceed to write code for the same. Can you help them predict the minimum number of moves in which the initial grid can be transformed into the final one?

      Input

      First line of input containts T, the number of test cases.

      First line of each test case contains 2 integers, N and M, separated by a single space.

      This is followed by 2*N lines per test case. The first N lines represent the initial grid and the next N lines represent the final grid.

      Each character in the grid is either a ‘C’ or a ‘.’

       ‘C’ means that there is a coin on that cell, and ‘.’ means that the cell is empty.

      Output

      For each test case, output a single line containing the minimum number of moves required. If it is not possible to transform the original grid into the final one, output ‘-1’ (without quotes)

      Example

      Input:
      

      2

      1 5

      .CC..

      CC...

      3 3

      C.C

      .C.

      C.C

      ...

      CCC

      .CC

      Output: 1
      3

      Explanation: In the first test case, the coin to the right can jump over the coin to the left in 1 move.


      Constraints:

      1<=T<=10

      1 <= N*M <= 20


      Added by:dce coders
      Date:2013-10-01
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      16210. Impossible Boss

      Problem code: DCEPC11I


      Vaibhav Sir and Saikat Sir, after completing their graduation, got a job together at a store.

      Their boss at the store was Sidharth Sir, who was very strict and did not want anyone to have fun at the job. He gave Vaibhav and Saikat sir a very boring job of stacking columns of boxes in a row of size N.

      To make it a little interesting, both of them decided that whenever they need to add more boxes, they will choose st and en, such that 1<=st<=en<=N, and place 1 box in column st, 2 boxes in column st+1, … and (en-st+1) boxes in column en.

      When Sidharth sir saw this, he decided to have some fun of his own, and asked them to count the number of boxes in all columns from st to en, and tell him the result. Now Vaibhav and Saikat sir have come to you for help to answer the queries of their boss, as they do not want to lose their jobs.

      Input

      The first line contains N, the number of columns and Q, the number of queries.

      The next Q lines can be of the following form –

      1)      0 st en, meaning Vaibhav and Saikat sir add boxes to the columns from st to en as described above.

      2)      1 st en, meaning Sidharth sir asks them to count the number of boxes in all columns from st to en.

      Output

      For all queries of type 2, output a line containing the answer to the query.

      Example

      Input:
      5 6
      0 2 4
      1 1 5
      0 1 5
      0 3 5
      1 1 5
      1 3 5 Output: 6
      27
      23

      Constraints:

      1<=N, Q<=100000


      Added by:dce coders
      Date:2013-10-01
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      16211. Boring Factorials

      Problem code: DCEPC11B


      Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot. Aman, their friend has been helping them out. But as it goes, Sameer and Arpit have got bored of problems involving factorials. Reason being, the factorials are too easy to calculate in problems as they only require the residue modulo some prime and that is easy to calculate in linear time. So to make things interesting for them, Aman - The Mathemagician, gives them an interesting task. He gives them a prime number P and an integer N close to P, and asks them to find N! modulo P. He asks T such queries.

      Input

      First line contains an integer T, the number of queries asked.

      Next T lines contains T queries of the form “N P”. (quotes for clarity)

      Output

      Output exactly T lines, containing N! modulo P.

      Example

      Input:
      

      3

      2 5

      5 11

      21 71

      Output:

      2

      10

      6

       

      Constraints:

      1 <= T <= 1000

      1 < P <= 2*10^9

      1 <= N <= 2*10^9

      Abs(N-P) <= 1000

      Added by:dce coders
      Date:2013-10-01
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      16212. Jailbreak

      Problem code: DCEPC11J


      The great King Kapish has prisoned Pushap, for he loves the princess Padmavati. To make sure that Pushap and Padmavati never meet again, King Kapish has kept Pushap in his most mysterious of jail.

      This jail is built in a 2D rectangular grid fashion, containing M*N prison cells. The entrance gate for jail is at bottom left corner (0,0). The mysteriousness of this jail comes from the fact that once a prisoner is taken from entrance gate (0,0) to any prison cell, then that prisoner can escape only if he comes back to the entrance visiting the cells used on his way from entrance to his prison cell. Note that in the escape, it is not required for the prisoner to trace the exact path or visit all the cells used on his way up, rather the condition is to use/visit only those prison cells used on his way up. Additionally, when the prisoner is taken from entrance (0,0) to a prison cell, they can fathom upto 2 cells in a single move/step in either upward direction or right direction. And when the prisoner is escaping, he can fathom upto 2 cells in a single move/step in either downward or left direction.

      King Kapish orders to jail prisoner Pushap in cell (M-1,N-1).

      You, being a common friend to Pushap and Padmavati, have to help Pushap escape the prison. Tell him the number of ways in which he can go up to cell (M-1,N-1) and then come back following the procedure described above. Please refer explanation part to know more.

      Input

      First line contains T, the number of test cases.

      Each test case contains 2 space separated integers, M and N.

      Output

      Output exactly T lines, each containing the required answer modulo 10^9 + 7.

      Example

      Input:
      

      3

      2 2

      2 3

      3 4

      Output:

      2

      7

      66

       

      Constraints:

      1 <= T <= 10

      1 < M,N <= 500


      Example:

      For (M,N) = (2,3), one valid way to go up to prison cell and come back is as follows:

      Path taken for going from (0,0) to (1,2) = (0,0) -> (0,1) -> (0,2) -> (1,2).

      Path taken for going from (1,2) to (0,0) = (1,2) -> (0,2) -> (0,0).


      Added by:dce coders
      Date:2013-10-01
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:Own Problem









      SPOJ Problem Set (classical)

      16214. Pabbu-pneumonia

      Problem code: CODPABBU


       

      There is a biology experiment going in the biotech. lab of the "very prestigious" DTU.The students there are trying to study the reproduction patterns of a newly discovered species of virus pabbu-pneumoniae   ;) 
      These pabbu-pneumoniae virus reproduce is a rather strange and fascinating way.
      After adding "a" number of viruses to the petri dish on the first day of they experiment they make the following observations
      On the second day, they found that the virus' number had been increased by "d".
      On the third day, they found that the new number of viruses in the dish was "r" times the number recorded on the second day.
      On the fourth day, they again found that the number had increased by "d" by that recorded on the third day....and so on...
      The pabbu-pneumoniae virus never ceases to reproduce.
      For example, if d=1, r=4 and a = 1..then the number of microbes recorded on each day would be -:
      1 2 8 9 36 37 148 149...
      Given 'a', 'd', 'r' and 'n', you have to find the number of microbes in the petri dish at the end of the n'th day...
      Since the numbers can be pretty large, you are required to print the answer modulo a number "m" ( "m" will be supplied for each case )

      There is a biology experiment going in the biotech. lab of the "very prestigious" DTU.The students there are trying to study the reproduction patterns of a newly discovered species of virus pabbu-pneumoniae   ;) 

      These pabbu-pneumoniae virus reproduce in a rather strange and fascinating way.

      After adding "a" number of viruses to the petri dish on the first day of the experiment they make the following observations

      On the second day, they found that the virus' number had been increased by "d".

      On the third day, they found that the new number of viruses in the dish was "r" times the number recorded on the second day.

      On the fourth day, they again found that the number had increased by "d" by that recorded on the third day....and so on...

      The pabbu-pneumoniae virus never cease to reproduce.

      For example, if d=1, r=4 and a = 1..then the number of microbes recorded on each day would be -:

      1 2 8 9 36 37 148 149...

      Given 'a', 'd', 'r' and 'n', you have to find the number of microbes in the petri dish at the end of the n'th day...

      Since the numbers can be pretty large, you are required to print the answer modulo a number "m" ( "m" will be supplied for each case )

       

      Input

      First line of input will have number 'T', the number of test cases. [ T <= 2000 ]

      Each of the test cases will have 2 lines -:

      First line will have 3 space-separated numbers 'a' ,'d'  and   'r' respectively.

      2nd line will have 2 space-separated numbers 'n' & 'm' respectively.

      Output

      For each test case print the required answer in a separate line.

      NOTE - The value of a , d , r , n & m will be more than 0 and less than 10^8.

      Example

      Input:
      1
      1 2 3
      4 5
      
      Output:
      1
      EXPLANATION - The sequence is - 1,3,9,11,33,35,105.....
      4th term is 11 and 11 % 5 = 1

      Added by:CSI
      Date:2013-10-01
      Time limit:2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      16240. Easy Password

      Problem code: DCEPC11E


      This is the year 2100. Pranjali ma’am due to her intelligence survived this far, by her “Secret Potion” to freeze her age. She keeps her lotion in a very secret vault which is electronic password protected. This is a very special system designed by our great Sameer sir, which don’t take any specific string as a password. Rather than it takes a “Tree”, yes you heard that right a “Tree” of numbers as a password. Your password should be exact to the tree both in structure and value to unlock the vault. Its high time and many hackers are trying to hack the system. So Pranjali ma’am was bit worried and wanted to change the password. Some of the new passwords are very vulnerable so Sameer sir told not to use them. You have to make the new password tree for Pranjali ma’am to keep her “Secret Potion” safe. You are given old password tree, and the one restricted password tree provided by Sameer sir. The structure and value of both might not be same as Sameer sir don’t know the exact password, he only know the current hacking pattern of the hackers.

      You have to make a new password tree with same structure as old password tree, with the nodes of old password tree permuted in some order and any new node should not be exactly equal in position and value to restricted password tree. The position of a node is defined by the sequence of moves (Left / Right) required to go down from the root to that node.

      If there are multiple answers, print the one whose difference is minimum from the old password tree.

      Calculating difference between trees :

      Diff = |sum((old[node[i]] - new[node[i]])*10^i)| where i is n-1 to 0. The ordering of nodes is based on level order traversal of trees. i.e. i will be n-1 for root node and so on.

       

      Input

      First line contains t, number of test cases. In each test case first line contain n and m, n is the number of nodes of old password tree and m is the number of nodes of restricted password tree. Next line contains n space separated numbers(value of nodes of old password tree). Next n lines contains expression like A B, in ith line A and B is the left and right child of node with index i(0 based). If there is no right or left child of a node -1 will be provided in place of any index.

      Next line contains m space separated numbers(value of nodes of restricted password tree).Then this tree is also described as the tree above.

       

      Output

      One integer. Minimum diff as per the above formula between old tree and new tree OR -1 if no such tree is possible.

       

      Constraints

      1 <= T <= 50

      0 <= node_value <= 9

      1 <= n <= 18

       

      Note:

      1. New tree can be same as old tree.

      2. If no such tree is possible print -1

      3. All trees in the problem are Binary Trees

       

      Example

      Input :

      1

      3 3

      5 4 8

      1 2

      -1 -1

      -1 -1

      5 1 8

      1 2

      -1 -1

      -1 -1

       

      Output :

      63

       

      Explanation :


      According to the rule specified above the most feasible tree is rooted at node with value 4 and it's left child being 8 and right child being 5.


      So the minimum diff is 63.

       


      Added by:dce coders
      Date:2013-10-05
      Time limit:0.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      16242. Dexters Trampoline

      Problem code: DTRAP



      Dexter studies in Huber Elementary School, so does his arch rival Mandark. The school planned a fun trip to a carnival for N students. Everyone’s happy. Mandark has devised a plan to ruin the trip. He knows that there exist many groups within the students. Students of one group are friends with each other but not with any student of other groups. His plan is to instigate a fight among them.

      At the carnival, all students line up for time on a trampoline. Dexter learns about Mandark’s plan and knows that If two students that are not friends get on the trampoline at the same time, a fight will start. Suddenly his ‘lab alert’ buzzes. Deedee is trying to break into the lab again! Dexter has to get back home to defend his lab as soon as possible, but he can’t let Mandark ruin the trip.

      The trampoline can handle a total weight of W kgs. The students are getting impatient to get on the trampoline. To save time and to avoid a fight, Dexter decides that he will select the first batch of  students to go on the trampoline in such a way that their total weight exactly equals W and that no two students are not friends. Your job is to tell him  the number of ways he can do  this. Dexter has the knowledge of only M pairs of friends. 

      INPUT:

      The first line contains T, the number test cases. T test cases follow. The first line of each test case contains three integers N, W and M. The next line contains N integers, The ith integer is the weight of the ith student (1<=i<=N). The next M lines contain two integers, q and w; this tells that student q and student w are friends.

      OUTPUT:

      For each test case, output a line containing a single integer, the number of ways Dexter can choose the first batch of students to get on the trampoline.

      CONSTRAINTS:

      1<=T<=10

      1<=N<=22

      1<=q,w<=N

      0<=M<=(N*(N+1))/2

      1<=W<=1500

      1<=Weight of each student<=60

      Assume that the max number of students on the trampoline has no limit. Only the max weight on the trampoline  has the limit W.

       

      SAMPLE TEST CASES:

      INPUT:

      2

      10  90 5

      20 30 10 20 30 50 40 20 40 50

      1 2

      2 3

      3 4

      4 5

      9 10

      5 57 3

      20 10 96 20 1

      1 2

      2 3

      1 3

      OUTPUT:

      3

      0

      EXPLANATION:

      For first test case, the following three ways are possible. Using student number,

      (1,2,3,5)

      (2,3,4,5)

      (9,10)

      For the second test case, no way is possible for total weight of selected students to be exactly W.


      Added by:Abhinav92003
      Date:2013-10-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16243. Anagrams

      Problem code: ANAGR



      Two strings are said to be anagrams of each other if the letters of one string may be rearranged to make the other string.  In this problem you’ll be given two strings. Your job is to find if the two strings are anagrams of each other. If they are not anagrams then find the lexicographically smallest palindrome (in lowercase alphabets) that may be appended to the end of either one of the two strings so that they become anagrams of each other.

      The lower and upper case letters are considered equivalent. The number of spaces  or any other punctuation is not important.

      INPUT:

      The first line of the input contains a number T, the number of test cases. T test cases follow. Each test case consists of two lines, one string in each line.

      OUTPUT:

      For each test case output a single line. Print ‘YES’ (without the quotes) if the two strings are anagrams of each other. If they are not, then print the lexicographically smallest string as discussed above. If no such string exists, then print ‘NO LUCK’ (without the quotes).

      CONSTRAINTS:

      1<=T<=100

      1<=length of the strings<=100

      SAMPLE TEST CASES:

      INPUT:

      4

      Computer programmer

      mature germ romp crop

      Awaaay

      away

      internet

      web

      the terminator

      I’m rotten hater

       

      OUTPUT:

      YES

      aa

      NO LUCK

      YES


      Added by:Abhinav92003
      Date:2013-10-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16244. Kusac

      Problem code: KUSAC


       

      Mirko has given up on the difficult coach job and switched to food tasting instead. Having skipped 
      breakfast like a professional connoisseur, he is visiting a Croatian cured meat festival. The most 
      renowned cook at the festival, Marijan Bajs, has prepared N equal sausages which need to be 
      distributed to M tasters such that each taster gets a precisely equal amount. He will use his trusted knife 
      to cut them into pieces. 
      In order to elegantly divide the sausages, the number of cuts splitting individual sausages must be as 
      small as possible. For instance, if there are two sausages and six tasters (the first test case below), it is 
      sufficient to split each sausage into three equal parts, making a total of four cuts. On the other hand, if 
      there are three sausages and four tasters (the second test case below), one possibility is cutting off three 
      quarters of each sausage. Those larger parts will each go to one of the tasrers, while the fourth taster 
      will get the three smaller pieces (quarters) left over. 
      Mirko wants to try the famous sausages, so he volunteered to help Bajs. Help them calculate the 
      minimum total number of cuts needed to carry out the desired division. 

      Mirko has given up on the difficult coach job and switched to food tasting instead. Having skipped 

      breakfast like a professional connoisseur, he is visiting a Croatian cured meat festival. The most 

      renowned cook at the festival, Marijan Bajs, has prepared N equal sausages which need to be 

      distributed to M tasters such that each taster gets a precisely equal amount. He will use his trusted knife 

      to cut them into pieces. 

      In order to elegantly divide the sausages, the number of cuts splitting individual sausages must be as 

      small as possible. For instance, if there are two sausages and six tasters (the first test case below), it is 

      sufficient to split each sausage into three equal parts, making a total of four cuts. On the other hand, if 

      there are three sausages and four tasters (the second test case below), one possibility is cutting off three 

      quarters of each sausage. Those larger parts will each go to one of the tasrers, while the fourth taster 

      will get the three smaller pieces (quarters) left over. 

      Mirko wants to try the famous sausages, so he volunteered to help Bajs. Help them calculate the 

      minimum total number of cuts needed to carry out the desired division. 

       

      Input

      The first and only line of input contains two positive integers, N and M (1 ≤ N, M ≤ 100), the number 

      of sausages and tasters, respectively.

      Output

      The first and only line of output must contain the required minimum number of cuts.

      Example

      Input:
      2 6 
      
      Output:
      4

      Input:
      3 4 
      
      Output:
      3

      Input:
      6 2 
      
      Output:
      0

      Added by:Tomislav Babic
      Date:2013-10-05
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:COCI 2013 1. round









      SPOJ Problem Set (classical)

      16245. Living with Courage

      Problem code: COURAGE


      Courage (the cowardly dog) lives with his master Muriel and her husband Eustace in the city of Nowhere. Eustace is a farmer but not a very good one. One fine day Courage was taking a stroll in Eustace's cropless field when he found seeds of a magical tree. He seow them in the field and the next morning n magical apple trees grew on the previously cropless field. The number of apples on the ith tree is apples[i] (0<=i< n). The number of apples on a tree may change as sometimes courage eats some apples from a tree and sometimes apples grow instantly on the trees (because they are MAGICAL!!).

      Eustace wants to start a business of apples. So he frequently enquires Courage about the total number of apples present on a range of trees. A range of trees is denoted by two integers, l and r (0<=l<=r< n) and includes the trees from l to r (both inclusive).

      Courage is very loyal to Muriel and wants to keep some apples for her. So whenever Eustace asks about the total number of apples on a range, he deliberately doesn't count the apples on a tree, s, such that l<=s<=r and MIN(apples[l],apples[l+1],apples[l+2],...,apples[r])=apples[s].

      In other words, while calculating the sum of apples on the trees in a range, Courage doesn't include the apples on the tree that has the minimum number of apples in that range.

       

      Input: 

      The first line contains n, the number of magical trees.

      The second line contains n non-negative integers that denote the array apples.

      The third line contains a non negative integer p, which is the number of events that take place.

       Now follow p lines. Each line will be of the form 'EAT x y' or 'GROW x y' or 'COUNT x y'.

       'EAT x y' means that Courage ate x apples from the yth tree. (0<=y< n)

       'GROW x y' means that x apples grew magically on the yth tree (0<=y< n).

       And 'COUNT l r' means that Eustace has told Courage to count the number of apples on the range of trees from l to r, both inclusive.

       Remember that the trees are indexed from 0.

      Output:

       For each 'COUNT x y' event, output a single number that Courage tells to Eustace.

       

      Constraints:

      1<=n<=100000

      1<=p<=100000

      0<=apples[i]<=10^9

      0<=l<=r<n

      0<=y<n

      The number of apples on a tree never exceeds 10^9.

      Sample Input:

      10

      6 5 12 48 3 20 4 2 3 7

      6

      COUNT 2 4

      COUNT 7 9

      GROW 12 4

      COUNT 2 4

      EAT 6 9

      COUNT 7 9

      Sample Output:

      60

      10

      63

      5

      SAMPLE TEST CASE EXPLANATION:

      For 'COUNT 2 4', the sum of apples on trees 2,3 and 4 is 12+48+3=63. But as Courage doesn't include the apples on the tree with the minimum number of apples in the specified range (which in this case is the 4th tree), the number that he has to tell Eustace is 12+48=60.

      For 'COUNT 7 9', the sum of apples on trees 7,8 and 9 is 2+3+7=12. In this case the tree with the minimum number of apples in the range is the 7th tree. So Courage tell Eustace the number 3+7=10

      'GROW 12 4' means that the 4th tree, which has 3 apples, grows 12 more apples on it. So the number of apples on the 4th tree becomes 15.

      For 'COUNT 2 4', the answer will be 48+15=63

      'EAT 6 9' means that Courage eats 6 apples from the 9th tree. So the 9th tree now has 7-6=1 apple.

      For 'COUNT 7 9, the answer will be 2+3=5.


      Added by:Abhinav92003
      Date:2013-10-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16248. Clones

      Problem code: NCLNE


      Trouble has befallen the ninja world (again!). As always, our hero Naruto has taken the responsibility to defend everyone from the evil forces. His signature attack is the cloning jutsu (i.e. cloning technique) in which he produces one clone of himself in one second. Each clone of Naruto can also perform the cloning technique.

      Naruto arrives alone at the battlefield at t=1 second. At each time step , t= 1,2,3,….,n second , some of the Narutos will leave to start fighting the enemy and the rest will stay back and perform the cloning jutsu again. If a clone  has left to fight the enemy he cannot come back to perform the jutsu. Also at t=n seconds all Narutos will go to fight with the enemy, i. e. no more cloning will take place on and after n seconds. Naruto is a very dedicated ninja so he won’t allow any of his clone to stay out of the fight.
      The commander of the ninja forces observes Naruto’s actions. He notes down the number of clones that went to fight the enemy at each time step( from t=1 second till t=n second).  However he is old and doubts if his observations are correct. He hires you, a ninja with sharp analytical skills, to check if his observations can be  valid or not.

      INPUT:

      The first line of the input contains t the number of test cases. The first line of each test case contains n, the time when all Naruto clones go to fight. In the second line of each test case there are n space separated integers that tell how many Naruto clones went to fight at successive seconds, starting from t = 1 second till t = n seconds;

      OUTPUT:

      For each test case output either “Yes” or “No” (without quotes) in a single line. “Yes” if the commander’s observations were correct and “No” if they were wrong;

      CONSTRAINTS:

      1<= T <= 20

      1<= n <=10^6

      Each of the n integers will be less than or equal to 10 ^ 6

      SAMPLE TEST CASES:


      INPUT:

       

      3
      3
      0 0 4
      2
      0 5
      3
      0 1 2

      3

      3

      0 0 4

      2

      0 5

      3

      0 1 2

      OUTPUT:

      Yes

      No

      Yes



      EXPLANATION:

      For the sample test case 2 :

      2

      0 5

      At t = 1 second, Naruto population is 1. According to the commander’s observations no Naruto leaves to fight at t=1 ( and all will perform the cloning jutsu), so the population will become 1 X 2= 2. He observed that at t=2 seconds, 5 narutos went to fight. This is not possible as at t=2 seconds the Naruto population is only 2. Therefore, the commander’s observations are incorrect.

       


      Added by:Abhinav92003
      Date:2013-10-05
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16250. Dilemma

      Problem code: GDIL


       

       Garfield the cat likes candies A LOT. He always keeps a huge stock of it at his home. Today John, his owner, brought home three types of candies. He brought A pieces of Red candy, B pieces of Green candy and C pieces of Blue candy. Garfield is really happy. But the problem is that John won’t allow him to eat all of it at once. He will allow him to eat at most N candies. Garfield is very confused. His love for candies is clouding his judgement and he can’t make a decision on how to choose the N candies.

      Garfield is a dumb cat. So he asks you to find out in how many ways he can choose from the available type of candies so that he eats a total of N candies or less.

      Note: There is no difference between candies of the same color


      Input:


      The first line contains an integer t, the number of test cases. Each test case contains four space separated integers N,A,B,C.


      Output:


      For each test case output a single line containing the number of ways Garfield can choose the N candies.


      Constraints:

       

      0<=t<=100

       0<=N,A,B,C<=5000


      ** No other constraint applicable

       

      SAMPLE INPUT:

      3

      2 1 2 3

      1 1 1 1

      2 1 0 1


      SAMPLE OUTPUT:

      9

      4

      4

      SAMPLE TEST CASE EXPLANATION:


      Explanation for the sample test case 1:


      For the test case 2 1 2 3

       There is 1 piece of Red candy, 2 pieces of Green and 3 pieces of Blue. Garfield can eat at most 2 candies.

       the possible combinations are:

       (R,G,B)

       (0,0,0)

       (0,0,1)

       (0,0,2)

       (0,1,1)

       (1,0,1)

       (0,1,0)

       (0,2,0)

       (1,1,0)

       (1,0,0)

       Therefore 9 is the answer.


      Added by:Abhinav92003
      Date:2013-10-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16254. Running Median Again

      Problem code: RMID2


      Danish has just solved the problem Running Median.

      The first line of the problem says "You will be given some integers in non-decreasing order". The problem asks you to report and remove the median of the list every time it is queried.

      Having solved this problem, Danish now begins to wonder how to solve the problem if the input is in any order (not necessarily non-decreasing order as mentioned above).

      Can you help him?

      Your task is to take as input a list of positive integers. Whenever -1 is given as input, you must output the median of the list, and remove it from the list. Take the smaller element as the median in case of even number of elements.

      Input

      The input contains several test caes.

      The first line contains an integer t, the number of test cases.

      Each test case has several lines, each containing an integer n (<=10^9) . If n is positive, add it to the list. n=-1 indicates a median query (there will be no median query if the list is empty). The test case is terminated by n=0.

      In each test case, there will be upto 10^5 integers to be added to the list, and upto 10^5 median queries.

      Output

      For each median query as described above, print the median on a new line.

      Example

      Input:
      1
      9
      10
      2
      5
      1
      18
      -1
      -1
      4
      3
      -1
      8
      7
      -1
      0
      
      
      Output:
      5
      9
      3
      7
      5
      9
      4

      Added by:Akhilesh Anandh
      Date:2013-10-05
      Time limit:0.5s-5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:variation on RMID









      SPOJ Problem Set (classical)

      16266. Simplifying the Farm

      Problem code: SKSTF


      Farmer John has been taking an evening algorithms course at his local university, and he has just learned about minimum spanning trees. However, Farmer John now realizes that the design of his farm is not as efficient as it could be, and he wants to simplify the layout of his farm. The farm is currently arranged like a graph, with vertices representing fields and edges representing pathways between these fields, each having an associated length. Farmer John notes that for each distinct length, at most three pathways on his farm share this length. FJ would like to remove some of the pathways on his farm so that it becomes a tree -- that is, so that there is one unique route between any pair of fields. Moreover, Farmer John would like this to be a minimum spanning tree -- a tree having the smallest possible sum of edge lengths. Help Farmer John compute not only the sum of edge lengths in a minimum spanning tree derived from his farm graph, but also the number of different possible minimum spanning trees he can create.

      Input

      * Line 1: Two integers N and M (1 <= N <= 40,000; 1 <= M <= 100,000), representing the number of vertices and edges in the farm graph, respectively. Vertices are numbered as 1..N. * Lines 2..M+1: Three integers a_i, b_i and n_i (1 <= a_i, b_i <= N; 1 <= n_i <= 1,000,000) representing an edge from vertex a_i to b_i with length n_i. No edge length n_i will occur more than three times.

      Output

      * Line 1: Two integers representing the length of the minimal spanning tree and the number of minimal spanning trees (mod 1,000,000,007).

      Example

      Input:
      4 5 
      1 2 1 
      3 4 1 
      1 3
      1 4 2 
      2 3 2
      Output:
      4 3

      Added by:Là con gái thật tuyệt
      Date:2013-10-06
      Time limit:0.689s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:USACO Gold Division









      SPOJ Problem Set (classical)

      16267. Real Numbers

      Problem code: REALNO



      Find whether there exists a pair of real nos. whose sum is in range (1,2) in an array consisting of real nos. in the range (0,2). If there exists such a pair print "found" else print "not found". (double quotes for clarity)

      Note: all intervals given above are open intervals.

      INPUT:

      First line is the number of test cases t (t<=6),

      then for each case no. of real nos. in the array is given (n)

      then in the next line the real nos. are given.

      OUTPUT:print the required ans, i.e., "found" or "not found"

       

      Constraints:

      1 <= n <= 3*10^5

      e.g.,

       

      Input:

      2

      3

      0.7 0.5 1.2

      5

      1.2 1.3 1.22 0.999 1.5

       

      Output:

      found

      not found


      Added by:Aditya Gourav
      Date:2013-10-06
      Time limit:0.009s-0.699s
      Source limit:500000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16272. Nanoworld

      Problem code: NANO


      You're living in the future, way beyond the singularity and the exhaustion of ipv6, and you want to plan a fastest trip between your own planet and the planet of the your favourite restaurant.

      You have a map of one-directional nanobot ferry lines between the planets in your system. The map states the distance dij between each (connected) pair of planets i and j, but due to the rapid technical evolution of this time, you estimate the travel time from i to j is dij/t where t is the time at which you choose to depart from i. (It is impossible to travel at t=0).

      Input

      The first line contains T the number of test cases.

      The first line of each test case contains integers t0, N, M where

      • t0 is the time at which you start your trip. 0 ≤ t0 ≤ 109
      • N is the number of planets in your system, numbered 0...N-1. 0 < N ≤ 2.5*105
      • M is the number of connections between planets. 0 < M ≤ 2.5*105

      The following M lines of each test case contain integers i, j, d where

      • i is the source planet. 0 ≤ i < N
      • j is the destination planet. 0 ≤ j < N
      • d is the distance from i to j. 0 ≤ d ≤ 109

      Output

      The arrival time at planet N-1 when starting at planet 0 at time t0, or "Impossible" (quotes for emphasis) if there is no possible route.

      Example

      Input:
      2
      0 5 5
      0 2 2
      2 3 3
      3 4 4
      0 1 5
      1 4 6
      0 2 1
      1 1 0
      Output:
      4.91760625098
      Impossible
      

      Added by:Thomas Dybdahl Ahle
      Date:2013-10-07
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16275. On the side of the road

      Problem code: TAP2013A


      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/tap2013-problems.pdf]

      On the side of the road, there are palm trees, there's a bar, there's shadow, there's something more. In this problem, we are particularly interested in the palm trees.

      Ana, Adan, Alan and Amanda organized a trip: while Ana and Adan where dealing with petty things like checking the car, preparing the luggage and finding a place to stay, Alan and Amanda dedicated themselves to the most important part: studying the views of palm trees to which they would have access to while on the road.

      The road they are now driving on is completely straight, and in this problem we will represent it by the Y = 0 line of the XY plane. On the side of the road with coordinates Y > 0 there are palm trees, which we will represent by different points of the XY plane with positive Y coordinate. Alan and Amanda have noticed that from each point on the road certain palm trees are visible, and in general these vary along the road. A palm tree is said to be visible from a point on the road if and only if the segment that joins both points does not go through any other palm tree.

      In the following figure the unfilled circles represent palm trees in the first sample input, whereas the filled ones represent some possible points on the road.

      TAP2013A

      From point p the palm trees that are visible are a, b and d, since palm tree c is hidden behind palm tree a. From point q the visible palm trees are a, c and d, since palm tree b is now hidden behind palm tree a. From point r all the palm trees are visible, and from point s only palm trees a and d are visible, since palm trees b and c are hidden behind palm tree d.

      While Ana and Adan take turns to drive the car, Alan and Amanda discuss the benefits of knowing how many visible quantities of palm trees there are. Given a set of palm trees, an integer number m is a visible quantity of palm trees if and only if there exists at least one point on the road (i.e. a point with coordinate Y = 0) from which exactly m palm trees are visible.

      In the example illustrated above, 2, 3 and 4 are visible quantities of palm trees, as can be respectively testified by points s, p and r on the road. On the other hand, 0 and 1 are not visible quantities, because from every point of the road at least 2 palm trees are visible. Finally, no m > 4 is a visible quantity, since there are only 4 palm trees in total. Therefore, in this example there are 3 visible quantities of palm trees. (Note that if m is a visible quantity of palm trees, there could be more than one point on the road that testifies to this situation; in the previous example this is the case with points p and q for the visible quantity 3, as well as with infinitely many other points along with r for visible quantity 4.)

      Ana and Adan are getting tired. They want Alan and Amanda to let go of the palm trees and at least prepare some sandwiches. For that reason, you need to make a program to calculate how many different visible quantities of palm trees there are along the road.

       

      Input

      The first line contains an integer number N indicating the number of palm trees that there are on the side of the road (1 ≤ N  1000). Each of the following N lines describes a different palm tree using two integer numbers X and Y, representing the coordinates of said palm tree in the XY plane ( X, Y  105). There are no two palm trees that share the same position.

       

      Output

      Print a single line containing an integer number representing the number of visible quantities of palm trees that there are along the road.

       

      Example 1

      Input:
      4
      2 1
      3 1
      3 2
      3 3
      
      Output:
      3

      Example 2

      Input:
      7
      2 1
      3 1
      4 1
      1 2
      3 2
      5 2
      3 3
      
      Output:
      4
      

      Added by:Fidel Schaposnik
      Date:2013-10-07
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2013









      SPOJ Problem Set (classical)

      16277. Little Red-Cap

      Problem code: TAP2013C


      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/tap2013-problems.pdf]

      Once upon a time there was a very joyous girl who was called Little Red-Cap because she always wore a red riding cap. Red-Cap enjoyed a lot her strolls in the woods, during which she collected berries in her small basket to offer them to her grandmother, who was known to prepare the most delicious pies of all the region. However, Red-Cap definitely did not enjoy the perils of the woods, and in particular the Big Bad Wolf who was always hungry and prying.

      One day, Red-Cap decides to go from her home to that of her grandmother, collecting berries on the way and trying to make her journey in the safest possible way. Red-Cap's house is in a clearing at the westernmost point of the woods, her grandmother's house is in another clearing at the easternmost point, and inside the woods between them there are some other clearings containing berry trees. The woods are very dense, so the only way to go through them is using the pathways between the clearings, which fortunately Red-Cap knows very well. In order not to get lost, Red-Cap always moves through pathways that take her to a point strictly to the east of the point where she is. In order not to be caught by the wolf Red-Cap finds it imperative to avoid an ambush, and for that reason she always has in mind the number of different paths that take her from her current position to her grandmother's home.

      A path in the woods is a sequence of clearings ordered from west to east, such that each clearing is connected with the next by a pathway. A path to the house of Red-Cap's grandmother is simply a path whose last clearing contains said house. For each clearing, its level of alternatives is the number of paths that go from it to Red-Cap's grandmother's house. In turn, for each path its level of alternatives is the sum of the levels of alternatives of all the clearings that make up that path. In order not to be captured by the wolf, Red-Cap wants to find the path with a maximum level of alternatives, starting at her house and ending at her grandmother's house. Can you help her?

       

      Input

      The first line contains two integer numbers N and S which respectively indicate the number of clearings and the number of pathways in the woods (3 ≤ N  3 × 104 and  S  105). The clearings are identified by different integer numbers between 1 and N, and are ordered from west to east, so that if  i < j  N then clearing i is to the west of clearing j. Red-Cap's house is in clearing 1, whereas her grandmother's house is in clearing N.

      Each of the following S lines describes a pathway using two integer numbers I and J, which indicate that there is a pathway between clearing I and clearing J ( I < J  N). There is at least one path from Red-Cap's house to her grandmother's house, and the maximum level of alternatives among the set of all such paths is no greater than 1018.

       

      Output

      Print a single line containing an integer number, representing the maximum level of alternatives for a path from Red-Cap's house to her grandmother's house.

       

      Example 1

      Input:
      3 2
      1 2
      2 3
      
      Output:
      3

      Example 2

      Input:
      4 6
      1 2
      2 3
      3 4
      1 2
      2 3
      3 4
      
      Output:
      15

      Example 3

      Input:
      9 9
      1 3
      2 3
      3 4
      4 5
      1 5
      3 4
      3 9
      7 8
      4 9
      
      Output:
      8
      

      Added by:Fidel Schaposnik
      Date:2013-10-07
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2013









      SPOJ Problem Set (classical)

      16278. Watching the game

      Problem code: TAP2013D


      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/tap2013-problems.pdf]

      In the kingdom of Nlogonia there is a lake known as the "Big O" because of its perfectly round shape. On the side of this lake there are N houses, each of them a distance of one nlogonic unit apart from its neighbors. The houses are numbered from 1 to N in clockwise order, as can be seen in the following figure for N = 8.

      TAP2013D

      In this way, if i < j the distance in clockwise order from house i to house j is j-i, whereas the corresponding distance in counterclockwise order is N - j + i. Note that the distance from a house to itself is N in both directions.

      It is well known that the people of Nlogonia are avid football fans, so when a family moves to a house on the side of the lake it is very important for them to know who are their closest neighbors that follow the same team as they do. This is not always easy, since there may be many houses around the lake, many different football teams in Nlogonia, and a lot of moving around. Given a sequence of M movings, people who live on the shore of the lake want to welcome each new family arriving by telling them the distance from their new home to the closest houses that follow the same team as they do, both in clockwise and counterclockwise order. Note that if there is no other house on the shore of the lake whose family follows the same team as the newly arrived, said distance shall be N in both directions, as the closest house would in fact be the same house involved in the moving. Do you want to take part in the welcoming committee?

      In Nlogonia there are F football teams, identified by different integer numbers from 0 to F-1. Because we don't want you to waste any time going from door to door asking which team is followed in each house, we will assume that initially the family living in house number i is a fan of team number ei, being this number generated in pseudo-random fashion by the recursive formula

      e1 = A     and     ei = (B × ei-1 + C) mod F     for     i = 2, 3, ..., N

      where A, B and C are constants and the expression x mod y represents the remainder of the integer division of x by y.

       

      Input

      The first line contains two integer numbers N and F, respectively indicating the number of houses around the lake and the number of football teams in Nlogonia (3 ≤ N  105 and  F  106). The second line contains three integer numbers A, B and C, which determine which team is followed by the families initially living around the lake as is described in the problem statement ( A, B, C < F).

      The third line contains a single integer number M, representing the number of movings that will be happening ( M  105). Each of the following M lines describes a moving using two integer numbers I and E, meaning that a family following team E is moving to house number I ( I  N and  E < F). The movings appear in the order that they occur, and should be taken into account by the committee for further welcomings.

       

      Output

      Print M lines, the i-th of them indicating the result of the i-th moving described in the input. Each line should contain two integer numbers dccw and dcw, representing the distances in nlogonic units from the house involved in the moving to the first house whose family follows the same team, in counterclockwise and clockwise order respectively.

       

      Example

      Input:
      5 10
      1 1 1
      6
      1 1
      2 2
      3 1
      4 2
      5 1
      3 1
      
      Output:
      5 5
      5 5
      2 3
      2 3
      2 1
      2 2
      

      Added by:Fidel Schaposnik
      Date:2013-10-07
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2013









      SPOJ Problem Set (classical)

      16279. Escaping from escaping

      Problem code: TAP2013E


      [Due to SPOJ restrictions, this problem has been modified with respect to the original version used in the Argentinian Programming Tournament of 2013 in order to have multiple test cases per input file. The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/tap2013-problems.pdf]

      A communications protocol is a set of rules designed to transfer information in a communications system. Elisa's job is to write programs that implement parts of said protocols. It is often necessary for this to transfer sequences of fields, and in order to know where a field ends and the next one begins it is customary to insert a separator between each pair of consecutive fields. Using a simple separator such as a space, a comma or a semicolon is inconvenient because sometimes the fields to be transferred contain these same characters. The standard solution in these cases is to insert an "escaping" character just before every appearance of a separator inside a field, so that it can be thus distinguished from a real separator. Elisa thinks this solution will increase a lot the length of the data to be transmitted, so she has decided to use a separator that is complex enough for it to never appear inside the data. In this way she hopes to escape the inefficient alternative of escaping separators.

      To choose the ideal separator, Elisa has compiled a log, which is nothing else than a long string of characters that is representative of the data that her protocol needs to manage. After thinking about the problem for a while, Elisa reached the conclusion that any non-empty string of characters that does not appear inside the log would be an acceptable separator for use within her protocol. But because she is interested in minimizing the length of the data to be transmitted, she would like to know the minimal length that an acceptable separator can have. She immediately wrote a program to calculate this length, and is now testing it for the particular case in which both the log and the acceptable separators only contain binary digits ('0' and '1'). Can you anticipate the results?

       

      Input

      The first line contains an integer number T, the number of test cases (1 ≤ T ≤ 200). Each of the following T lines contains a log, which is a non-empty string of at most 105 binary digits.

       

      Output

      For each test case, print a single line containing an integer number representing the minimal length of an acceptable separator for the given log.

       

      Example

      Input:
      3
      011101001
      100010110011101
      11111
      Output:
      

      3
      4
      1


      Added by:Fidel Schaposnik
      Date:2013-10-07
      Time limit:7s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2013









      SPOJ Problem Set (classical)

      16280. Flowers of Babylon

      Problem code: TAP2013F


      [Due to SPOJ restrictions, this problem has been modified with respect to the original version used in the Argentinian Programming Tournament of 2013 in order to have multiple test cases per input file. The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/tap2013-problems.pdf]

      In Babylon grow some plants with flowers that are very much appreciated among the inhabitants. Florencio is such an inhabitant of Babylon who has a garden with N plants of these species, and he wants to collect some of their flowers. Because Florencio is quite lazy he does not want to go through a lot of effort to collect the flowers. Therefore, he has decided to walk to some point in his garden, and then with a circular movement of his scythe he shall cut a good amount of plants to later collect their flowers. Florencio is very skillful using the scythe so he will cover with it a perfect circle centered wherever he is standing, which will allow him to cut all the plants lying within this circle, including its border. The higher Florencio has to lift his scythe, the greater the radius of the corresponding circle he will cover with it. Florencio wants to cut at least P plants, but his laziness is such that he wants to do so lifting his scythe as little as possible.

      Florencio has managed to get his hands on a satellite image of his garden where all of his plants appear, and he has furthermore managed to get someone to convert this image to a list where each plant is represented by its coordinates in an XY plane. Now he is sitting outside, his scythe in hand, waiting for your team to tell him the minimum radius of a circle that encloses at least P plants.

       

      Input

      The first line contains a single integer number T, the number of test cases (1 ≤ T ≤ 100).

      For each test case, the first line contains two integer numbers N and P, which respectively represent the number of plants that there are in the garden and the minimum number of plants that Florencio wants to cut (1 ≤ P  N  500). Each of the following N lines describes a different plant using two integer numbers X and Y, representing the coordinates of that plant in the XY plane ( X, Y  105). No two plants sit at the same position.

       

      Output

      For each test case, print a line containing a single rational number representing the minimum radius of a circle enclosing at least P plants. You should print the result using exactly 4 digits after the decimal mark, rounding if necessary (there will be no rounding ties).

       

      Example

      Input:
      2
      3 2
      10000 10000
      10000 9999
      9999 10000
      2 1
      1 1
      10000 10000
      Output:
      

      0.5000
      0.0000 


      Added by:Fidel Schaposnik
      Date:2013-10-07
      Time limit:120s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16281. War

      Problem code: TAP2013G


      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/tap2013-problems.pdf]

      War, an event worthy only of appearance in literature, movies or perhaps programming contests, has reached the Nlogonian empire, which is facing the neighboring empire of Quadradonia.

      War protocols agreed upon by both parties indicate that the war will be waged in successive battles, in each of which a different soldier from each empire will face one another, so that each soldier will take part in exactly one battle. The empire that wins more battles will then win the war.

      Each empire has an army formed by S soldiers, and each soldier has a certain combat skill. In each battle between two soldiers, the one with greatest combat skill wins the battle. If both soldiers have the same combat skills, the battle is declared a draw and technically no side claims victory. The spies of Nlogonia have intercepted secret information concerning the combat skill of each soldier of Quadradonia's army, so Nlogonia's queen requires your assistance in order to calculate the maximum number of battles that can be won during the war if her soldiers are sent in the appropriate order.

       

      Input

      The first line contains an integer number S representing the number of soldiers in each army (1 ≤ S  105). The second line contains S integer numbers Qi representing the combat skills of the different soldiers of Quadradonia's army, in the order in which the battles shall take place ( Qi  109 for i = 1, ..., S). The third line contains S integer numbers Ni representing the combat skills of the different soldiers in Nlogonia's army, in an arbitrary order ( Ni  109 for i = 1, ..., S).

       

      Output

      Print a line containing a single integer number representing the maximum number of battles that Nlogonia can win during the war.

       

      Example 1

      Input:
      3
      2 1 1000000000
      1 1 2
      
      Output:
      1

      Example 2

      Input:
      4
      6 3 1 4
      2 7 4 3
      
      Output:
      3
      

      Added by:Fidel Schaposnik
      Date:2013-10-07
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2013









      SPOJ Problem Set (classical)

      16282. Horace and his primes

      Problem code: TAP2013H


      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/tap2013-problems.pdf]

      Horace likes to play writing natural numbers in the blackboard in his bedroom. One of his favourite games consists in first writing a number n, then the sum of all the different prime numbers that divide n, and so on until the number written on the board becomes a prime number. For example, if Horace begins writing the number n = 90, because 90 = 2 × 32 × 5 the next number to be written will be 2 + 3 + 5 = 10; then, as 10 = 2 × 5 Horace will write the number 2 + 5 = 7; finally, because 7 is a prime number the game will end here.

      Formally, in this game each natural number n >= 2 defines a sequence whose first element is n, and each new element is the sum of all the prime numbers that divide the previous element in the sequence. The order of the game is the position of the first prime number in the sequence, and coincides with the total number of numbers written on the blackboard one the game has ended. In the example from the previous paragraph, with n = 90 the order of the game is K = 3, because the numbers that are written will be 90, 10 and 7.
      Now, not all games are equally entertaining to Horace, and in this case he prefers to begin by writing a number n such that the order of the corresponding game is a particular value K. Horace would like to know how many different values of n between A and B inclusive satisfy this condition, but because he does not know how to code he needs someone to do this calculation for him. Can you help him?
      INPUT
      The first line contains an integer P which indicates the number of questions Horace wants to ask you (1 <= P <= 10^5). Each of the next P lines describes a question using three integer numbers A, B and K, which mean that Horace would like to know how many different values of n satisfy that A <= n <= B and the order of the game beggining with n is K (2 <= A <= B <= 10^6 and 1 <= K <= 10^6).
      OUTPUT
      You should print P lines, each one containing an integer number with the answer to one of the questions made by Horace, in the order in which they appear in the input.

      Formally, in this game each natural number n ≥ 2 defines a sequence whose first element is n, and each new element is the sum of all the prime numbers that divide the previous element in the sequence. The order of the game is the position of the first prime number in the sequence, and coincides with the total amount of numbers written on the blackboard once the game has ended. In the example from the previous paragraph, with n = 90 the order of the game is K = 3, because the numbers that are written will be 90, 10 and 7.

      Now, not all games are equally entertaining to Horace, and in this case he prefers to begin by writing a number n such that the order of the corresponding game is a particular value K. Horace would like to know how many different values of n between A and B inclusive satisfy this condition, but because he does not know how to code he needs someone to do this calculation for him. Can you help him?

       

      Input

      The first line contains an integer P which indicates the number of questions Horace wants to ask you ( P ≤ 105). Each of the next P lines describes a question using three integer numbers A, B and K, which mean that Horace would like to know how many different values of n satisfy that  n  B and the order of the game beginning with n is K ( A  B  106 and  K ≤ 106).

       

      Output

      You should print P lines, each one containing an integer number with the answer to one of the questions made by Horace, in the order in which they appear in the input.

       

      Example 1

      Input:
      1
      90 90 3
      
      Output:
      1

      Example 2

      Input:
      5
      2 9 1
      2 9 2
      800 810 4
      999999 1000000 2
      100000 1000000 1000000
      
      Output:
      4
      4
      5
      2
      0

      Added by:Fidel Schaposnik
      Date:2013-10-07
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2013









      SPOJ Problem Set (classical)

      16283. Treasure Island

      Problem code: TAP2013I


      [The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/tap2013-problems.pdf]

      Finding the treasures hidden centuries ago by the pirates of the Caribbean islands is no easy task, but even more difficult is living to tell the story. This is because, as everybody knows, pirates had supernatural powers which they used to curse the person who took their treasure unauthorized.

      A very common curse among the most powerful of pirates, and for which it is always a good idea to be prepared, is known today as the deadly mist. Whenever a pirate's treasure is found, this curse will make a poisonous mist lift from the ground until the whole island gets covered by it. Any living creature that is touched by the mist will die instantly, something especially undesirable for those who have just found a treasure. The only way to save yourself is then to return to your boat, always going through areas that have not yet been covered by the mist, and thus flee with that part of the treasure that may have been rescued. In this problem we are interested in knowing what's the maximum amount of time that one can take to collect the treasure in such a way so as to be able to return to the boat alive.

      To simplify the problem, we will consider that an island can be represented by a grid with R rows and C columns, in which the cell in the i-th row and the j-th column has height Hij above sea level. Furthermore, we will assume that the treasure is always hidden in the cell in row 1 and column 1, because this is the one furthest away from the only place where the boat can set anchor, which is the cell in row R and column C. The deadly mist appears at sea level at the very same instant that the treasure is found, and then rises on all the island at a rate of one unit of height per second, so that after t seconds one cannot be in any cell of height less or equal to t. In order to return to the boat, you may go from one cell to another only if they share a side, so that if you are on a given cell you can only move horizontally to the cell before or after it in the same row, or vertically to the cell before or after it in the same column, but you cannot move diagonally or cross the boundaries of the island. Each such movement from one cell to another takes exactly one second.

       

      Input

      The first line contains two integer numbers R and C, respectively the number of rows and columns of the grid that represents the island, which consists of at least two cells (1 ≤ R, C  500 and R×C ≥ 2). Each of the following R lines contains C values. In the i-th of these R lines, the j-th value is an integer Hij representing the height of the cell at row i and column j (1  Hij  106 for i = 1, ..., R and j = 1, ..., C).

       

      Output

      Print a single line containing an integer number representing the maximum amount of time in seconds that one can take to collect the treasure, so as to be able to return to the boat without being reached by the deadly mist. Print the number -1 if it is impossible to return to the boat even if one starts the way back as soon as the treasure is discovered.

       

      Example 1

      Input:
      
      3 3
      3 3 2 3 4 3 4 5 4 5 6
      Output:
      1

      Example 2

      Input:
      3 3
      1 2 3
      2 2 3
      2 4 5
      
      Output:
      -1

      Example 3

      Input:
      3 2
      1000000 1000000
      1000000 1000000
      1000000 314
      
      Output:
      310 

      Added by:Fidel Schaposnik
      Date:2013-10-07
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2013









      SPOJ Problem Set (classical)

      16284. Game of stones

      Problem code: TAP2013J


      [Due to SPOJ restrictions, this problem has been modified with respect to the original version used in the Argentinian Programming Tournament of 2013 in order to have multiple test cases per input file. The original version of this problem (in Spanish) can be found at http://www.dc.uba.ar/events/icpc/download/problems/tap2013-problems.pdf]

      Jaimito loves to play with the N identical stones that he was given for his birthday, piling them to form mountains of various sizes. His happiness would be perfect if her mother, Jimena, did not constantly remind him that at the end of the day comes the Time to Arrange the Piles (TAP). It is then that Jaimito must destroy his mountains of stones, which he had piled up with so much effort.

      Because Jimena knows how much Jaimito is bothered by the TAP, she suggests to play a game with him in order to make this task more fun. Jaimito and his mother take turns to play, with Jaimito starting because he is the youngest. Initially there are one or more mountains, each one of them composed of a certain number of stones. In his turn each player chooses a mountain with more than one stone and divides it to form two mountains, not necessarily of the same size. The game continues in this way until one of the players cannot make a valid move, at which point this player is declared the looser, the other player being the winner.

      Jaimito is a very smart kid, and he has realized that he can distribute the N stones to form the mountains in a strategic way, so as to be certain that when they begin to play with these mountains he will undoubtedly win during the TAP. Because of the way the game works, Jaimito will not consider that two initial arrangements of the stones are different if they only change in the order in which the mountains are given. This means that in order for him to consider two initial distributions to be different, these need to have a different number of mountains or, if the number of mountains is the same, then the stones must be distributed in a different way among the mountains. For example, if Jaimito has N = 4 stones, there are five ways in which he can initially distribute them in mountains: four mountains of one stone each; two mountains of one stone each, and another mountain with two stones; one mountain of one stone, and another mountain with three stones; two mountains of two stones each; and, lastly, a single mountain with all four stones.

      Because Jaimito does not want his mother to realize that he is cheating, he wants to change the initial distribution of the N stones every day. He is convinced that there are many different ways to initially arrange the stones that will guarantee him the victory, but he does not know how many exactly. For example, in the case with N = 4 stones Jaimito only has two possible ways to choose from: a single mountain with four stones, or two mountains of one stone each and another mountain with two stones. Your team's task in this problem is to help Jaimito count the number of different ways in which he can distribute his N stones in mountains in such a way that his victory is certain when playing against Jimena. In this way, Jaimito will rest assured knowing how many days he can win without his mother doubting of his good intentions.

       

      Input

      The first line contains an integer number T, the number of test cases (1 ≤ T ≤ 200). Each of the following T lines contains an integer number N, representing the number of stones Jaimito has (2 ≤ N  1000).

       

      Output

      For each test case print a line containing a single integer number representing the number of different ways in which the N stones can initially be arranged in mountains so as to guarantee that Jaimito will win the game against Jimena. Because the answer can be a very large number, you only have to print the remainder of its division by 109+7.

       

      Example

      Input:
      2
      4
      239
      Output:
      

      2
      465766207


      Added by:Fidel Schaposnik
      Date:2013-10-07
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2013









      SPOJ Problem Set (classical)

      16297. Sir and The ICC Ratings

      Problem code: ICC


      Everyone knows Sir Jadeja can alone blow the opposition away. Sir has dominated the ICC Rankings as well. One day he was going through his career rating graph on Cricinfo.com and noticed the peaks in the graph. He found these graphs interesting and decides to create many hypothetical graphs. In all his graphs, at any time  the slope of the graph is either 45o (increasing) or -45o (decreasing) only and takes non-negative integral values only. Since the graphs are hypothetical he starts the graph at rating 0 and end it at 0 too. In between the end points the total time covered is 2N (horizontal axis) units and there are a total of K peaks. He wants to calculate the total number of different graphs for a given N and K. Since the answer could be very large, print it modulo 10^9+7. You too are supposed to be good at Maths, so please help Sir solve the problem.

      Input

      First Line denotes the number of test cases T (1<=T<=1000000). Each test case consists of two numbers, N and K.

      1<=K<=N<=1000.

      Output

      Total number of such graphs modulo 1000000007.

      Example

      Input:
      1
      5 2
      
      Output:
      10

      Added by:Aaquib Javed
      Date:2013-10-08
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem used in LiveWire 2k13 MNNIT









      SPOJ Problem Set (classical)

      16300. Playing with isosceles triangle

      Problem code: TRIISO


      Naruto was always alone as a kid. He used to get bored a lot and always tried different things for fun. Once he got facinated by isosceles triangles and developed a game. He will choose a integer value S to be length of the equal sides of the isosceles triangle. Now if it is possible that he can form any triangle which has a third side of even length as well a height of integral value with the third side as base then he becomes happy.
      Given S determine if Naruto will be happy.

      Input

      First line contains T, the number of test cases. (T<=10000)

      The next T lines each contain a integer value S<1000000.

      Output

      For each of T test cases output YES if Naruto will be happy and NO otherwise

      Example

      Input:
      2
      5
      8
      Output:
      YES
      NO
      Explaination:
      In 1st case for S=5, the third side can be 6 and height can be 4.
      In 2nd case for S=8, no such combination is possible.

      Added by:Abhra
      Date:2013-10-09
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16307. Game of stones II

      Problem code: GOSTONES


      [An easier version of this problem was used in the Argentinian Programming Tournament of 2013. You may want to try it before proceeding with this one: http://www.spoj.com/problems/TAP2013J/ ]

      Jaimito loves to play with the N identical stones that he was given for his birthday, piling them to form mountains of various sizes. His happiness would be perfect if her mother, Jimena, did not constantly remind him that at the end of the day comes the Time to Arrange the Piles (TAP). It is then that Jaimito must destroy his mountains of stones, which he had piled up with so much effort.

      Because Jimena knows how much Jaimito is bothered by the TAP, she suggests to play a game with him in order to make this task more fun. Jaimito and his mother take turns to play, with Jaimito starting because he is the youngest. Initially there are one or more mountains, each one of them composed of a certain number of stones. In his turn each player chooses a mountain with more than one stone and divides it to form two mountains, not necessarily of the same size. The game continues in this way until one of the players cannot make a valid move, at which point this player is declared the looser, the other player being the winner.

      Jaimito is a very smart kid, and he has realized that he can distribute the N stones to form the mountains in a strategic way, so as to be certain that when they begin to play with these mountains he will undoubtedly win during the TAP. Because of the way the game works, Jaimito will not consider that two initial arrangements of the stones are different if they only change in the order in which the mountains are given. This means that in order for him to consider two initial distributions to be different, these need to have a different number of mountains or, if the number of mountains is the same, then the stones must be distributed in a different way among the mountains. For example, if Jaimito has N = 4 stones, there are five ways in which he can initially distribute them in mountains: four mountains of one stone each; two mountains of one stone each, and another mountain with two stones; one mountain of one stone, and another mountain with three stones; two mountains of two stones each; and, lastly, a single mountain with all four stones.

      Because Jaimito does not want his mother to realize that he is cheating, he wants to change the initial distribution of the N stones every day. He is convinced that there are many different ways to initially arrange the stones that will guarantee him the victory, but he does not know how many exactly. For example, in the case with N = 4 stones Jaimito only has two possible ways to choose from: a single mountain with four stones, or two mountains of one stone each and another mountain with two stones. Your team's task in this problem is to help Jaimito count the number of different ways in which he can distribute his N stones in mountains in such a way that his victory is certain when playing against Jimena. In this way, Jaimito will rest assured knowing how many days he can win without his mother doubting of his good intentions.

       

      Input

      The first line contains an integer number T, the number of test cases (1  T  104). Each of the following T lines contains an integer number N, representing the number of stones Jaimito has (2 ≤ N ≤ 105).

       

      Output

      For each test case print a line containing a single integer number representing the number of different ways in which the N stones can initially be arranged in mountains so as to guarantee that Jaimito will win the game against Jimena. Because the answer can be a very large number, you only have to print the remainder of its division by 109+7.

       

      Example

      Input:
      2
      4
      12345
      Output:
      

      2
      483042273


      Added by:Fidel Schaposnik
      Date:2013-10-09
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16381. Help Vishnu with his points

      Problem code: RUMMY


      Vishnu is very fond of Rummy. Rummy is a game played with 13 cards, where you have to make sets of atleast three consecutive cards  of the same kind, or exactly three cards of the same number. For simplicity, consider only a single type of cards available. There is a special card called Joker, which can be substituted for any other card in the deck. The cards are denoted from 1,2,3...11,12,13. Where 1,11,12,13 denote A,J,Q and K respectively. Now, 123 is a set, while 467 is not.AKQ is a set while AKJ is not. The set should contain atleast three cards.

      After a game is over, every player shows the sets that he has forned. The cards that do not belong to any set are added for points. Numbers are given the points equal to their value, while A,J,Q and K have 10 points each. Now given a set of 13 cards and the value of joker, find out what is the minimum number of points that Vishnu can reduce it to.

      Input

      First line consists of an integer T denoting the number of test cases. The next T line contains 14 integers each, denoting the set of 13 cards Vishnu has, and the last number denoting the joker of that particular game(Not to be considered as a card in the set).

      1<=T<=20

      Each of the next coming integers <=13

      Output

      For test case, output a single integer, the minimum number of points that Vishnu can reduce the given set of cards to.

      Example

      Input:
      2
      1 2 3 4 5 6 7 8 9 10 11 12 13 3
      1 1 3 3 5 5 7 7 9 11 11 13 13 9
       Output: 0
      60
       

      Added by:aswin murugesh
      Date:2013-10-11
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      16389. Play with Strings

      Problem code: MY02



      All you have to do is implement the following algorithm ,which is a very popular compression technique.

      1.You are given an input string A. (For eg. ababc )

      2.Find all the rotations of A (In this case, it is ababc,babca,abcab,bcaba,cabab)

      • Now sort them (After sorting, we have ababc,abcab,babca,bcaba,cabab)
      • Then arrange them as follows:
      ababc
      abcab
      babca
      bcaba
      cabab
      • Now pick out the last column. It is ‘cbaab’. It is the result of this algorithm
      • Also observe that the 1st row has the original string.(Use 1 indexing)

      Now, for this problem, you are given the output and the row number that has the original string.
      For the above example , it is ‘cbaab’ and 1.
      Given these 2 parameters, you just need to decode it. (ie.,find the original string.)


      Input:


      Each test case has 2 lines.
      1st line – An integer R that represents the row that contains the original string.
      2nd line - A string that represents the output of the above algorithm. (Length of string <=2000) (All characters are lower case).
      The input is terminated with R=-1.

      Output:

      The original string.

      Sample Input:

      1
      cbaab
      3
      mnoag
      -1

      Sample Output:

      ababc
      mango

      Added by:n.7n
      Date:2013-10-11
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Wikipedia









      SPOJ Problem Set (classical)

      16409. Lopov

      Problem code: LOPOV


       

      The difficult economic situation in the country and reductions in government agricultural subsidy 
      funding have caused Mirko to change his career again, this time to a thief. His first professional 
      endeavour is a jewellery store heist. 
      The store contains N pieces of jewellery, and each piece has some mass Mi
       and value Vi
      . Mirko has K 
      bags to store his loot, and each bag can hold some maximum mass Ci
      . He plans to store all his loot in 
      these bags, but at most one jewellery piece in each bag, in order to reduce the likelihood of damage 
      during the escape. 
      Find the maximum total jewellery value that Mirko can “liberate”. 

      The difficult economic situation in the country and reductions in government agricultural subsidy funding have caused Mirko to change his career again, this time to a thief. His first professional endeavour is a jewellery store heist. 

      The store contains N pieces of jewellery, and each piece has some mass Mi and value Vi. Mirko has K bags to store his loot, and each bag can hold some maximum mass Ci. He plans to store all his loot in these bags, but at most one jewellery piece in each bag, in order to reduce the likelihood of damage during the escape. 

      Find the maximum total jewellery value that Mirko can “liberate”. 

       

      Input

      The first line of input contains two numbers, N and K (1 ≤ N, K ≤ 300 000). 

      Each of the following N lines contains a pair of numbers, Mi and Vi (1 ≤ Mi, Vi ≤ 1 000 000).

      Each of the following K lines contains a number, Ci (1 ≤ Ci ≤ 100 000 000). 

      All numbers in the input are positive integers. 

      Output

      The first and only line of output must contain the maximum possible total jewellery value. 

      Example

      Input:
       
      2 1 
      5 10 
      100 100 
      11 
      
      Output:
      10

      Input:
       
      3 2 
      1 65 
      5 23 
      2 99 
      10 
      2 
      
      Output:
      164

      Added by:Tomislav Babic
      Date:2013-10-12
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:COCI 2013 1. round









      SPOJ Problem Set (classical)

      16410. Organizator

      Problem code: ORGNZ


       

      Unexpected problems with law enforcement have convinced Mirko to take up a less lucrative but less 
      morally ambiguous career: he has become the chief organizer of a team computer science contest. 
      There are N CS clubs that wish to participate in the contest. The presidents of the clubs are quite 
      stubborn and will participate in the contest only if the contest team size makes it possible for all club 
      members to participate. 
      The contest consists of two rounds: qualifications and finals. All teams that are competing must have 
      an equal number of members and all members of one team must belong to the same club. Any 
      number of teams from each club can participate in the qualification round, and the best team from 
      each club earns a spot in the finals. 
      Mirko is aware that, with a new and unproven contest, he needs publicity. For that reason, he wants to 
      set the team size such that the number of individual participants in the finals is as large as possible. 
      Remember, each club that participates has a right to one team in the finals. Furthermore, at least two 
      clubs must participate in the contest, otherwise the contest would be too boring to attract sponsors. 
      Determine the maximum possible number of participants in the finals so that Mirko can double check 
      his team size choice. 

      Unexpected problems with law enforcement have convinced Mirko to take up a less lucrative but less morally ambiguous career: he has become the chief organizer of a team computer science contest. There are N CS clubs that wish to participate in the contest. The presidents of the clubs are quite stubborn and will participate in the contest only if the contest team size makes it possible for all club members to participate. 

      The contest consists of two rounds: qualifications and finals. All teams that are competing must have an equal number of members and all members of one team must belong to the same club. Any number of teams from each club can participate in the qualification round, and the best team from each club earns a spot in the finals. 

      Mirko is aware that, with a new and unproven contest, he needs publicity. For that reason, he wants to set the team size such that the number of individual participants in the finals is as large as possible. Remember, each club that participates has a right to one team in the finals. Furthermore, at least two clubs must participate in the contest, otherwise the contest would be too boring to attract sponsors. Determine the maximum possible number of participants in the finals so that Mirko can double check his team size choice. 

       

      Input

      The first line of input contains the positive integer N (2 ≤ N ≤ 200 000), the number of clubs. The second line of input contains N space-separated integers from the interval [1, 2 000 000], the number of members of each club. 

      Output

      The first and only line of output must contain the maximum possible number of finalists.

      Example

      Input:
      3 
      1 2 4 
      
      Output:
      4

      Input:
      2 
      1 5 
      
      Output:
      2
      Input:
      2 
      1 5 
      
      Output:
      2

      Added by:Tomislav Babic
      Date:2013-10-12
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:COCI 2013 1. round









      SPOJ Problem Set (classical)

      16411. Slasticar

      Problem code: SLAST


       

      Organizing CS contests didn't prove very lucrative for Mirko, so he has opened an ice cream and pastry 
      shop. The business was flourishing until, one day, the European Union health inspection decided to 
      pay him a visit. 
      A new directive specifies M banned ingredients which cannot appear in food even in trace amounts. 
      Each ingredient has a serial number consisting of digits 0 through 9. The declaration on each food 
      package lists all the serial numbers of ingredients contained in the respective food item. 
      Mirko must check whether any of his products has a banned ingredient serial number listed on its 
      declaration. However, Mirko, being inept and reckless as always, decided to concatenate all the serial 
      numbers into one long number with length N believing that it will make his job easier. He has 
      borrowed a robot from his friend Slavko. The robot is programmed to check whether a serial number 
      A contains another serial number B as a substring. Let us denote the length of B by L. The robot 
      carries out search as follows: 
      • First, it compares the segment of A from position 1 to position L, digit by digit, with the digits 
      in B. Comparison is stopped when a differing digit is found or when the segments are 
      determined to be equal. If the segments are equal, the search is stopped and the match 
      reported. 
      • If the segments are not equal, the procedure above is repeated with the segment from 2 to L+1. 
      If those segments aren't equal either, the search continues with segments 3 to L+2, 4 to L+3 
      etc. 
      • If the robot doesn't have a sufficient number of digits to obtain a full segment of length L (for 
      example, starting at character 5 in a serial number with length 8, a segment with length 6 is 
      needed), it will pad the number with '#' signs. For example, the segment of "563232" from 
      position 4 to position 10 is "232####". 
      • If the robot reaches the end of the serial number (having tried out all N segments) without 
      having found B, the absence of match is reported. 
      The robot takes one second for each comparison between two digits, and Slavko charges Mirko one 
      dollar per second for using the robot. 
      Help Mirko determine how much money he'll have to pay Slavko for pattern matching! 

      Organizing CS contests didn't prove very lucrative for Mirko, so he has opened an ice cream and pastry shop. The business was flourishing until, one day, the European Union health inspection decided to pay him a visit. A new directive specifies M banned ingredients which cannot appear in food even in trace amounts. Each ingredient has a serial number consisting of digits 0 through 9. The declaration on each food package lists all the serial numbers of ingredients contained in the respective food item. Mirko must check whether any of his products has a banned ingredient serial number listed on its declaration. However, Mirko, being inept and reckless as always, decided to concatenate all the serial numbers into one long number with length N believing that it will make his job easier. He has borrowed a robot from his friend Slavko. The robot is programmed to check whether a serial number A contains another serial number B as a substring. Let us denote the length of B by L. The robot carries out search as follows:

      • First, it compares the segment of A from position 1 to position L, digit by digit, with the digits in B. Comparison is stopped when a differing digit is found or when the segments are determined to be equal. If the segments are equal, the search is stopped and the match reported. 

      • If the segments are not equal, the procedure above is repeated with the segment from 2 to L+1. If those segments aren't equal either, the search continues with segments 3 to L+2, 4 to L+3 etc. 

      • If the robot doesn't have a sufficient number of digits to obtain a full segment of length L (for example, starting at character 5 in a serial number with length 8, a segment with length 6 is needed), it will pad the number with '#' signs. For example, the segment of "563232" from position 4 to position 10 is "232####". 

      • If the robot reaches the end of the serial number (having tried out all N segments) without having found B, the absence of match is reported. 

       

      The robot takes one second for each comparison between two digits, and Slavko charges Mirko one dollar per second for using the robot. Help Mirko determine how much money he'll have to pay Slavko for pattern matching! 

       

      Input

      The first line of input contains the positive integer N (1 ≤ N ≤ 100 000), the length of the long serial 

      number. 

      The second line of input contains N digits from 0 to 9, the long serial number. 

      The third line of input contains the positive integer M (1 ≤ M ≤ 50 000), the number of banned 

      ingeredients. 

      Each of the following M rows contains a single banned serial number, 

      A banned serial number will not exceed 100 000 digits in length. 

      The total length of all banned serial numbers will not exceed 3 000 000 digits. 

      Output

      Output M integers, one per line. Line i must contain the dollar amount that Mirko needs to pay Slavko 

      for the search for ingredient serial number i.

      Example

      Input:
      7 
      1090901 
      4 
      87650 
      0901 
      109 
      090 
      
      Output:
      7 
      10 
      3 
      4 
      

      Input:
      10 
      5821052680 
      4 
      210526 
      2105 
      582 
      105268 
      
      Output:
      8 
      6 
      3 
      9 

      Input:
      3 
      001 
      1 
      11 
      
      Output:
      
      4 

      Added by:Tomislav Babic
      Date:2013-10-12
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:COCI 2013 1. round









      SPOJ Problem Set (classical)

      16420. Even Numbers

      Problem code: EC_CONB


       

      Marina is a college girl who likes to play with all kinds of numbers. One day she was very bored and decided to play around with even numbers.
      She notes N numbers on the board(odd and even numbers) and then, she modifies only even numbers (for some reason she likes the odd numbers) and inverts its binary representation and replaces each even number. But soon she gets bored and ask  you help in order to automate the conversion process.

      Marina is a college girl who likes to play with all kinds of numbers. One day she was very bored and decided to play around with even numbers.

      She writes N numbers on the board (odd and even numbers) and then, she modifies only even numbers (for some reason she likes the odd numbers) and inverts its binary representation (from the left to the right ) and replaces each even number. But soon she gets bored and ask  you help in order to automate the conversion process.

       

      Input

      In the first line contains the value of N. This integer is followed by N lines, every one with a positive integer ai (1 <= ai <= 10^7)

      Output

      The output will contain N lines, the numbers that are on the blackboard after the conversion process

      Example

      Input:
      5
      10
      8
      3
      5
      2
      
      Output:
      5
      1
      3
      5
      1

      Added by:Eddy Cael
      Date:2013-10-12
      Time limit:1s
      Source limit:2000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PYTH 2.7 RUBY









      SPOJ Problem Set (classical)

      16480. Decrypt the message !

      Problem code: DCRYPT


      Krishna loves Radha and wants to propose her in a different way. He wants to tell her the message, but he wanted the message to be a surprise. So, he plans to encrypt the message and send the encrypted message to Radha and he also gives the key to decrypt. He thinks that this might be a surprise to Radha. Help Radha to decrypt the message.

      Rules of encryption :

      0<=key<=51

      The original message only consists of a-z, A-Z, and space.

      Spaces are encrypted as '.'

      If key lies between 0 and 25, then the character is added with the key and modulo is taken and the case is maintained. For eg, if key is 3, then a is decrypted to d and e is decrypted to h.

      If key lies between 26 and 51, then the character is added with the key and modulo is taken and the case is inverted. For eg, if key is 29, then a is decrypted to D and E is decrypted to h.

      Input

      First line consists of t, the number of test cases. (1<=t<=20)

      For each test case, first line consists of key. 0<=key<=51

      Second line consists of the encrypted message S. |S| <= 100000

      Output

      For each test case, display the decrypted message in a separate line.

      Example

      Input:
      1
      2
      dsz.dsf
      Output: fub fuh

      Added by:Pandian
      Date:2013-10-15
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      16482. Make them equal !

      Problem code: MKEQUAL


      You have an array containing n elements. At any move, you choose two indices i and j ( 0 <= i,j <n and i != j ) and increment value at one index and decrement value at other index. You can make this move any number of times. What is the maximum number of elements which can have the same value (after any number of moves) ?

      Input

      First line consists of t, the number of test cases. ( 1<=t<=100)

      t sets follow. Each set contains n, the number of elements in the array, in the first line. (1<=n<=100000)

      Next line of each set consists of n space separated integers ( 0<=value<=100000)

      Output

      Output t lines each containing the required answer.

      Example

      Input:
      1
      4
      1 2 3 4
      Output:  3

      Added by:Pandian
      Date:2013-10-15
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      16483. Lucky Cities

      Problem code: LUCKY


      John has recently arrived in Romania for the South Eastern European Regional competitions. John has never been to Romania before so Romanians decided to organize sightseeing tour for him. This tour will include several Romanian cities and none of them will be visited more than once. John will start in one city and will visit some other cities according to a guide tour. At the end of the tour John will return to the starting point.

      There are N cities numbered from 1 to N and M two-way roads in the country. Each road connects two different cities. Consider a sightseeing tour for John c1,c2,...,cn, where each ci denotes a city in Romania. Then all ci must be distinct, ci and ci+1 must be connected by a road, where i=1,2,...,n-1, cn and c1 must be connected by a road as well. 

      Being a odd person John would like to visit an odd number of cities. The organizers have drawn the plan of all possible tours with an odd number of cities. 

      Residents of the cities would like John to visit them. So if there is at least one tour passing through some city than this city is called lucky. Your task is to calculate the number of lucky cities in Romania.

      Input

      The first line of input contains a single integer T – a number of test cases. Every test case starts with a line containing two integers separated by a single space – N and M. Each of the next M lines will contain two integers ai and bi separated by a single space – the labels of cities that i-th road connects.

      Output

      Output should contain T lines – answers for each of the test cases.

      Constraints

      1 ≤ T ≤ 77, 
      0 ≤ N, M ≤ 100000 (105), 
      1 ≤ ai < bi ≤ N

      Example

      Input:
      
      1 
      7 7 
      1 5 
      3 5 
      3 7 
      1 7 
      6 7 
      4 7 
      4 6
      Output:
      3
      PS: If you like this problem, also see problem BUSINESS

      Added by:acheron
      Date:2013-10-15
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Southeastern European Regional Programming Contest









      SPOJ Problem Set (classical)

      16487. Update the array !

      Problem code: UPDATEIT


      You have an array containing n elements initially all 0. You need to do a number of update operations on it. In each update you specify l, r and val which are the starting index, ending index and value to be added. After each update, you add the 'val' to all elements from index l to r. After 'u' updates are over, there will be q queries each containing an index for which you have to print the element at that index.

      Input

      First line consists of t, the number of test cases. (1<=t<=10)

      Each test case consists of "n u",number of elements in the array and the number of update operations, in the first line (1<=n<=10000 and 1<=u<=100000)

      Then follow u lines each of the format "l r val" (0<=l,r<n 0<=val<=10000)

      Next line contains q, the number of queries. (1<=q<=10000)

      Next q lines contain an index (0<=index<n)

      Output

      For each test case, output the answers to the corresponding queries in separate lines.

      Example

      Input:
      1
      5 3
      0 1 7
      2 4 6
      1 3 2
      3
      0
      3
      4

      Output:
      7
      8
      6

      Added by:Pandian
      Date:2013-10-15
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      16549. Query on a tree VI

      Problem code: QTREE6


      You are given a tree (an acyclic undirected connected graph) with n nodes. The tree nodes are numbered from 1 to n. Each node has a color, white or black. All the nodes are black initially. We will ask you to perform some instructions of the following form:

      • 0 u: ask for how many nodes are connected to u, two nodes are connected if all the node on the path from u to v (inclusive u and v) have the same color.
      • 1 u: toggle the color of u (that is, from black to white, or from white to black).

      Input

      The first line contains a number n that denotes the number of nodes in the tree (1 ≤ n ≤ 105). In each of the following n-1 lines, there will be two numbers (u, v) that describes an edge of the tree (1 ≤ u, vn). The next line contains a number m denoting number of operations we are going to process (1 ≤ m ≤ 105). Each of the following m lines describe an operation (t, u) as we mentioned above(0 ≤ t ≤ 1, 1 ≤ un).

      Output

      For each query operation, output the corresponding result.

      Example

      Input 1:
      5 1 2 1 3 1 4 1 5 3 0 1 1 1 0 1 Output 1:
      5 1

      Input 2:
      7 1 2 1 3 2 4 2 5 3 6 3 7 4 0 1 1 1 0 2 0 3

      Output 2:

      7 3 3


      Warning: large input/output data,be careful with certain languages

       

       


      Added by:xiaodao
      Date:2013-10-17
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, CodeChef December Challenge 2013









      SPOJ Problem Set (partial)

      16554. Linearian Colony

      Problem code: COLONY


      Description

      Linearians are pecurliar creatures. They are odd in several ways:
      1. Every Linearian is either red or blue.
      2. A Linearian colony is a straight line, aligned N-S with the magentic field.
      3. A colony starts with single red Linearian.
      4. Every year, each Linearian produces an offspring of the opposite color. After birth, the parent moves just south of the offspring. (Since everyone is born at once, this does make for a lot of jostling, but everyone stays in order.)
      So a colony grows as follows:
      N ----------- S
      
      Year 0: R
      Year 1: BR
      Year 2: RBBR
      Year 3: BRRBRBBR
      Year 4: RBBRBRRBBRRBRBBR
      Given a year and a position along the N-S axis, determine what the color of the Linearian there will be.

      Input

      The first line is the year Y (0 <= Y <= 51). The second line is the position P from north to south, 0-indexed (0 <= P < 2^Y).

      Ouput

      The color of the Linearian, either red or blue.
      Input Input
      3
      6
      51
      123456789012345
      Output Output
      blue
      red

      Added by:BYU Admin
      Date:2013-10-18
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (partial)

      16556. Triangle

      Problem code: PEGS


      Description

      Consider the following common single-player game.
      A board has fifteen holes, arranged in a triangular pattern. Pegs fit in these holes.
      A valid move is to take a peg and jump in a straight line over an adjacent peg to the an empty hole two positions away from the starting position. The peg that was jumped is removed from the board. The player wins the game when there is only one peg remaining.
      For example, in the game below, the player wins in two moves.
          x             .            .
         x .           . .          . .
        . . .   =>    x . .   =>   . . .
       . x . .       . x . .      . . . .
      . . . . .     . . . . .    . . x . .
      In the game below, the player has no possible moves and loses.
          x
         . .
        x . .
       . . . .
      . . . . .
      
      Given a starting position, determine if it is possible to win.

      Input

      The first line is N, the number of starting pegs (0 < N < 15).
      The next N lines are the pegs' positions. The positions on the board are numbered as following:
              1
            2   3
          4   5   6
        7   8   9  10
      11  12  13  14  15
      
      Input Input Input
      3
      1
      2
      8
      14
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      13
      2
      3
      13
      5
      8
      11
      10
      9
      12
      4
      14
      15
      13
      Output Output Output
      yes
      yes
      no

      Added by:BYU Admin
      Date:2013-10-18
      Time limit:25s-50s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (partial)

      16557. HTML Formatting

      Problem code: FORMAT


      Description

      You have been given formatted text and asked to converted it HTML.
      Each character may be formatted as bold, italic, underlined, or some combination.
      In HTML, content between <b> and </b> tags is bold. Content between <i> and </i> tags is italic. Content between <u> and </u> tags is underlined.
      What is the minimum number of propertly nested HTML tags need to produce a given format?
      For example, say we wanted to format LookAtMe!
      • <b><i>LookAt</b>Me</i>! has incorrectly nested tags.
      • <b><i>LookAt</i></b><i>Me</i>! has correctly nested tags, but is longer than necessary.
      • <i><b>LookAt</b>Me</i>! is the shortest and uses the fewest number of tags.

      Input

      There will be a sequence of 1 to 20,000 numerals. Each numeral denotes the formatting at that position.
      • 0 - no formatting
      • 1 - bold
      • 2 - italic
      • 3 - bold and italic
      • 4 - underlined
      • 5 - bold and underlined
      • 6 - italic and underlined
      • 7 - bold, italic, and underlined
      (There is no need to actually specify the content, since that will not affect the answer.)
      The example earlier would be given as 333333220.

      Output

      The minimum number of <b>, </b>, <i>, </i>, <u>, and </u> tags required.
      Input Input Input Input
      01
      333333220
      
      00110066
      12364012375303657213412303
      Output Output Output Output
      2
      4
      6
      54

      Added by:BYU Admin
      Date:2013-10-18
      Time limit:1s-2.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16580. Query on a tree VII

      Problem code: QTREE7


      You are given a tree (an acyclic undirected connected graph) with n nodes. The tree nodes are numbered from 1 to n. Each node has a color, white or black, and a weight. We will ask you to perfrom some instructions of the following form:

      • 0 u: ask for the maximum weight among the nodes which are connected to u, two nodes are connected if all the node on the path from u to v (inclusive u and v) have a same color.
      • 1 u: toggle the color of u(that is, from black to white, or from white to black).
      • 2 u w: change the weight of u to w.

      Input

      The first line contains a number n denoted how many nodes in the tree(1 ≤ n ≤ 105). The next n-1 lines, each line has two numbers (u, v) describe a edge of the tree(1 ≤ u, v ≤ n). The next 2 lines, each line contains n number, the first line is the initial color of each node(0 or 1), and the second line is the initial weight, let's say Wi, of each node(|Wi| ≤ 109). The next line contains a number m denoted how many operations we are going to process(1 ≤ m ≤ 105). The next m lines, each line describe a operation (t, u) as we mentioned above(0 ≤ t ≤ 2, 1 ≤ un, |w| ≤ 109).

      Output

      For each query operation, output the corresponding result.

      Example

      Input 1:
      5
      5 1 2 1 3 1 4 1 5 0 1 1 1 1 1 2 3 4 5 3 0 1 1 1 0 1
      1 2

      Output 1:
      1 5

      Input 2:
      7 1 2 1 3 2 4 2 5 3 6 3 7 0 0 0 0 0 0 0 1 2 3 4 5 6 7 4 0 1 1 1 0 2 0 3

      Output 2:

      7 5 7


      Warning: large input/output data,be careful with certain languages

       

       


      Added by:xiaodao
      Date:2013-10-18
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, 2013 Multi-University Training Contest 05 - Host by HIT









      SPOJ Problem Set (classical)

      16607. Sweets

      Problem code: IE1


      John has got n jars with candies. Each of the jars contains a different kind of candies (i.e. candies from the same jar are of the same kind, and candies from different jars are of different kinds). The i-th jar contains mi candies. John has decided to eat some of his candies. He would like to eat at least a of them but no more than b. The problem is that John can't decide how many candies and of what kinds he would like to eat. In how many ways can he do it?

      Input

      The first line of input contains three integers: n, a and b, separated by single spaces (1 ≤ n ≤ 10, 0 a b ≤ 10000000). Each of the following n lines contains one integer. Line i+1 contains integer mi - the amount of candies in the i-th jar (0 mi ≤ 1000000).

      Output

      Let k be the number of different ways John can choose the candies to be eaten. The first and only line of output should contain one integer: k mod 2004 (i.e. the remainder of k divided by 2004).

      Example

      Input:
      
      2 1 3
      3
      5
      Output:
      9
      John can choose candies in the following ways: (1,0), (2,0), (3,0), (0,1), (0,2), (0,3), (1,1), (1,2), (2,1)

      Added by:acheron
      Date:2013-10-19
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CEOI 2004









      SPOJ Problem Set (classical)

      16636. Journey

      Problem code: IE2


      In Byteland there are n cities numbered from 1 to n. These cities are connected by a network of m bidirectional roads. It is known that each pair of cities is connected by at most one road.

      Byteman admitted recently that he likes some cities more than others. More precisely, he spends his time especially well in cities with numbers from 1 to k, so during every journey he visits each of them at least once.

      Byteman's journey is a sequence of d cities, such that each pair of consecutive cities is connected by a road. The journey can start and end in any city. Your task is to compute the number of distinct journeys around Byteland that Byteman can make. Because this number might be quite large, it will be enough to find it modulo 109 + 9.

      Input

      The first line of input contains four integers n, m, k  and (1 ≤ n ≤ 20, 1 ≤ k ≤ min(n, 7), 1 ≤ d ≤ 109), separated by single spaces. The following m lines contain descriptions of connections between cities of Byteland. A description of a road consists of two numbers a, bi (1 ≤ a, bi ≤ n, ai ≠ bi), separated by a single space and denoting the numbers of cities connected by the 'th road.

      Output

      The output should contain one integer, denoting the number of distinct journeys that Byteman can make, modulo 109 + 9.

      Example

      Input:
      
      4 4 2 3
      1 2
      2 3
      3 1
      2 4
      Output:
      10

      Added by:acheron
      Date:2013-10-19
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:PA 2008









      SPOJ Problem Set (classical)

      16639. Endless Knight

      Problem code: IE4


      In the game of chess, there is a piece called the knight. A knight is special -- instead of moving in a straight line like other pieces, it jumps in an "L" shape. Specifically, a knight can jump from square (r1, c1) to (r2, c2) if and only if (r1 - r2)2 + (c1 - c2)2 = 5.

      In this problem, one of our knights is going to undertake a chivalrous quest of moving from the top-left corner (the (1, 1) square) to the bottom-right corner (the (HW) square) on a gigantic board. The chessboard is of height H and width W.

      Here are some restrictions you need to know.

      • The knight is so straightforward and ardent that he is only willing to move towards the right and the bottom. In other words, in each step he only moves to a square with a bigger row number and a bigger column number. Note that, this might mean that there is no way to achieve his goal, for example, on a 3 by 10 board.
      • There are R squares on the chessboard that contain rocks with evil power. Your knight may not land on any of such squares, although flying over them during a jump is allowed.

      Your task is to find the number of unique ways for the knight to move from the top-left corner to the bottom-right corner, under the above restrictions. It should be clear that sometimes the answer is huge. You are asked to output the remainder of the answer when divided by 10007, a prime number.

      Input

      Input begins with a line containing a single integer, NN test cases follow.

      The first line of each test case contains 3 integers, HW, and R. The next R lines each contain 2 integers each, r and c, the row and column numbers of one rock. You may assume that (1, 1) and (HW) never contain rocks and that no two rocks are at the same position.

      Output

      For each test case, output a single line of output, prefixed by "Case #X: ", where X is the 1-based case number, followed by a single integer indicating the number of ways of reaching the goal, modulo 10007.

      Limits

      1 ≤ N ≤ 100
      0 ≤ R ≤ 10

      1 ≤ W ≤ 108
      1 ≤ H ≤ 108
      1 ≤ r ≤ H
      1 ≤ c ≤ W

      Example

      Input:
      5
      1 1 0
      4 4 1
      2 1
      3 3 0
      7 10 2
      1 2
      7 1
      4 4 1
      3 2 Output: Case #1: 1
      Case #2: 2
      Case #3: 0
      Case #4: 5
      Case #5: 1

      Added by:acheron
      Date:2013-10-20
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Google Codejam 2008









      SPOJ Problem Set (classical)

      16686. Some Sums

      Problem code: SOMESUMS


      After giving a heartwarming, inspirational speech to the sorority sisters of Delta Gamma at the University of Maryland, Michael Shannon was assaulted on the street by an armed mathematician, who defined a function f as follows:

      f(0,n,k)=n^k \\ f(m,n,k)=\sum_{i=0}^n f(m-1,i,k), m>0

      The mathematician presented Shannon with an ultimatum: You will write a program to calculate this function modulo 10^9+7 for various values of m, n, and k within the given constraints XOR I will shoot you with this gun!

      As the mathematician lay recovering in his hospital bed, a Sigma Nu brother who had witnessed the event gingerly approached him and said, "Professor Martinson, I've written a program to solve your problem, but the online judge on your website keeps telling me the answer is wrong. Please tell me what the problem is. Submission ID 571972597."

      Wearily, Martinson replied, "Have you written a brute force program to verify your program's output for smaller cases?"

      The Sigma Nu brother replied, "Sorry, what did you say? I wasn't listening. Hey, are you going to eat that?" He then took the professor's chocolate pudding and went home to his lovely girlfriend from Zeta to enjoy the rest of the evening.

      Input

      In the first line, an integer T, the number of test cases. Then T lines containing integers m, n, and k separated by spaces.

      Output

      T lines containing the value of f(m,n,k) modulo 10^9+7 for each test case.

      Constraints

      1 ≤ T ≤ 20000
      0 ≤ m ≤ 1000
      0 ≤ n ≤ 10^9
      0 ≤ k ≤ 1000

      Example

      Input:

      5
      0 0 0
      1 100 1
      2 100 0
      2 100 1
      100 100 100

      Output:

      1
      5050
      5151
      171700
      143422859

      Additional Info

      There are two randomly generated data sets, one with T=10000 and the other with T=20000. The distributions are close to uniform random.

      At the time of publication, my C code runs in 0.69s and my Python 2.7 code runs in 24.70s. The Python code is about 1KB, not golfed.


      Added by:Mitch Schwartz
      Date:2013-10-20
      Time limit:20s-30s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Generalisation of ASUMHARD









      SPOJ Problem Set (classical)

      16696. Nadal vs Djokovic

      Problem code: RAFANOLE


      Rafael Nadal vs Novak Djokovic is probably the fiercest rivalry in tennis right now. Now your task is very simple.
      You are given a string containing the scores of a single set(A set consists of many games) between these two stalwarts.
      N denotes Nadal and D denoted Djokovic.
      For those who are new to tennis , have a look of the rules online.
      Anyway small desciption about the rules:

      Now how a player wins a single game?

      In a game scores are incremented as follows:
      15,30,40
      A player wins if scores are like 40-0,40-15,40-30.
      If tied at 40-40., it is called Deuce.
      If N wins next he has an Advantage and if he loses the next volley he comes back to Deuce.
      After Advantage if the player wins the immediate volley he wins that game.

      Simply put the player who wins 6 games first (provided he has won two games more than his opponent) wins the set.
      For eg., 6-1,6-2,6-3,6-4 are all valid.

      If 1 player has won 6 games and the other has won 5 games the match continues.(7-5 is also a valid scoreline)
      If both the players are deadlocked at 6-6, then we have a tiebreaker.
      In the tiebreaker the scores are counted normally (1,2,3,....)
      The person who reaches 7 points first and is atleast 2 more than his opponent wins the set.
      Eg: 7-0,7-1,7-2.....7-5 are valid.
      If the scenario is 7-6 the match proceeds until one of the players scores two points more than the other.
      Eg: Even 10-8 is valid.

      Input:
      1st line - No. of test cases

      Next T lines consist of strings denoting who won a volley.

      Output:

      Winner  Score (tie breaker score if any)

      Loser  Score

      Example:

      Input:
      2
      N N N N N N N N N N N N N N N N N N N N D D D D D D D D N N N N
      D D D D N N N N D D D D N N N N D D D D N N N N D D D D N N N N D D D D N N N N D D D D N N N N D D D D D D N N N N N D

      Output:
      N 6
      D 2

      D 7 (7-5)
      N 6


      Added by:N.7N
      Date:2013-10-21
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      16716. Help Your Commander

      Problem code: HELPCOMM


      A good war commander must take quick decisions, and at the same time be a good strategist. One of the functions of the commander is to delegate soldiers to several strategic points, such that the enemy can be caught surprised and be defeated. There are several strategic points at the battle field, as well as several routes that connect these points.

      Your field is, however, being bombarded, and these routes are not so safe as they were. Once a bomb falls at one route, such terrain becomes irregular and your crossing becomes impossible. To deal with such problem, the commander ordered a new task to some soldiers: find new routes.

      The commander asked your help to calculate the shortest path between the base of operation and the strategic points. You will be informed about the initial state of the battle field, with N strategic points (being the point 1 the base of operation) and M routes. As the bombs falls over some routes, and other routes are found by the soldiers, you must update your math such that your commander can make good use of such informations.

      Good luck, the country depends on you.

      Input

      The input contains several test cases. Each test case begins with two integers, N and M (2 ≤ N ≤ 1000 and 1 ≤ M ≤ 10000), representing, respectively, the number of strategic points and the number of routes that connects two strategic points. After that, there will be M lines, each one with three integers U, V and W (1 ≤ U, VN and 1 ≤ W ≤ 100) each, representing that there is a route that connects the point U to the point V, in unique direction, with distance W.

      There will be, then, an integer Q (1 ≤ Q ≤ 1000), that represents the number of consults or updates that will be done over the routes. At the next Q lines there will be a letter and a determined number of integers.

      If the letter is a R, there will be two integers U and V (1 ≤ U, VN), indicating that the route that used to connect the point U to the point V was bombed.

      In the case that the letter is a I, there will be three integers U, V and W (1 ≤ U, VN and 1 ≤ W ≤ 100), indicating that a new route was found, which connects the point U to the point V, with distance W.

      And in the case that the letter is a P, there will be one integer V (1 ≤ VN), and you must inform to the commander what is the shortest distance between the base of operation and the strategic point V.

      The input ends when N = M = 0.

      Output

      A good war commander must take quick decisions, and at the same time be a good strategist. One of the functions of the commander is to delegate soldiers to several strategic points, such that the enemy can be caught surprised and be defeated. There are several strategic points at the battle field, as well as several routes that connect these points.
      Your field is, however, being bombarded, and these routes are not so safe as they were. Once a bomb falls at one route, such terrain becomes irregular and your crossing becomes impossible. To deal with such problem, the commander ordered a new task to some soldiers: find new routes.
      The commander asked your help to calculate the shortest path between the base of operation and the strategic points. You will be informed about the initial state of the battle field, with N strategic points (being the point 1 the base of operation) and M routes. As the bombs falls over some routes, and other routes are found by the soldiers, you must update your math such that your commander can make good use of such informations.
      Good luck, the country depends on you.

      For each test case there will be a not defined number of output lines. When the commander order to know the shortest distance between the base of operation and a strategic point (letter P), such distance must be print in an unique line. If it is not possible to reach such strategic point, the number -1 must be printed. There must have a blank line after each test case.

      Example

      Input:
      3 3
      1 2 2
      2 3 3
      1 3 4
      5
      P 3
      R 2 3
      P 3
      I 2 3 1
      P 3
      Output:
      4
      4
      3

      Added by:Cristhian Bonilha
      Date:2013-10-22
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      16758. Divisible by 6 and 9

      Problem code: SNGDIV69


      Let num (> 0) be n (> 0) digit(s) positive integer. num is represented as N1N2N3N4.....Nn-2Nn-1Nn , where Ni is the ith digit of num from left (0 < i < n+1). Digits of num are sorted in descending and ascending order respectively and this sorting generates two new positive integers numdsc and numasc. The difference between the numbers is diffnum = numdsc - numasc , if diffnum is divisible by both 6 and 9, then we say that num is a magic number. Let sumdigits is defined as following

      number = diffnum
      do {
      number = sum of digits of number
       
      } while (number > 10)

       sumdigits = number

      Input

      First line of input is t (< 101), total number of test cases. Each test case has n (< 10001) as its first input and next n lines contains num (< 10100). 

      Output

      For each test case, write exactly n lines containing two/three specifications without space :
      (i) Y if num is magic number otherwise N.
      (ii) Let sumdigits = c, ZER if c is 0 (zero), ONE if c is 1 (one) if c > 1, EP if c is even and prime, ENP if c is even but not prime, OP if c is odd and prime or ONP if c is odd but not prime.
      (iii) Let diffnum = d, If num is not a magic number then print EQL if d is not divisible by both 6 and 9, LTN if d is not divisible by 6 only, GTN if d is not divisible by 9 only.

      Example

      Input:
      1
      2
      31
      100
      Output:
      YONP
      NONPLTN
      0 is divisible by 6 and 9 :)

      Added by:Abhimanyu Singh
      Date:2013-10-24
      Time limit:0.5s
      Source limit:1024B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Abhimanyu Singh
      My Problems









      SPOJ Problem Set (classical)

      16776. Modems

      Problem code: EC_MODE


      A Oruro province wants all the towns to have Internet access and to communicate with each other by at least one channel (not necessarily direct). The engineer in charge asks you to help him determine the minimum cost of providing this access.

      There are N towns in total (1 <= N <= 1000). UTP can be used only up to range R (1<=R<=10000). If this distance is exceeded, optical fiber must be used instead. The unit cost of using UTP cable is U and the unit price of the optical fiber is V (U <= V; 1 <= U, V <= 10). There are also W satellite modems purchased (1 <= W < N). These modems can be placed in any town. Modem will allow a town to use the internet and communicate with any other modem in the province.

      Input

      The first line contains the number of test cases. First line of each test case consists of five integers N, R, W, U, V. Then N lines follow, each with integer pair xi, yi (-10000 <= xi, yi <= 10000), the coordinates of i-th town.

      Output

      For each case, print a line of the form:

      Caso #TC: A B

      Where TC is the case number, A is the total cost of using UTP cable and B is the total cost of using optical fiber. Print both A and B rounder to 3 decimal places.

      Example

      Input:
      2
      3 1 1 1 1
      0 0
      0 1
      1 0
      6 1 3 2 3
      0 0
      0 2
      2 0
      3 2
      2 3
      3 3
      
      Output:
      Caso #1: 2.000 0.000
      Caso #2: 4.000 6.000

      Added by:Eddy Cael
      Date:2013-10-25
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 HASK JAVA PAS fpc PYTH 2.7 RUBY
      Resource:Competencia CCBOL 2013









      SPOJ Problem Set (classical)

      16778. Sir and the Guitar

      Problem code: CSHOWB


      After teaching guitar to Jimmy Page (Led Zeppelin Band Guitarist), Sir Jadeja has decided to do something new. As we all know Sir Jadeja has got the special ability to have billons of fingers at the same time. Sir Jadeja took out his guitar and started playing a melody he invented when he was 2 months old.
      The guitar as usual has 6 strings denoted by numbers through 1 to 6. Each string is divided into P frets denoted by numbers 1 to P.
      A melody is a sequence of tones, where each tone is produced by picking a string pressed on a specific fret.(ex. 4th string pressed on 8th fret). If a string is pressed on several frets, the produced tone will be the one corresponding to the highest of those frets.
      For instance, if the 3rd string is already pressed on the 5th fret, and the tone which corresponds to the 7th fret is to be produced, the string can be pressed on the 7th fret and picked without releasing the 5th fret, since only the highest one affects the tone produced (7th in this case). Similarly, if a tone that corresponds to the 2nd fret on the same string is next to be produced, it is necessary to release both 5th and 7th frets.
      Sir Jadeja feeling tired wants to play the melody with minimum number of finger movements.
      Note that press or release a single fret counts as one finger move. String picking does not count as finger move, but rather a guitar pick move.

      Input:
      First line consists of N(N<=500000) and (2<=P<=300000).N denotes number of tones in the melody and P denotes number of frets.
      The next N lines describe the fields for the corresponding tones – the ordinal of the string and the ordinal of the fret, respectively, in the same order as the Sir play them.

      Output:
      Minimum number of finger movements by Sir.
      Sample:
      INPUT:
      5 15
      2 8
      2 10
      2 12
      2 10
      2 5

      OUTPUT:
      7

      Explanation:
      All the tones played are produced by picking the 2nd string . First the frets 8, 10, 12 are pressed in order(three movements), then the 12th fret is released to produce the second tone again (fourth movement), Finally the fifth fret is pressed followed by the release of frets 10 and 12( 5th, 6th and 7th ). Therefore 7.


      Added by:Therapist
      Date:2013-10-25
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:CodeShow IIIT Allahabad









      SPOJ Problem Set (classical)

      16793. Statistics Applied

      Problem code: EC_ESTA


       

      El semestre va culminando y las practicas se acumulan para Isabel, y el ayudante
      de cátedra de la materia de Estadística le ha dado una tarea muy simple, la cual
      consiste en encontrar la mediana de un conjunto de datos (la mediana es el
      elemento central del grupo de datos ordenados), por ejemplo si los datos son
      {2,6,3,3,2} la mediana seria 3. De modo general si tenemos n elementos
      a1,a2,a3…an definimos la mediana como el elemento a(n+1)/2 si n es impar y
      (an/2+an/2+1)/2 en caso contrario.

      The semester is culminating and practices will accumulate to Isabel, and assistant professors in the subject of Statistics has given a very simple task, which is to find the median of a data set (the median is the central element ordered data group), for example if the data are {2,6,3,3,2}the median would be 3. In general if we have n elements a1, a2, a3 ... an,  we define the median such as element  a(n+1)/2 if n is odd and (an/2+an/2+1)/2 otherwise.

      The task was very easy but now she should calculate the median of up to 100000 elements! So in the end its task consisted of the following: It will give she N numbers and she must calculate N medians, each median is taken in the range [a1, a2, a3, .., ai] for 1 <= i <= N.

      She wants to present their work, but do not want to sleep late doing many calculations and she asked for help from you.

       

      Input

      The first line contains the number of test cases, and each case consists of an integer N (1 <= N <= 100000) Then follows a line with N integers  ai (0 <= ai <231) the elements in data list.

      Output

      For each case, print N lines with the required answers.

      Example

      Input:
      2
      4
      3 5 7 3
      2
      3 4
      Output:
      3
      4
      5
      4
      3
      3.5

      Added by:Eddy Cael
      Date:2013-10-26
      Time limit:1s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:COMPETENCIA CCBOL2013









      SPOJ Problem Set (classical)

      16809. Estimation

      Problem code: EST


       

      “There are too many numbers here!” your boss bellows. “How am I supposed to
      make sense of all of this? Pare it down! Estimate!”
      You are disappointed. It took a lot of work to generate those numbers. But, you’ll
      do what your boss asks.
      You decide to estimate in the following way: You have an array A of numbers.
      You will partition it into k contiguous sections, which won’t necessarily be of the
      same size. Then, you’ll use a single number to estimate an entire section. In
      other words, for your array A of size n, you want to create another array B of size
      n, which has k contiguous sections. If i and j are in the same section, then
      B[i]=B[j]. You want to minimize the error, expressed as the sum of the absolute
      values of the differences (∑|A[i]-B[i]|).

      “There are too many numbers here!” your boss bellows. “How am I supposed to make sense of all of this? Pare it down! Estimate!” You are disappointed. It took a lot of work to generate those numbers. But, you’ll do what your boss asks. You decide to estimate in the following way: You have an array A of numbers. You will partition it into k contiguous sections, which won’t necessarily be of the same size. Then, you’ll use a single number to estimate an entire section. In other words, for your array A of size n, you want to create another array B of size n, which has k contiguous sections. If i and j are in the same section, then B[i]=B[j]. You want to minimize the error, expressed as the sum of the absolute values of the differences (∑|A[i]-B[i]|).

       

      Input

      There will be several test cases in the input. Each test case will begin with two integers on a line, n (1≤n≤2,000) and k (1≤k≤25, k≤n), where n is the size of the array, and k is the number of contiguous sections to use in estimation. The array A will be on the next n lines, one integer per line. Each integer element of A will be in the range from -10,000 to 10,000, inclusive. The input will end with a line with two 0s.

      Output

      For each test case, output a single integer on its own line, which is the minimum error you can achieve. Output no extra spaces, and do not separate answers with blank lines. All possible inputs yield answers which will fit in a signed 64-bit integer.

      Example

      Input:
      7 2
      6
      5
      4
      3
      2
      1
      7
      0 0
      
      Output:
      9

      Added by:Bidhan Roy ( বিধান )
      Date:2013-10-27
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      16825. Divisors

      Problem code: EC_DIVS


      Misael is a child learned this year operations with decimal numbers, simplifying fractions, maximum and minimum of a set, well in addition to many other extra things you learn as a child ...

      But Misael is not an ordinary child, he knows programming and he proposed a challenge: He will give you a list of numbers and you must calculate all common divisors the entire list of numbers. The task is simple but Misael offers you something more interesting even ...  The size list is variable, and he can remove numbers as well as he can remove numbers ... However Misael don't like the prime divisors ... So you should not give those numbers as part answer ...

      Input

       

      Pero Misael no es un niño común, él sabe programar y te ha propuesto un reto: Él
      te dará una lista de números y tú debes calcular todos los divisores comunes de
      toda la lista de números. La tarea es simple pero Misael te propone algo más
      interesante aun… Algo que no puedes rechazar… El te dice que la lista de números
      es variable, osea puede quitar números así como también eliminar números… No
      obstante algo que Misael no toma en cuenta (nadie sabe porque…) es a los
      divisores primos… Así que no debes darle esos números como parte respuesta…

      The first line contains the number of test cases, and each case consists of an integer n (1 <= n <= 100000) the number of operations to perform.

      Each operation can be one of 3 types:

      UPD ADD x: Updating the list by adding the element x to the list

      UPD REM x : Update the list by removing the element x from the list

      CON:  print common divisors to the entire list.

      The range of values ​​of x is 1 <= x <10000

       

      Output

      For each type operation CON print a line with common divisors listed in ascending order. If the list become empty print -1.

      Example

      Input:
      1
      6
      UPD ADD 6
      CON
      UPD ADD 12
      CON
      UPD REM 6
      CON
      
      Output:
      1 6
      1 6
      1 4 6 12

      Added by:Eddy Cael
      Date:2013-10-27
      Time limit:1s-1.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Competencia CCBOL 2013









      SPOJ Problem Set (classical)

      16909. Critical Edges

      Problem code: EC_P


      This time I will not bore you with a long and boring sentence. Give a connected graph, you must find all the edges that are critical, in other words you must find the edges which when removed divide the graph.

      Input

       

      The first line contains a NC (1 ≤ NC ≤ 200), the number of test cases integer. Then follow NC test cases.
      Each case begins with two integers N (1 ≤ N ≤ 700) and M (N-1 ≤ M ≤ N * (N-1) / 2), the number of locations and number of roads respectively. Then follow M lines, each with a pair of integers b (1 ≤ a, b ≤ N) indicate that between the city and b there is a way.

      The first line contains a integer NC (1 ≤ NC ≤ 200), the number of test cases. Then follow NC test cases.

      Each case begins with two integers N (1 ≤ N ≤ 700) and M (N-1 ≤ M ≤ N * (N-1) / 2), the number of nodes and the number of edges respectively. Then follow M lines, each with a pair of integers a b (1 ≤ a, b ≤ N) indicate that between the node a and the node b there is a edge.

      Output

      For each test case print the list of ways to protect the following format:

      Caso # <n>

      <t>

      <x1> <y2>

      <x2> <y2>

      ...

      <xt> <yt>

      Where n is the case number (starting from 1), t is the total of critical edges, list elements xi  yi indicates, for each line, there is a critical edge between the node xi and node yi (1 ≤ xi <yi ≤ N). In addition, the list should be sorted in no-decreasing order first by xi and then by yi.

      If there isn't any critical edge print: "Sin bloqueos" (quotes for clarity).

      Example

      Input:
      
      3
      
      5 4
      1 2
      4 2
      2 3
      4 5
      
      5 5
      1 2
      1 3
      3 2
      3 4
      5 4
      
      4 6
      1 3
      1 4
      2 1
      3 2
      4 2
      4 3
      Output:
      Caso #1
      4
      1 2
      2 3
      2 4
      4 5
      Caso #2
      2
      3 4
      4 5
      Caso #3
      Sin bloqueos
      

      Added by:Eddy Cael
      Date:2013-10-31
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA









      SPOJ Problem Set (classical)

      16956. Encoded Coordinates

      Problem code: ENCODE


       

      You have been monitoring a terrorist cell that is planning a big attack somewhere close. The
      terrorists have been sending encoded coordinates to each other, and you suspect that the attack
      will happen at one of the locations described by these coordinates. You have intercepted
      the relevant communications for a series of locations you want to investigate.
      Every location consists of a separate x and y coordinate, each being a non-negative integer
      smaller than some prime number P. Both coordinates are encoded separately using the same
      process. A source has given you information on the process of decoding a single coordinate.
      The input of this process consists of five values: A, B, C, K and N.
      Central to the decoding process is a collection of three functions, defined in terms of each
      other and the input value K:
      F(n + 1) = G(n) + H(n)
      G(n + 1) = K  F(n) + H(n 􀀀 1)
      H(n + 1) = F(n) + K  G(n)
      The values A, B and C are used to initialize these functions as follows:
      F(1) = A G(1) = B H(1) = C
      The decoded coordinate is the value of F(N) mod P.
      As you might have noticed, there is some crucial information missing: you need the value
      of H(0) to calculate G(2). While you do not have this value, you do know that the x and y
      coordinate use the same value for H(0). Luckily, you have managed to already obtain the
      x coordinates for the locations. Your colleagues have suggested that this does not give you
      enough information to calculate the y coordinates, but you want to prove them wrong.

      You have been monitoring a terrorist cell that is planning a big attack somewhere close. The terrorists have been sending encoded coordinates to each other, and you suspect that the attack will happen at one of the locations described by these coordinates. You have intercepted the relevant communications for a series of locations you want to investigate. Every location consists of a separate x and y coordinate, each being a non-negative integer smaller than some prime number P. Both coordinates are encoded separately using the same process. A source has given you information on the process of decoding a single coordinate. The input of this process consists of five values: A, B, C, K and N. Central to the decoding process is a collection of three functions, defined in terms of each other and the input value K:

      F(n + 1) = G(n) + H(n)

      G(n + 1) = K * F(n) + H(n - 1)

      H(n + 1) = F(n) + K * G(n)

      The values A, B and C are used to initialize these functions as follows:

      F(1) = A, G(1) = B, H(1) = C

      The decoded coordinate is the value of F(N) mod P. As you might have noticed, there is some crucial information missing: you need the value of H(0) to calculate G(2). While you do not have this value, you do know that the x and y coordinate use the same value for H(0). Luckily, you have managed to already obtain the x coordinates for the locations. Your colleagues have suggested that this does not give you enough information to calculate the y coordinates, but you want to prove them wrong.

      Input

      On the first line one positive number: the number of test cases, at most 100. After that per test case:

       # one line with the prime number P (2  P  19 997).

       # one line with five space-separated integers Ax, Bx, Cx, Kx and Nx (0  Ax;Bx;Cx;Kx < P and 1  Nx  109): the parameters for the x coordinate.

       # one line with five space-separated integers Ay, By, Cy, Ky and Ny (0  Ay;By;Cy;Ky <P and 1  Ny  109): the parameters for the y coordinate.

       # one line with one integer x (0  x < P): the x coordinate.

      Output

      Per test case:

       # one line with one integer: the calculated y coordinate. If your colleagues are right, and there is not exactly one valid y coordinate, print “UNKNOWN” on a single line instead.

      Example

      Input:
      2
      11
      2 3 5 7 4
      4 6 8 9 7
      5
      7
      1 6 2 5 1
      3 4 2 5 3
      1
      
      Output:
      7
      UNKNOWN
      
      Notice : Extra spaces in output will cause Wrong Answer

      Added by:Bidhan Roy ( বিধান )
      Date:2013-11-03
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:BAPC 2013









      SPOJ Problem Set (classical)

      17110. Black Widow Rings

      Problem code: BWIDOW


      Black Widow has a collection of N(numbered 1 to N) Rings. She uses the rings to attack the enemies. She has decided to use one ring for distraction.She will first throw the distraction ring and then all the other rings will be thrown through it (one at a time). Each ring has an inner and outer radius.
      A ring R1 will pass through ring R2 only if the outer radius of R1 is less than the inner radius of R2.
      If she can chose a distraction ring from the given collection print the index of the ring (1-based), else print -1.

      Input

      The first line of the input contains an integer T denoting the number of test cases.
      The first line of each test case contains a single integer N denoting the number of Rings.
      Next N lines consists of Inner and Outer Radius of the ith Ring - r, R.

      • 1T100
      • 2N1000
      • 1r, R107

       

      Output

      For each test case print the desired result in separate line.

      Example

      Input:
      
      2
      3
      2 3
      6 8
      3 5
      3
      4 5
      5 8
      3 10
      Output:
      2
      -1

      Added by:[bLanK]
      Date:2013-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Code Weavers 2013









      SPOJ Problem Set (classical)

      17112. Training Land of Fury

      Problem code: NFURY


      S.H.I.E.L.D. is recruiting soldiers for the battle with Loki's army. Nick Fury has come to Manhattan to find a large area of land to be used for training purposes. He meets a popular landlord there who is a little foolish by nature.
      He gives square pieces of land with integral sides and charges on the basis of number of pieces of land bought irrespective of how large a piece of land is. Fury has to buy exactly A area of land. In order to minimize the expenditure, Fury has to buy minimum number of pieces of land. Help Fury by determining the minimum number of pieces that should be bought.

      Input

      The first line of the input contains an integer T denoting the number of test cases.
      The first line of each test case contains a single integer A denoting the area that nick fury want to buy.

      • 10T100000
      • 1A1000

       

      Output

      For each test case print the minimum number of pieces that should be bought.

      Example

      Input:
      
      4
      1
      2
      3
      10
      Output:
      1
      2
      3
      2

      Explanation

      For the last test case 10 the answer will be 2 as 10 can be expressed as sum of minimum two squares that is 10 = 32+12 .

      Added by:[bLanK]
      Date:2013-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Code Weavers 2013









      SPOJ Problem Set (classical)

      17113. Finding the Tesserect

      Problem code: TESSER


      Dr. Bruce Banner had estimated a coarse location of Tesseract through gamma radiation emission tracing experiment. It was estimated that Tesseract was hidden somewhere within the Alps mountains. Captain America was given the assignment to look for the Tesseract and bring it back to S.H.I.E.L.D. While roaming through the mountains of Alps, Captain America looked at the height of hills and clicked a panoramic photograph of mountains. This gives an idea of the heights of mountains. Meanwhile Banner was able to determine a continuous pattern of mountains behind which the Tesseract lies and transmitted a message containing the pattern.

      The message is a string consisting of characters 'G' , 'L' and 'E' where G means greater, L means less and E means equal. But this estimation is likely to go wrong due to not considering environmental disturbances that may have arisen in the medium during the experiment.

      Pattern estimate is correct only if one can find a set of consecutive heights out of the given N heights satisfying the message pattern (if G is first character of the message string then second height should be greater than the first height of the selected set and so on) Captain America seeks your help to find out whether the estimation is correct or wrong so that Captain America could proceed his tasks.

      Input

      The first line of the input contains an integer T denoting the number of test cases. Each test case consists of 3 lines. The first line of each test case contains a single integer N denoting the number of hills. Second line of each test case consists of N integers (a_1,a_2....a_n), the heights of hills. Third line contains the message pattern.

      • 1T105
      • 2N105
      • 1a_i109
      • 1Length of Message PatternN-1

      Output

      For each test case print 'YES' if the pattern estimation is correct. Else print 'NO'.

      Example

      Input:
      1
      5
      1 2 3 4 1
      GGL
      
      Output:
      YES

       

      Explanation

      Answer is "YES", because 2 3 4 1 satisfies GGL pattern, i.e. 3 is greater than 2, 4 is greater than 3, 1 is less than 4.


      Added by:[bLanK]
      Date:2013-11-14
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Code Weavers 2013









      SPOJ Problem Set (classical)

      17123. Destroying the Weapon Warehouse

      Problem code: IMBOX


      Iron man is hovering over enemy territories. He comes across their weapons warehouse. The weapons are stored in N rectangular boxes. No two boxes share edges. Boxes may be located inside other boxes but no two boxes will partially overlap each other. Iron man can destroy a box by sending a magnetic pulse with power equal to area of the box (irrespective of the height of the box). This pulse will destroy anything present inside the box. Since Iron man is running low on power, he conveys the 2-D coordinates of all the boxes (as seen from the top view) to Jarvis(artificial intelligence) to calculate the minimum total power of the pulses that will be used to destroy all the boxes. Help Jarvis in determining the total effective area of the weapon warehouse to which the beam needs to be directed to destroy all the boxes.

      Input

      The first line of the input contains an integer N denoting the number of rectangular boxes. N lines follow. Each following line contains 4 integers- x_1, y_1, x_2, y_2 where coordinates (x_1,y_1) and (x_2,y_2) uniquely identify a rectangular box.

      • 1N105
      • -108x_1, y_1, x_2, y_2108

      Output

      Print the total effective area to be destroyed.

      Example

      Input:
      3
      0 0 2 2
      -1 -1 4 4
      5 5 8 8
      
      Output:
      34

      Explanation

      In the given test case, first box lies completely inside the second box so we need not to consider that box in calculating the total effective area. Therefore the answer will simply be the sum of areas of the second and third boxes that is 25+9=34


      Added by:[bLanK]
      Date:2013-11-15
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Code Weavers 2013









      SPOJ Problem Set (classical)

      17124. Chess Board of Avengers

      Problem code: AVCHESS


      The Avengers become divided, both over how to approach Loki and the revelation that S.H.I.E.L.D. plans to harness the Tesseract to develop weapons as a deterrent against hostile extraterrestrials. The argument is raised between Captain America, Iron man and Thor each having his own point to keep. Agent Natasha Romanoff comes up with a non-violent solution to this argument by suggesting a variant of the game of chess for three players. This time chessboard contains only a knight, a rook and a bishop. In this game, first Captain America takes his turn, next Iron Man and then Thor. After Thor's turn, this sequence repeats.

      • Captain America can only move knight, Iron Man rook, and Thor bishop and each player can move their respective piece to an empty position.
      • The rook can move any number of squares horizontally or vertically, but may not leap over other pieces.
      • The bishop can move any number of squares diagonally, but may not leap over other pieces.
      • The knight' move forms an "L"-shape: two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The knight is the only piece that can leap over other pieces.


      The objective of game is to place rook at the initial position of knight, bishop at initial position of rook and knight at initial position of bishop. That is, if the initial position of knight, rook and bishop is (x1, y1), (x2, y2) and (x3, y3), respectively, then the final position of them should be (x3, y3), (x1, y1), (x2, y2) respectively.

      Input

      The first line of the input contains an integer T denoting the number of test cases.
      Each test case consists of exactly one line containing 6 space separated integers x1 y1 x2 y2 x3 y3.
      x1 y1 represents the initial position of Knight.
      x2 y2 represents the initial position of Rook.
      x3 y3 represents the initial position of Bishop.

      • T=5
      • 0x1, y17
      • 0x2, y27
      • 0x3, y37
      • No pair of initial positions are equal, i.e., (x1, y1) != (x2, y2) && (x1, y1) != (x3, y3) && (x2, y2) != (x3, y3)

      Output

      For each test case, print the minimum number of turns required to achieve this objective.

      If the desired configuration is not reachable print -1.

       

      Example

      Input:
      1
      0 0 5 1 3 3 
      
      Output: 
      5
      

      Explanation

      Starting Points of Knight[0,0], Rook[5,1] and Bishop[3,3] can be changed to Knight[3,3], Rook[0,0], Bishop[5,1] in the following five steps:
      Knight - [0,0] to [1,2]
      Rook - [5,1] to [5,0]
      Bishop - [3,3] to [5,1]
      Knight - [1,2] to [3,3]
      Rook - [5,0] to [0,0]

      There is no way to get the required final configuration in less than 5 steps.


      Added by:[bLanK]
      Date:2013-11-15
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Code Weavers 2013









      SPOJ Problem Set (classical)

      17125. Thor vs Frost Giants

      Problem code: TBATTLE


      Thor is caught up in a fierce battle with Loki's army. This army consists of frost giants that have magical powers with them. Their strength levels gets multiplied when they are together. Giants are not highly skilled in the arts of combat, but their sheer size and strength make them formidable opponents even for the Asgardian gods. Thor is no exception. They recover very fast from physical injury but their recovery slows down when they are exposed to extreme heat.
      Thor's hammer can generate heat only in multiples of heat quantum N. Frost giants get killed only when their combined strength level is exactly equal to the heat level of the hammer. Thor is interested in killing a continuous stretch of frost enemies with a throw of his hammer with a preference to kill closer enemies first.
      Continuous stretch is defined as a set of consecutive elements.
      Help Thor to determine the minimum stretch of frost giants that could be killed in a throw. In case of multiple minimal stretches, output the indices of that stretch that has lowest starting index. If there is no such continuous stretch possible then print -1.

      Input

      The first line will contain N, the number of Frost Giants in Loki's army and the Heat quantum.
      The second line will contain N integers (a_0, a_2....., a_n-1) - the strength of each frost giant.
      Minimum stretch of the army should be 1.

      • 1N100000
      • 1a_i100000

      Output

      Output the range of the minimum stretch of frost giants that could be killed in a throw. In case of multiple minimal stretches, output the indices of that stretch that has lowest starting index.
      If there is no such continuous stretch possible then print -1.

      Example

      Input:
      3
      1 2 9
      Output: 
      2 2

      Input:

      5
      2 3 4 8 9 Output:
      -1

      Input:
      10 2 4 3 5 17 4 7 5 2 15
      Output:
      7 8

      Explanation

      Input #1:
      Thor can only kill the stretch [2,2] as this is the minimum length range with strength, multiple of 3.

      Input #2:
      There is no stretch of frost giants that have combined strength as a multiple of 5.

      Input #3:
      There are many stretches of frost giants that have strength as multiple of 10. But the minimal stretch with the least indices is from [7,8]. Minimum size stretches are [7, 8] and [8, 9]. Out of them we select [7,8].


      Added by:[bLanK]
      Date:2013-11-15
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Code Weavers 2013









      SPOJ Problem Set (classical)

      17128. Putnik

      Problem code: PUTNIK


      Chances are that you have probably already heard of the travelling salesman problem. If you have, then you are aware that it is an NP-hard problem because it lacks an efficient solution. Well, this task is an uncommon version of the famous problem! Its uncommonness derives from the fact that this version is, actually, solvable. 


      The travelling salesman is on a mission to visit N cities, each exactly once. The cities are represented by numbers 1, 2, ..., N. What we know is the direct flight duration between each pair of cities. The salesman, being the efficient man that he is, wants to modify the city visiting sequence so that the total flight duration is the minimum possible. 

      Alas, all is not so simple. In addition, the salesman has a peculiar condition regarding the sequence. For each city labeled K must apply: either all cities with labels smaller than K have been visited before the city labeled K or they will all be visited after the city labeled K. In other words, the situation when one of such cities is visited before, and the other after is not allowed. 

      Assist the poor fellow in his ambitious mission and calculate the minimum total flight duration needed in order to travel to all the cities, starting from whichever and ending in whichever city, visiting every city exactly once, so that his peculiar request is fulfilled. 


      Input

      The first line of input contains the positive integer N (2 ≤ N ≤ 1500), the number of cities. Each of the following N lines contains N positive integers from the interval [0, 1000]. The number in Bth place in the Ath row represents the flight duration between cities A and B; that number is equal to the Ath number in the Bth row. When A = B, that number is 0. Otherwise, it is a positive value.


      Output

      The first and only line of output must contain the required minimum total flight duration. 


      Example

      Input:
      3 
      0 5 2 
      5 0 4 
      2 4 0 
      
      Output:
      7
      

      Input:
      4 
      0 15 7 8 
      15 0 16 9 
      7 16 0 12 
      8 9 12 0
      Output:
      31

      Clarification of the first example: 

      the optimal sequence is 2, 1, 3 or 3, 1, 2. The sequence 1, 3, 2 is even more favourable, but it does not fulfill the salesman's condition


      Clarification of the second example: 
      the sequence is either 3, 1, 2, 4 or 4, 2, 1, 3.

      Added by:Tomislav Babic
      Date:2013-11-15
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:COCI 2013 2. round / Adrian Satja Kurdija









      SPOJ Problem Set (tutorial)

      17143. Make Psycho

      Problem code: PSYCHO3


      Problem Statement:

      The number N is called Psycho Number . Psycho Number is calculated as follows:

      First, If we factorize N , then we have some prime and their power. Assume that, there are M powers. From M powers , you should count the number of even and odd powers. Then if the number of even power is strictly greater than odd power , then we call the number N is “Psycho Number”, otherwise the number N is call “Ordinary Number”.

      As for example, if N = 67500 then prime factorization, 

      67500 = 22 x 33 x 54

      Count even powers and odd powers . This number have 2 even power(2,4) and 1 odd power ( 3 ). Since even power 2 (2,4) is greater than odd power 1 (3), so the number 67500 is a Psycho Number.

      Now, Given an integer K, your task is to find whether it is possible to form a subset consisting of only psycho numbers that sum up to exactly K, or not.


      Input:
      The first line of the input contains an integer, T (1 ≤ T ≤ 2000) indicating the number of test cases. For each test case, two lines appear, the first one contains a number N (1 ≤ N ≤ 100), representing the length of the numbers . and K (1 ≤ K ≤ 105). The second line of each test case contains the sequence of integers p1, p2, ..., pn (0 ≤ pi ≤ 1100).  It's mixed with psycho number and ordinary number.
       

      Output:
      For each case print  “Yes” if possible to make K . otherwise “No”.

      Sample Input/Output:

      Sample Input

      Sample Output

        3
        5 20
        4 5 12 20 16
        5 3
        3 5 9 2 7  
        3 24
        4 4 16

       Yes

       No

       Yes

       


      Explanation
      :
      1st test case : psycho numbers :
      4 and 16 .
      possible number: 4, 16 and 20 (4+16).
      k is 20 so you can make this number .
      2nd test case : psycho numbers : only 9
      k is 3 but it's not possible to make subset of psycho numbers which sum is equal to k .
      3rd test case : psycho numbers : 4 4 16
      possible number : 4 , 16 , 20(16+4) and 24 (16+4+4)
      k is 24 so you can make this number .

      Note : 0 and 1 is not a psycho number .
      Psycho 1 : Psycho
      Psycho 2 :
      Psycho Function
       

      Problem setter:   Shipu Ahamed, Dept. of CSE
      Bangladesh University of Business and Technology (BUBT)

      
      

      Added by:Shipu Ahamed
      Date:2013-11-17
      Time limit:0.5s
      Source limit:9000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17247. Digit Sum

      Problem code: PR003004


       

      For a pair of integers a and b, the digit sum of the interval [a,b] is defined as the sum of all digits occurring in all numbers between (and including) a and b. For example, the digit sum of [28, 31] can be calculated as:
                     2+8  +  2+9  +  3+0  +  3+1 = 28
      Given the numbers a and b, calculate the digit sum of [a,b].

      For a pair of integers a and b, the digit sum of the interval [a,b] is defined as the sum of all digits occurring in all numbers between (and including) a and b. For example, the digit sum of [28, 31] can be calculated as:

       

                     2+8  +  2+9  +  3+0  +  3+1 = 28

       

      Given the numbers a and b, calculate the digit sum of [a,b].

       

      Input

      On the first line one positive number: the number of test cases, at most 100.

      After that per test case:

      •  one line with two space-separated integers, a and b (0 <= a <= b <= 10^15).

      Output

      Per test case:

      •  one line with an integer: the digit sum of [a,b];              

      Example

      Input:
      3
      0 10
      28 31
      1234 56789
      
      Output:
      46
      28
      1128600

      Added by:kojak_
      Date:2013-11-25
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:BAPC









      SPOJ Problem Set (classical)

      17258. Yungom

      Problem code: HPREFIX


       

      Yungom  

      After getting her Ph.D in Cooking with her research paper on "How to Prepare a Pizza", and another Ph.D in Medicine for finding cures for H.I.V and Alzheimers, Dae Jang Guem (Called Yungom in Persian) decided to solve yet another open problem in Information Theory that even Shanon (the father of Information Theory) failed to solve. She is going to construct a language of n words with d given characters c1, c2, …, cd. This language should be prefix free which means that there is no pair of words like (s, t) in which the word s is a prefix of t. Each character ci has a usage cost of wi. The cost of a word s with the length l is the sum of the costs of its l characters. For example, if c1=a; c2=b; w1=1 and w2=10, the cost of word "aba" is 1+10+1=12. Similarly, the cost of a language with n words is equal to the sum of the costs of its n words. For example, the cost of language “ab”; “bbb”; “baaa” is 11+30+13=54. Like her previous jobs, Yungom is going to do this task perfectly which means that she wants to find the minimum cost, prefix free language with n words.   

      Input (Standard Input)

      There are multiple test cases in the input. Each test case starts with a line containing two integers n (1 ≤ n ≤ 200) and d (1 ≤ d ≤ 200). The next line contains nonnegative integers w1,w2, …, wd. The input is terminated by a line containing two zero numbers.  

      Output (Standard Output)

      For each test case, you should print the minimum cost of a prefix free language with n words and d characters.

      Sample Input and Output

       

      Standard Input

      3 4

      1 10 100 1000

      0 0

       

      Standard Output

      23   

       Problem D. Yungom  After getting her Ph.D in Cooking with her research paper on "How to Prepare a Pizza", and another Ph.D in Medicine for finding cures for H.I.V and Alzheimers, Dae Jang Guem (Called Yungom in Persian) decided to solve yet another open problem in Information Theory that even Shanon (the father of Information Theory) failed to solve. She is going to construct a language of n words with d given characters c1, c2, …, cd. This language should be prefix free which means that there is no pair of words like (s, t) in which the word s is a prefix of t. Each character ci has a usage cost of wi. The cost of a word s with the length l is the sum of the costs of its l characters. For example, if c1=a; c2=b; w1=1 and w2=10, the cost of word "aba" is 1+10+1=12. Similarly, the cost of a language with n words is equal to the sum of the costs of its n words. For example, the cost of language “ab”; “bbb”; “baaa” is 11+30+13=54. Like her previous jobs, Yungom is going to do this task perfectly which means that she wants to find the minimum cost, prefix free language with n words.   
      Input (Standard Input) There are multiple test cases in the input. Each test case starts with a line containing two integers n (1 ≤ n ≤ 200) and d (1 ≤ d ≤ 200). The next line contains nonnegative integers w1,w2, …, wd. The input is terminated by a line containing two zero numbers.  
      Output (Standard Output) For each test case, you should print the minimum cost of a prefix free language with n words and d characters. Sample Input and Output Standard Input Standard Output 3 4 1 10 100 1000 0 0 23   

       


      Added by:DVH
      Date:2013-11-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACM International Collegiate Programming Contest









      SPOJ Problem Set (classical)

      17261. Bank robbery

      Problem code: BANKROB


       

      The city is plagued with bank robbers, and last year there was a robbery each week in some bank in the city. Police wants to fight this plague, and has to come up with a strategy to solve the problem. One obvious solution would be to place a police patrol at every bank, but this would cost too much money, and because of the crisis it is not possible to choose this solution.

      An alternative solution is as follows. Police is alerted about the robbery right after it happened, and can react pretty fast. Robbers use only either motors or cars. Police is able to block any crossroad in the city, and once a crossroad is blocked it is sure that the robbers will be caught if they try to pass the blockage. Moreover, it is possible to forecast some possible destinations of escape from a given bank. Thus the strategy in this case would be to, immediately after a robbery, block some crossroads to make it impossible to reach an escape destination. It would be also great if the number of blockages would be as small as possible, since then the action is cheaper, more effective, and less troublesome for the citizens.

      Obviously, if we would compute the smallest number of crossroads that make it impossible to pass from a given bank to given escape points, then this information would be actually useless for the police. Because of the geometry of the city, most likely the smallest set of blockages would consist of couple of crossroads right next to the bank, and by the time police would arrive there, the robbers would be already somewhere else. Thus during the chase, police wants to make real-time decisions that depend on the progress of the situation. To make smart decisions police needs an efficient computer program to compute blockages, and it is your task to write this program. Your program has to read the description of the city map and two locations s and t. It has to compute and return one number, the minimum number of blocked crossroads that will make it impossible to go from location s to location t.

      Input

      Your program reads from the standard input. In the first line of input you are given two natural numbers n and m (1 < n <= 1000, 1<= m <= 5000), where n is the number of crossroads in the city, and m is the number of streets, where each street connects two crossroads; any two crossroads can be connected by at most one street. Crossroads are numbered from 1 to n. In the line number 2 of the input you are given two numbers s and t, indicating the crossroads that have to be disconnected. In the next m lines of the input you will be given the description of the connections; each such line consists of two numbers c1, c2 and it means that there is a two-way street connecting crossroads c1 and c2.

      Output

      On the standard output your program has to write one number, the smallest number of crossroads that, when blocked, make it impossible to reach t from s. You may assume that there is no street directly connecting s and t.

      Example 1

      Input:
      10 14
      1 10
      1 2
      1 3
      1 4
      2 5
      3 5
      3 6
      4 6
      5 7
      5 8
      6 8
      6 9
      7 10
      8 10
      9 10 Output: 2

      Example 2

       

      Input: 10 14
      5 10
      1 2
      1 3
      1 4
      2 5
      3 5
      3 6
      4 6
      5 7
      5 8
      6 8
      6 9
      7 10
      8 10
      9 10 Output: 3


      Added by:Marek Adamczyk
      Date:2013-11-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17302. Servers

      Problem code: SERVS


      Suppose we want to replicate a file over a collection of n servers, labeled S1, S2, ..., Sn. To place a copy of the file at server Si results in a placement cost of ci, for an integer ci > 0. Now, if a user requests the file from server Si, and no copy of the file is present at Si, then the servers Si + 1, Si + 2, Si + 3... are searched in order until a copy of the file is finally found, say at server Sj, where j > i. This results in an access cost of ji. (Note that the lower-indexed servers Si−1, Si−2, ... are not consulted in this search.) The access cost is 0 if Si holds a copy of the file. We will require that a copy of the file be placed at server Sn, so that all such searches will terminate, at the latest, at Sn.
      We’d like to place copies of the files at the servers so as to minimize the sum of placement and access costs. Formally, we say that a configuration is a choice, for each server Si with i = 1, 2, ..., n−1, of whether to place a copy of the file at Si or not. (Recall that a copy is always placed at Sn.) The total cost of a configuration is the sum of all placement costs for servers with a copy of the file, plus the sum of all access costs associated with all n servers.
      Write a program which reads from the standard input the placement costs and writes a single number, the minimum cost of a configuration. First line of the input consists of the number n of servers (1 ≤ n ≤ 1000). In the next n lines you are given the placement costs, in line i + 1 you are given the placement cost ci of server Si.
      Example
      For the input:
      4
      1
      1
      1
      9
      the answer is:
      12
      and for the input:
      4
      4
      3
      2
      1
      the answer is:
      6

      Added by:Marek Adamczyk
      Date:2013-11-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17303. Board

      Problem code: BOARD1


      Consider a board with fields numbered from 0 to n. On each field i ∈ {1, ..., n} there is an integer (possibly negative) number ai ∈ ℤ. A player is given a pawn on field number 0. Player can move the pawn back and front on distance not exceeding k. A pawn can visit all the fields many 0 and n many times, but it can stop moving definitively only at position n (player decides on when to stop). Whenever a pawn visits field i, the field is cleared and the number ai is removed (if the field wasn’t clear before the move). A player wants to maximize the sum of numbers on non-cleared fields.

      Write a program that reads on the standard input the description of a game, and writes on standard output the value of an optimal strategy. On the first line of input you are given the number n (1 ≤ n ≤ 1000). On the second line of input you are given the parameter k (1 ≤ k ≤ n). In the next n − 1 lines of the input you are given single integer numbers, where on line i + 2 you are given the number ai. There are no values given for fields 0 and n, because these positions will be always clear at the end of the game.
      Example
      For the input:
      5
      5
      15
      5
      8
      15
      the answer is:
      43
      And for the input
      5
      2
      15
      5
      8
      15
      the answer is:
      30

      Added by:Marek Adamczyk
      Date:2013-11-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17309. Operation Bits

      Problem code: OPBIT


      Operation bits - A new operation conducted by the secret team currently working on a project on security enhancement. Mr.Abay, the team head, has found a new pattern on the perfect squares. This can be used as a outer cover for his project as its securing power is low. So he assign you this problem to find the key based on the given conditions:

      "An two adjacent perfect squares have their absolute difference as an odd number except when a and b are equal. Your task is to find the key which is deined as: 

      key(a,b) where a and b are perfect squares is ( ( AND( absolute difference betwen every adjacent perfect squares in [a,b]) ) AND ( XOR( absolute difference betwen every adjacent perfect squares in [a,b]) ) )"

      Find the key for the given inputs :)

      Input

      The input begins with a number T (1<=T<=1000) where T is the number of testcases.

      T lines follow

      Each line has two numbers a and b (0 < a <= b <= 10^6)

      It is assured that a and b are perfect squares.

      Output

      For each test case print the corresponding key 

      Example

      Input:
      2
      1 4
      25 49
      Output:
      3
      0
      for test case 1 we have key=(3)&(3)=3

      Added by:Benkindersophobia
      Date:2013-11-30
      Time limit:0.100s-0.5s
      Source limit:40000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:My Own









      SPOJ Problem Set (classical)

      17320. Guess The Number With Lies v3

      Problem code: GUESSN3


      GUESSN3

      Judge has chosen an integer x in the range [1, n]. Your task is to find x, using query as described below. But be careful, because the Judge can lie. Judge is allowed to lie only once in single game and only in reply for query.

      Query

      Single query should contains range R = [a, b]. The reply for query is "YES", if a ≤ x ≤ b. Otherwise the reply is "NO".

      1 ≤ a ≤ b ≤ n

      Communication

      You should communicate with Judge using standard input and output.

      Attention: the program should clear the output buffer after printing each line. It can be done using fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution - setlinebuf(stdout).

      The first line of input contains single integer T, the number of games. Then T games follow.

      At the beggining of each game You should send to the Judge a line with command "START_GAME". The Judge will answer You with numbers n, m, where n is as described above and m is the maximum number of queries that You can use in this game.

      Then You should send some queries, every query is a line with "QUERY" keyword, then single-space separated values a b. After each query the Judge will answer "YES" or "NO".

      At the end of game You should give answer: "ANSWER y", where 1 ≤ y ≤ n is the answer for the game. When y ≠ x, the solution will got WA.

      Then start the next game (if there is any).

      Constraints

      1 ≤ T ≤ 210

      2 ≤ n ≤ 1018

      m: This value will be as small as possible. This means, that there exists strategy for player to find the value x using m queries, but there doesn't exist such strategy using m-1 queries.

      Example

      The example of communication. J=Judge, P=Player.

      J: 3

      P: START_GAME
      J: 2 3

      P: QUERY 1 1
      J: YES
      P: QUERY 2 2
      J: YES
      P: QUERY 1 1
      J: NO
      P: ANSWER 2

      P: START_GAME
      J: 2 3

      P: QUERY 1 1
      J: YES
      P: QUERY 2 2
      J: NO
      P: ANSWER 1

      P: START_GAME
      J: 5 6

      P: QUERY 1 3
      J: YES
      P: QUERY 4 5
      J: YES
      P: QUERY 2 4
      J: YES
      P: QUERY 3 4
      J: NO
      P: ANSWER 2

      Explanation:

      In 1st game there is conflicting information in first and second query, so we know, that the last query isn't lie.

      In 2nd game the Judge don't use lie (Judge can lie once, but don't need to do it).

      In 3rd game there is conflicting information in first and second query, so the next queries has correct answers.

      Note

      Be careful. The Judge will try to maximize the number of queries that You will ask. If necessary, the Jugde can also replace chosen value x with the other one. But don't worry too much - at the end of the game, the value x chosen by Judge will satisfy all except at most one of Your queries.

      Similar problems

      There is a family of similar problems. Here is the table with them:

      CodeNumber of liesQuery formatTypeSectionDifficulty
      GUESSN1 1 subset interactive challenge easy
      GUESSN2 2-16 subset interactive challenge medium/hard
      GUESSN3 1 range interactive classical medium
      GUESSN4 1 subset non-interactive challenge medium
      GUESSN5 2-16 subset non-interactive challenge hard

      subset - the query is about any subset of {1,2,...,n}
      range - the query is about any range [a,b]
       interactive - the Judge replies after every query
      non-interactive - all queries have to be asked at once, before any reply


      Added by:miodziu
      Date:2013-12-02
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17382. Airplane Parking

      Problem code: HFLY



      Airplane Parking

      During this economic crisis time, Jack has started an incredible new business related to air travel, a parking-lot for airplane. He bought a very large land to park airplanes. However the land is very narrow, so that the only way airplanes can go in or go out of the parking lot must be in the Last-In First-Out fashion (see picture below). He only has spaces in the parking lot so he cannot take some airplane at the end out so that other airplanes can move.

       

      \epsfbox{p4712.eps}

      Because of the limitation of the parking lot, it is not possible to accommodate all requests for parking. Each request consists of the planned arrival time and planned departure time, which are the times the airplane arrives at the parking lot. An example below shows a request table for 4 planes.

       

       

      Airplane Arrival Departure
      1 1 10
      2 2 5
      3 3 7
      4 6 9

       


      In this case, it is possible to accommodate airplane 1, 2, and 4. But it is not possible to accommodate both airplanes 2 and 3.

      It is possible that different planes plan to arrive or depart the parking lot at the same time. Jack has the best crews working with him, so that they will manage to arrange the plane to the parking lot in the best way that if it is possible to park and take out the planes they will be able to do it. Consider another example.

       

       

      Airplane Arrival Departure
      5 10 12
      6 10 15
      7 13 17

       


      Although airplane 5 and 6 arrive at the same time, Jack's crews know that airplane 5 will have to be out before airplane 6, so when both airplanes arrive they put airplane 6 in first, following by airplane 5.

      Given a list of parking requests, you want to find the maximum number of airplanes that can be parked in this parking lot, provided that they can only depart in the Last-In First-Out fashion.

      Input

      The first line contains an integer T, the number of test cases (1$ \le$T$ \le$5). Each test case is in the following format.

      The first line starts with an integer N (1$ \le$N$ \le$300) denoting the number of airplanes. The next N lines describe the request table. Each line 1 + i, for 1$ \le$i$ \le$N, contains two integer Si and Ti , (0$ \le$Si < Ti$ \le$1, 000, 000, 000) which are the planned arrival time and planned departing time for airplane i.

      Output

       

      For each test case, you program must output a single line consisting of one integer, the maximum number of airplanes that can be parked in Jack's parking lot.

       

      Sample Input

      2

      4

      1 10

      2 5

      3 7

      6 9

      3

      10 12

      10 15

      13 17

      Sample Output

      3

      2


      Added by:DVH
      Date:2013-12-06
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACM Asia - Phuket - 2009/2010









      SPOJ Problem Set (classical)

      17394. Bits Game

      Problem code: DCEPC12B


      Pranjali and Nancy are playing an amazing game. The game starts with a string of bits (i.e. string of 0’s and 1’s). Game progresses in the form of right to left bit by bit scans. Pranjali takes turn when a “1” bit comes while scanning the string and Nancy takes turn when a “0” bit comes while scanning. In their respective turns, they can either choose to toggle their bit or keep it unchanged. The goal is to make all bits 0 at the end of scan, failing which means the scanning starts again from right to left. If all the bits are 0 at the end of a scan, the game ends and Pranjali is declared a winner. There is no win for Nancy. The game either ends to the goal described or the scanning continues indefinitely. So it can be seen that Pranjali has to win the game and in an optimal number of scans whereas Nancy’s aim is to not let Pranjali win (by making it an indefinite play) or to delay Pranjali’s win if it’s sure. So now assuming that they both play with their optimal strategy, can you please tell if Pranjali can win the game or not?

      Note: There has to be AT LEAST 1 scan before the game can end.

      Input

      First line contains T, the number of test cases.

      Each of the next T lines contains a string of 0’s and 1’s.

      Output

      For each string given in the input, output either “WIN m”, without quotes, if Pranjali can force her win in “m” scans in an optimal play, or output “INFINITE PLAY” if the game cannot be reached to the above mentioned goal in an optimal play.

      Constraints

      1<=T<=20

      1<= Length of string <=50

      Example

      Input:
      2
      1
      10
      
      Output:
      WIN 1
      WIN 2

      Explanation

      In the 2nd test case, during the first scan, Nancy gets the first turn because the right most bit is 0. She has to toggle it or the game will be over in a single scan. In the next turn, Pranjali chooses to keep her bit unchanged. So after first scan, the string is now “11”. In the next scan, Nancy has no turns. So Pranjali will toggle both 1 bit and thus end the game.


      Added by:dce coders
      Date:2013-12-07
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      17396. Dazzling Pearls

      Problem code: DCEPC12D


      Nancy and Pranjali are best friends. For her birthday, Pranjali bought a beautiful bracelet for Nancy, made of ‘N’ multi-coloured pearls. Although stunned by the beauty of the pearls and touched by the gesture, Nancy felt that the arrangement of pearls could be changed somewhat, to make the bracelet even more beautiful. After thinking for a long time and making complex calculations, she came up with a formula to calculate the Elegance Factor (E) of the bracelet.

      Starting from a particular pearl, she numbers all the pearls from 0 to N-1. Next, she assigns a numeric value to each distinct colour of the pearls, based on RGB values. Thus the bracelet can be represented by a circular integer array ‘A’ of size N. Also she comes up with another array, ‘B’ also of size N. Now, the Elegance Factor is given by:

      E = sum (i = 1 to n-1) {(A [i] – A [i-1]) * B[i]}

      Obviously, Nancy wants to find an arrangement with the maximum value of E. If there are multiple such arrangements, then she wants the lexicographically smallest one.

      Once she has found the required arrangement, Nancy proceeds to re-arrange the pearls in the bracelet. However, Pranjali does not like the fact that her friend is making so many changes to her gift. To make her task much harder, she gives Nancy a number, D, and tells her that in 1 move, she can interchange the positions of 2 pearls only if they are at a distance D from each other.

      Nancy does not want to upset her friend, but she also wants to finish the rearrangement as fast as possible. Can you help her find the minimum number of moves to finish the re-arrangement? If it is not possible to reach the desired arrangement, output -1.

       

      Note 1: In case of multiple possible arrangements with the maximum elegance factor, the desired one is always the lexicographically smallest one, irrespective of whether it can be reached or not.

      Note 2:  There can be at most 3 distinct colours of the pearls in the bracelet

      Note 3: Remember, the bracelet is circular. The distance D can be in both directions.

      Input

      First line contains T, the number of test cases.

      First line of each test case contains 2 space separated integers, N and D.

      The next line contains N space separated integers representing array A.

      The next line contains N space separated integers representing array B.

      Output

      Output a single integer, the minimum number of moves, or -1 if not possible.

      Example

      Input:
      

      1

      5 1

      2 3 4 2 3

      0 0 0 0 0

      Output: 3
      Explanation:

      For all arrangements, E = 0. Therefore the desired arrangement is the lexicographically 

      smallest one i.e. 2 2 3 3 4.

      The 3 pairs of indices to be exchanged (in order) to achieve this are (0 based indexing):

      (i) 2-3;

      (ii) 3-4;

      (iii) 1-2;

       

      Constraints:

      1 <= T <= 5

      2 <= N <= 14

      1 <= D <= N-1

      1 <= A[i] <= 1000000

      0 <= B[i] <= 1000000


      Added by:dce coders
      Date:2013-12-07
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      17397. End of Fun

      Problem code: DCEPC12E


      Its holiday time after exams and Kappi and Pushap are enjoying to its fullest. But the sadist Sid, their 

      teacher, can’t see them enjoy. Sad isn’t it? To ruin their fun, he gave them a programming problem to be 

      solved within next 5 hours. He gives them 2 square matrices of equal dimension, Matrix A and a Matrix 

      B and asks multiple queries on these matrices. The queries will be to change a particular element of one 

      of the matrix and output the sum of elements of product of their matrix. Sid asks a lot of such queries. 

      Kappi and Pushap don’t want the end of fun and so they ask you to solve this problem on behalf of 

      them.

       

      Input

      First line consists of N, the dimension of matrix.

      Each of the next N lines contains N space separated integers. This is matrix A.

      Each of the next N lines contains N space separated integers. This is matrix B.

      Next line contains Q, the number of queries asked by Sid.

      Each of the next Q lines consists of queries of the form “A i j K” or “B i j K” (quotes for clarity), meaning 

      change the element in ith row and jth column of matrix A or B to value K.

      Output

      Output exactly Q lines corresponding to Q queries, each containing the sum of the elements of the 

      matrix A*B.

      Example

      Input:
      2
      
      1 2
      
      3 4
      
      4 3
      
      2 1
      
      3
      
      A 1 1 2
      
      B 0 1 3
      
      A 0 0 10
      
      Output:
      40
      
      40
      
      103
      
      Constraints:
      
      1<=N<=100
      
      1<=Q<=100000
      
      0<=i,j<N
      
      -10^6 <= A[i][j], B[i][j] <= 10^6
      

      Added by:dce coders
      Date:2013-12-07
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      17398. Fitting in the Team

      Problem code: DCEPC12F


      Aman, Gitanshu and Vishal have recently been selected as admins of DCE Coders. Kapish is pretty happy with the selection, but he wants to make sure that the new admins understand the importance of team-work if they are to take DCE Coders forward in the coming year. Keeping this in mind, he challenges the 3 of them to a game.

      Kapish takes all 3 of them to a long narrow corridor, and gives each of them separate start and end coordinates. The task is simple: All of them have to go from their start coordinates to their respective end coordinates simultaneously (i.e. using the same number of moves). However, they can only move in some discrete steps, which are also given by Kapish. He provides one array (of size ‘N’) of acceptable jumps to each of the 3.  The challenge is that in one move, all 3 of them have to agree upon 1 common index (from 0 to N-1) and then they would add the value corresponding to that index from their respective arrays to get their new coordinates.

      Now Pushap, who likes challenges (such as jumping off moving trains!!), further complicates the problem. If the index selected in the previous move is odd, then it must be even for the current move, and vice versa. They can choose any index for the first move.

      The 3 new admins are required to find the minimum number of moves in which all 3 of them can simultaneously reach their destinations. Can you help them?

      Note 1: You can assume the corridor is 1 dimensional and infinite.

      Note 2: It is possible for more than 1 person to be on the same coordinate at the same time.

      Input

      First line of input contains T the number of test cases

      First line of each test case contains 3 separated integers, A1, G1 and V1, the initial coordinates for the 3.

      Next line contains 3 space separated integers, A2, G2 and V2, the final coordinates for the 3.

      Next line contains a single integer, N.

      Next 3 lines contain N space separated integers each, denoting arrays A, G and V of acceptable jumps for the 3.

      Output

      Output a single integer (in a separate line) per test case, containing the minimum number of moves.

      If it is not possible for them to reach their destinations simultaneously, output -1.

      Example

      Input:
      

      1

      1 2 3

      2 3 5

      2

      1 3

      1 2

      2 1

      Output: 1

      Explanation:

      The 3 of them can choose index 0 in the first move to reach their destinations.

       

      Constraints:

      1 <= T <= 5

      -50 <= A1, A2, G1, G2, V1, V2 <= 50

      1 <= N <= 20

      -10 <= A[i], G[i], V[i] <= 10


      Added by:dce coders
      Date:2013-12-07
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      17399. G Force

      Problem code: DCEPC12G


      Prime(n) is defined as  number of primes less than equal to N.

      Totient(n) is defined as the number of positive integers less than or equal to n that are relatively prime to n.

      F(N) = Prime(n) – Totient(n) 

      and we don’t like negative values, so if F(n) < 0, consider it as 0.

      G(n) = Totient(n) ^ (Factorial (F(N)))

       

      You are given a number N. You have to output G(N) % 10^9+7.

      Input

      First line consists of T, the number of test cases.

      Each of the next T lines contains one integer N.

      Output

      Output T lines each line containing the value of function G(N) % 10^9+7

      Constraints

      1<=T<=100

      1<=N<=10000000

      Example

      Input:
      1
      2
      
      Output:
      1

      Added by:dce coders
      Date:2013-12-07
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      17400. Height of Expectation

      Problem code: DCEPC12H


      Welcome To ICPC! ICPC is a programming competition in which N teams participate every year. Out of N teams, K number of teams has been selected from our college. You know what? K is always a prime number. Coincidence! Before going to ICPC, we want to calculate our expected overall score of our college.

      Expected Overall score is defined as expected median value of our college team’s ranks.

       

      All the ranks are distinct. Team’s rank value always lies between 1 to N.

      Input

      First line consists of T, the number of test cases.

      Each of the next T lines contains 2 space separated integers N and K.

      Output

      Output T lines each line containing expected overall score of our college. You should output at least 6 digits after decimal.

      Constraints

      1<=T<=500

      1<=N<=100

      1<=K<=10

      N>=K

      Example

      Input:
      1
      3 3
      
      Output:
      
      2.0000000

      Added by:dce coders
      Date:2013-12-07
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      17402. Joy of Arbitrage

      Problem code: DCEPC12J


       

      Gitu is the smartest economist in the city. He has been kidnapped by Ankur and Vaibhav. They want him 
      to make profit by Arbitrage. 
      Arbitrage, roughly, is the process of taking advantage of price differences in various economies/markets 
      to earn profit.
      So Ankur and Vaibhav have some units of each of the N valuables items to be sold in exactly N different 
      markets in exchange of some money. Now they want Gitu to sell the items intelligently and maximize 
      the total money earned. However, there is one condition. If Gitu sells some units of a particular item in 
      a particular market, he cannot sell further units of that item in any other market and he cannot sell any 
      other item’s units in this market. 
      Ankur and Vaibhav have allowed Gitu to talk to you and only you. Can you help Gitu to strategize the sell 
      to make maximum earning?

      Gitu is the smartest economist in the city. He has been kidnapped by Ankur and Vaibhav. They want him 

      to make profit by Arbitrage. 

      Arbitrage, roughly, is the process of taking advantage of price differences in various economies/markets 

      to earn profit.

      So Ankur and Vaibhav have some units of each of the N valuables items to be sold in exactly N different 

      markets in exchange of some money. Now they want Gitu to sell the items intelligently and maximize 

      the total money earned. However, there is one condition. If Gitu sells some units of a particular item in 

      a particular market, he cannot sell further units of that item in any other market and he cannot sell any 

      other item’s units in this market. 

      Ankur and Vaibhav have allowed Gitu to talk to you and only you. Can you help Gitu to strategize the sell 

      to make maximum earning?

       

      Input

      First line consists of T, the number of test cases.

      Each test case starts with an integer N, the different items to be sold and the different markets present.

      Next line contains N space separated integers, the units of each of the items Ankur and Vaibhav have.

      Each of the next N lines consists of N space separated integers. jth integer in ith line signifies the money 

      earned after selling one unit of jth item in ith market.

      Output

      Output T lines corresponding to each test case, the maximum money that can be earned by following 

      the process stated above.

      Example

      Input:
      1
      3
      1 2 3
      1 1 1
      2 2 2
      3 3 3
      Output: 14 
      Constraints:
      
      1<=T<=10
      
      1<=N<=40
      
      All other integers in input are positive and not greater than 100.

      Added by:dce coders
      Date:2013-12-07
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict HASK JAVA PAS fpc PAS gpc PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n









      SPOJ Problem Set (classical)

      17406. Cheating a Boolean Tree

      Problem code: GCJ082A


      For this problem we will consider a type of binary tree that we will call a boolean tree. In this tree, every row is completely filled, except possibly the last (deepest) row, and the nodes in the last row are as far to the left as possible. Additionally, every node in the tree will either have 0 or 2 children.

      What makes a boolean tree special is that each node has a boolean value associated with it, 1 or 0. In addition, each interior node has either an "AND" or an "OR" gate associated with it. The value of an "AND" gate node is given by the logical AND of its two children's values. The value of an "OR" gate likewise is given by the logical OR of its two children's values. The value of all of the leaf nodes will be given as input so that the value of all nodes can be calculated up the tree.

      The root of the tree is of particular interest to us. We would really like for the root to have the value V, either 1 or 0. Unfortunately, this may not be the value the root actually has. Luckily for us, we can cheat and change the type of gate for some of the nodes; we can change an AND gate to an OR gate or an OR gate to an AND gate.

      Given a description of a boolean tree and what gates can be changed, find the minimum number of gates that need to be changed to make the value of the root node V. If this is impossible, output "IMPOSSIBLE" (quotes for clarity).

      Input

      The first line of the input file contains the number of cases, N. N test cases follow.

      Each case begins with M and V. M represents the number of nodes in the tree and will be odd to ensure all nodes have 0 or 2 children. V is the desired value for the root node, 0 or 1.

      M lines follow describing each of the tree's nodes. The Xth line will describe node X, starting with node 1 on the first line.

      The first (M−1)/2 lines describe the interior nodes. Each line contains G and C, each being either 0 or 1. If G is 1 then the gate for this node is an AND gate, otherwise it is an OR gate. If C is 1 then the gate for this node is changeable, otherwise it is not. Interior node X has nodes 2X and 2X+1 as children.

      The next (M+1)/2 lines describe the leaf nodes. Each line contains one value I, 0 or 1, the value of the leaf node.

      To help visualize, here is a picture of the tree in the first sample input.




      Output

      For each test case, you should output:

      Case #X: Y

      where X is the number of the test case and Y is the minimum number of gates that must be changed to make the output of the root node V, or "IMPOSSIBLE" (quotes for clarity) if this is impossible.

      Limits

      1 < N ≤ 20

      2 < M < 10000

      Sample


      Input
       

      Output
       
      2
      9 1
      1 0
      1 1
      1 1
      0 0
      1
      0
      1
      0
      1
      5 0
      1 1
      0 0
      1
      1
      0

      Case #1: 1
      Case #2: IMPOSSIBLE

      In case 1, we can change the gate on node 3 to an OR gate to achieve the desired result at the root.
      In case 2, only the root can be changed but changing it to an OR gate does not help.

       

       

       


      Added by:Shafaet
      Date:2013-12-07
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Google Code Jam Round 2, problem A









      SPOJ Problem Set (classical)

      17443. Magical Bus Journey

      Problem code: MABJ


      Townsville has a well developed bus system. Since most of the important buildings in town are located along the Main Street, almost all the buses pass through the street. All the stops along the Main Street, and there are very many of them, are numbered with numbers: 0, 1, 2 and so on. All the buses enter the Main Street at the stop numbered 0 and continue towards the higher numbered stops. For each bus line (which is also identified by a number), there is a schedule posted at stop 0 giving the minutes within an hour when a bus of this line leaves the stop.

      Rahul arrives at stop 0 at m minutes (0 <= m < 60) after the hour and takes the first bus that leaves stop 0 along the Main Street. If Rahul arrives at stop 0 the same minute when a bus leaves, Rahul manages to board the bus. He leaves the bus at the next stop and takes the next bus that arrives and continues to the next stop where he leaves. Rahul continues in this fashion until he reaches stop n, 0 < n < 10^9. Your task is to find by which bus will Rahul arrive at stop n?

      Input

      Input contains multiple cases. The first line of a case gives t, the number of bus lines, 0 < t < 30. The next t lines each contain a number of a bus line followed by a colon and then a list (separated by spaces) of minutes after a full hour when the bus of this line leaves stop 0. Each list of departure times is terminated by -1. No bus leaves stop 0 more than 20 times in an hour, no two buses leave station 0 at the same time, all the buses have the same speed and they never meet at a stop. A line with m and n then follows. The input ends with a line where t = 0. This line should not be processed. 

      Output

      For each case of input, output in a format shown below the number of the bus line by which Rahul arrives at stop n. 

      Example

      Input:
      

      1 11: 10 20 30 -1 3 2 2 11: 10 20 30 -1 134: 16 25 35 45 58 -1 48 783 0

      Output:

      Case 1: Rahul arrives at stop 2 by bus 11. Case 2: Rahul arrives at stop 783 by bus 134.


      Added by:Sourangsu
      Date:2013-12-10
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Stanford Local Programming Contest,2002









      SPOJ Problem Set (main)

      17504. Run length encoding

      Problem code: RLE


      Ram had to send large amount of data to his friend Vishnu. Since he was concerned about the time and the amount of data transfer it will take, he wanted to compress the data before he sent it. So he turns to you for help.

      You need to perform run length encoding on a given string. The encoding is as follows : 'consecutive character count' followed by '!' followed by the 'character'. Do not encode the characters unless they lead to compression !

      Input

      Input consists of multiple lines of strings s, one string per line,  with |s| <= 100000 (read the input till EOF)

      Output

      For each input string, output a single line printing the run length encoding of the input string

      Example

      Input:
      aabbbbbccccc
      aaaabbbbbbbbbbbbbbbccccc Output: aa5!b5!c
      4!a15!b5!c

      Added by:Pandian
      Date:2013-12-14
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      17539. Cows Language

      Problem code: COWWORDS


      Like all bovines, Farmer John's cows speak the peculiar 'Cow'
      language. Like so many languages, each word in this language comprises
      a sequence of upper and lowercase letters (A-Z and a-z).  A word
      is valid if and only if each ordered pair of adjacent letters in
      the word is a valid pair.
      
      Farmer John, ever worried that his cows are plotting against him,
      recently tried to eavesdrop on their conversation. He overheard one
      word before the cows noticed his presence. The Cow language is
      spoken so quickly, and its sounds are so strange, that all that
      Farmer John was able to perceive was the total number of uppercase
      letters, U (1 <= U <= 250) and the total number of lowercase
      letters, L (1 <= L <= 250) in the word.
      
      Farmer John knows all P (1 <= P <= 200) valid ordered pairs of
      adjacent letters.  He wishes to know how many different valid
      words are consistent with his limited data.  However, since
      this number may be very large, he only needs the value modulo
      97654321.
      
      INPUT FORMAT:
      
      * Line 1: Three space-separated integers: U, L and P
      
      * Lines 2..P+1: Two letters (each of which may be uppercase or
              lowercase), representing one valid ordered pair of adjacent
              letters in Cow.
      
      SAMPLE INPUT :
      
      2 2 7
      AB
      ab
      BA
      ba
      Aa
      Bb
      bB
      
      INPUT DETAILS:
      
      The word Farmer John overheard had 2 uppercase and 2 lowercase
      letters.  The valid pairs of adjacent letters are AB, ab, BA, ba,
      Aa, Bb and bB.
      
      OUTPUT FORMAT:
      
      * Line 1: A single integer, the number of valid words consistent with
              Farmer  John's data mod 97654321.
      
      SAMPLE OUTPUT :
      
      7
      
      OUTPUT DETAILS:
      
      The possible words are:
      AabB
      ABba
      abBA
      BAab
      BbBb
      bBAa
      bBbB

      Added by:CQT.Bảo Coder
      Date:2013-12-17
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:USACO 2011









      SPOJ Problem Set (classical)

      17559. Two Game

      Problem code: TWOGAME


      Alice started playing a new simple game.  She starts with the pair of integers (1, 1) and then she may a) duplicate one of the numbers or b) subtract the smaller number from the bigger one.  So the game may proceed as follows:  she starts with (1, 1), then she moves to (2, 1), then to (4, 1), then to (4, 2), then to (8, 2), then to (6, 2), etc.

      She is now wondering if given an arbitrary pair of positive integers (A, B), will she be able to reach at this pair using the proceduce described above ?

      Input

      The first line contains a single positive integer T (T ≤ 500), denoting the number of test cases to solve.  Each test case consists of a single line containing two positive integers A, B (A, B ≤ 1018).

      Output

      For each test case print a single line with the character Y if it is possible for Alice to reach the given pair or N if it is impossible.

      Example

      Input:
      3
      6 2
      5 1
      3 3
      
      Output:
      Y
      
      Y
      N

      Added by:acheron
      Date:2013-12-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      17617. WHAT A CO-ACCIDENT

      Problem code: SYNC13C


       

      Ramesh and Suresh get a box full of five stars on lottery each. Since both the boxes need not have the same number of chocolates, they decide to play a game. The winner gets to have both the boxes of chocolates. They play alternatively and Suresh starts the game.
       
      Given the number of chocolates in both the boxes, let them be c1 and c2, the player takes either c1 or c2 number of chocolates and divide the remaining box of chocolates to two boxes (these two boxes need not have the same number of chocolates). The player who cannot make such a move loses.
      Given the initial number of chocolates (c1 and c2) find the winner.

      Ramesh and Suresh get a box full of five stars on lottery each. Since both the boxes need not have the same number of chocolates, they decide to play a game. The winner gets to have both the boxes of chocolates. They play alternatively and Suresh starts the game.

       

      Given the number of chocolates in both the boxes, let them be c1 and c2, the player takes either c1 or c2 number of chocolates and divide the remaining box of chocolates to two boxes (these two boxes need not have the same number of chocolates). The player who cannot make such a move loses.

      Given the initial number of chocolates (c1 and c2) find the winner.Assume both the players play optimally.

       

      Input

      First line of input contains a number T(1<=T<=1000), the number of test cases. Then follows T lines each containing two space separated integers c1 and c2

      (1<=c1<=c2<=10000).

      Output

      For each test case print "Ramesh" or "Suresh" depending on who is the winner.

      Example

      Input:
      2
      3 1
      4 5
      
      Output:
      
      Ramesh
      Suresh

      Added by:Pandian
      Date:2013-12-19
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17624. Cooperation in geometry !

      Problem code: GCOOP


       

      Aang is fond of geometric figures, especially with equilateral triangles. He likes to know how well equilateral triangles cooperate with other figures. 
      He initially takes an equilateral triangle of side t1. He also takes a square of side a, rectangle of dimensions l and b, another equilateral triangle of side t2 
      and a circle of radius r. He then takes turn and places each figure near the initial equilateral triangle of side t1. While placing nearer, he can place those 
      figures in any orientation, any two edges of the two figures can be along same line but the figures cannot overlap. He now needs to find a cooperation value 
      which is the minimum area of the rectangle needed to surround the area of the two figures. For example, when he places a square near a triangle, the cooperation 
      value is the area of the smallest rectangle which can surround the areas of the triangle and square. Now, given the values, find the cooperation values of all 
      the figures with the initial equilateral triangle.

      Aang is fond of geometric figures, especially with equilateral triangles. He likes to know how well equilateral triangles cooperate with other figures. He initially takes an equilateral triangle of side t1. He also takes a square of side a, rectangle of dimensions l and b, another equilateral triangle of side t2 and a circle of radius r. He then takes turn and places each figure near the initial equilateral triangle of side t1. While placing nearer, he can place those figures in any orientation, any two edges of the two figures can be along same line but the figures cannot overlap. He now needs to find a cooperation value which is the minimum area of the rectangle needed to surround the area of the two figures. For example, when he places a square near a triangle, the cooperation value is the area of the smallest rectangle which can surround the areas of the triangle and square. Now, given the values, find the cooperation values of all the figures with the initial equilateral triangle.

       

      Input

      First line consists of t, the number of test cases (1 <= t <= 20)

      Next t lines consists of 6 values t1, a, l, b, t2 and r denoting side of first triangle, side of square, length and breadth of rectangle, side of second triangle and radius of circle. (all values will lie between 1 and 100 inclusive)

      Output

      For each test case, print a single line consisting of the cooperation values of the first triangle with the square, rectangle, circle and the other triangle respectively. (separated by spaces rounded off to 4 decimal digits)

      Example

      Input:
      1
      2 2 2 3 2 1
      
      Output:
      7.4641 9.4641 7.4641 5.1962

      Added by:Pandian
      Date:2013-12-19
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      17626. Eat all the brownies !

      Problem code: CUTCAKE


       

      PROBLEM:
      BrownieDude was given the job of cutting cake at a party for serving the guests. But BrownieDude is both lazy and hungry, so he wants to cut the cake into maximum number of pieces with minimum number of cuts and go off to eating brownies. 
      The host of the party says that BrownieDude can cut the cake into unequal pieces but cannot cut in more than one plane.(Only vertical cuts are allowed.) Given the number of guests, find the number of cuts sufficient to generate the cake pieces.
      Input:
      First line contains 't', the number of test cases. 't' lines follow.
      Each line denotes the number of guests.
      Output:
      One number denoting the number of cuts.
      Note: It is guaranteed that an integer solution will always exist.
      Example Input:
      2
      1
      2
      Example Output:
      0
      1
      Explanation for test cases: If there is only one guest, there is no need to cut the cake. If there are 2 guests, the cake can be cut into 2 pieces in 1 cut.

      BrownieDude was given the job of cutting cake at a party for serving the guests. But BrownieDude is both lazy and hungry, so he wants to cut the cake into maximum number of pieces with minimum number of cuts and go off to eating brownies. 

      The host of the party says that BrownieDude can cut the cake into unequal pieces but cannot cut in more than one plane.(Only vertical cuts are allowed.) Given the number of guests, find the number of cuts sufficient to generate the cake pieces.

      Input

      First line contains 't', the number of test cases. 't' lines follow. (1 <= t <= 1000)

      Each line denotes the number of guests. (1 <= n <= 10^11)

      Output

      One number denoting the number of cuts.

       

      Note: It is guaranteed that an integer solution will always exist.

       

      Example Input:

      2

      1

      2

       

      Example Output:

      0

      1

       

      Explanation for test cases: If there is only one guest, there is no need to cut the cake. If there are 2 guests, the cake can be cut into 2 pieces in 1 cut.

       

       

       


      Added by:Pandian
      Date:2013-12-19
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      17627. Family members

      Problem code: FAMWEALT


      Consider a family in the form of a binary tree consisting of male and female nodes. All the left nodes will be male nodes and all the right nodes will be female nodes.

      Root node will be female node. The root female initially has a wealth w which she passes on down the tree. The rules are as follows :

      a) all the males in the family pass half of their wealth to each of their children.

      b) all the female nodes pass only half of their wealth to both their children collectively, but the male child suddenly converts it to twice the wealth received.

      The members are numbered from 1 to n in the row-wise order. ie, root will be 1, it's two children will be 2 and 3 and so on. 

      Given wealth W of xth node, you need to find the wealth of yth node.

       

      Input :

      First line consists of t, the number of test cases(1 <= t <= 20)

      Each of t lines consists of three values x, y and W (1 <= x, y <= 10^6 and 1 <= W <= 1000)

       

      Output :

      For each input test case, print the wealth of yth node in a single line (rounded off to six decimal digits)

       

      Example :

      input :

      2

      11 3 1

      4 6 4

       

      output:

      4.000000

      2.000000

       

      Consider a family in the form of a binary tree consisting of male and female nodes. All the left nodes will be male nodes and all the right nodes will be female nodes.
      Root node will be female node. The root female initially has a wealth w which she passes on down the tree. The rules are as follows :
      a) all the males in the family pass half of their wealth to each of their children.
      b) all the female nodes pass only half of their wealth to both their children collectively, but the male child suddenly converts it to twice the wealth received.
      The members are numbered from 1 to n in the row-wise order. ie, root will be 1, it's two children will be 2 and 3 and so on. 
      Given wealth W of xth node, you need to find the wealth of yth node.
      Input :
      First line consists of t, the number of test cases(1 <= t <= 20)
      Each of t lines consists of three values x, y and W
      Output :
      For each input test case, print the wealth of yth node in a single line.
      Example :
      input :
      11 3 1
      4 6 4
      output:
      4
      2

      Added by:Pandian
      Date:2013-12-19
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17660. The Bridge to Home

      Problem code: WAYHOME


      Late in the night, a group of people are approaching home after an exciting adventure in the wilderness. However, as a last challenge on their long and tiresome fare, they have to cross a small bridge over a raging river.

      The bridge is so narrow and slippery that the group decides only to let a maximum of two people walk on it at any given time. Also, the person or pair who is walking on the bridge, must carry the single light that the group possesses.

      The group asks you to determine, given the amounts of time that each person takes to cross the bridge, the minimum total amount of time it'll take the entire group to cross. Notice that, when two people walk on the bridge at the same time, their crossing time is determined by the slower walker.

      Input

      First line: The number of testcases C.

      Next C lines: The number of people in the group N, followed by N sorted integers Ai.

      0 ≤ C ≤ 100; 1 ≤ N ≤ 1000; 0 ≤ Ai ≤ 1000.

      Output

      For each testcase, write the minimum total amount of time it'll take the group to pass.

      Example

      Input:
      4
      1 1
      2 1 2
      3 1 1 1
      4 1 2 4 8
      Output:
      1
      2
      3
      15
      

      In the third test case, the people can cross the bridge in the following way:

      1. The first two people walk over the bridge, taking 1 time unit.
      2. One person walks back over the bridge, with the light, taking 1 time unit.
      3. The two people, now on the left, cross the bridge, taking 1 time unit.

       


      Added by:Thomas Dybdahl Ahle
      Date:2013-12-21
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17705. Gopu and Combinatorics on Graphs

      Problem code: SPCE


      Little Gopu was playing with graphs. He encoutered following problem while playing.

      Given a graph G with n vertices and m edges. Let us say it has k connected components. Find out how many numbers of ways you can add k - 1 edges to make the graph connected. Note that the new edge you are going to add should not be a repeated edge ie. if you are going to connect u, v then there should not be an edge between u, v already in the graph. Output the answer modulo 10^9 + 7.

      If the graph is already connected, Output -1

      Help Gopu with this task.

      Input

      First line contains T : number of test cases. (1 <= T <= 20)

      For each test case, First line contains two space seperated integers n, m: (1 <= n, m <= 10^5).

      Then For each of the next m lines, each line contains two space seperated integers u and v denoting that u and v are connected to each other. (1 <= u, v <= n and u != v)  

      Output

      For each test case, output the answer as required.

      Example

      Input:
      4
      4 2
      1 2
      3 4
      5 3
      1 2
      3 4
      4 5
      3 3
      1 2
      2 3
      3 1
      7 5
      1 2
      3 4
      4 5
      3 5
      6 7 
      Output:
      4
      6
      -1
      84

      Added by:praveen123
      Date:2013-12-23
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      17707. Constructible Regular Polygons

      Problem code: POLCONST


      The investigation of which regular polygons can be constructed only with compass and straightedge is a classical problem in mathematics. Triangle, square, hexagon can easily be constructed, but, can we construct a regular heptagon? It was the German mathematician Gauss (1777-1855) who first proved that one could construct a 17-sided regular polygon and later, in one the of the most beautiful math works of all time (Disquisitiones Arithmeticae, 1798), he gave sufficient conditions to decide which regular polygons can be constructed.

      Input
      In the first line, an integer T<50000 representing the number of test cases; then, T integer numbers representing the number of sides of a non-degenerated regular polygon, up to 1000000 (10^6).

      Output
      Print “Yes” if the regular polygon can be constructed with compass and straightedge or “No” otherwise.

      Example

      Input
      5
      5
      6
      7
      8
      9

      Output
      Yes
      Yes
      No
      Yes
      No

      If you have any question, you can ask in the forum.


      Added by:Alexandre Henrique Afonso Campos
      Date:2013-12-23
      Time limit:1s-2s
      Source limit:1000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Classical math.









      SPOJ Problem Set (classical)

      17711. Gopu and Create Collections Part Two

      Problem code: SPCJ


      Little Gopu likes to play very much. As you know he only plays with numbers. So he is given n numbers. Now he tries to group the numbers into collections where each collection contains exactly two numbers. He can form the collection of two numbers a and b (a <= b), if and only if b is either 2 * a or 2 * a + 1.

      Note that you can not use a single number in forming of more than one collections. Eg. 1, 2, 4 He can divide the numbers into a single collection only either [1, 2] or [2, 4] because each collection requires exactly two numbers, and each number has to be used only once in a group.

      Given n numbers, Find out how many maximum number of collections he can form ?

      Input

      T: number of test cases.

      For each test case, First line will contain n :  (1 <= n <= 10^5)

      Then next line will contain n numbers single space seperated. Range of each number will be between 1 and 10^18.

      Sum of n over all the tests will be atmost 10^6. So number of test cases are decided on this criteria.

      Output

      For each test case, output maximum number of collections that can be formed.

      Example

      Input:
      4
      2
      1 2
      3
      1 2 4
      4
      1 2 4 8
      2
      4 4 
      Output:
      1
      1
      2

      Added by:praveen123
      Date:2013-12-23
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      17714. Gopu and function

      Problem code: SPCM


      Once Gopu was reading a maths problem which had a weird looking function f as follows.

                      {
                               1, if n is a prime number.
      f(n)  =                f (sum of prime divisors of n) + number of distinct prime divisors of n,  otherwise.
                      }

      Compute f (n) for a given value of n. 

      Input

      First line contains T : number of test cases. (1 <= T <= 20)

      For each test case, there is a single line containing integer n. (2 <= n <= 10^12).

      Output

      For each test case, output value of f (n) in a single line.

      Example

      Input:
      6
      2
      3
      4
      5
      20
      123456 
      Output:
      1
      1
      2
      1
      3
      6

      Added by:praveen123
      Date:2013-12-23
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      17717. Gopu and Counting Bitwise Prime Numbers

      Problem code: SPCO


       

      A positive integer is said to be Bit-sum-prime if the sum of all the bits in
      its binary representation is a prime number

      A positive integer is said to be bitwise prime if the sum of all the bits in its binary representation is a prime number. 

      You are given two integers a and b. You have to output number of bitwise prime numbers between a and b (inclusive).

       

      Input

      First line contains T : number of test cases. (1 <= T <= 10^5)

      For next T lines, each test case contains two space seperated integers a and b. (a <= b). 1 <= a, b <= 10^19.

      Output

      For each test case, print the number of bitwise prime numbers between a and b (inclusive).

       

      Example

      Input:
      2
      1 2
      1 3 Output: 0

      Added by:praveen123
      Date:2013-12-23
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      17725. Bad XOR

      Problem code: BADXOR


      Bad XOR | BADXOR

      Time Limit: 1s

      You are given an array A of N elements. Also you are given another array B of M elements. Any subset (i­1, i2, i3, …., ip ) is bad IFF ( Ai1 ⊕ Ai2 ⊕ …. ⊕ Aip ) equals any value of B. ⊕ means Bitwise XOR, which can be found with ^ syntax in popular programming languages. Now your job is to find the number of good subsets. Empty Subset has XOR value of 0.

       

      Input

      The first line of input denotes the number of test cases T (1 <= T <= 20). The first line of each test case contains two integers N and M ( 0 <= N, M <= 1000). The next line contains N integers of the array A (0 <= Ai <=1000). The next line contains M integers of the array B (0 <= Bi <=1000). You can assume that each element of array B will be unique.  

       

      Output

      For each case, print the case number and the total numbers of good subsets in a line. As the result can be very big, output it modulo 100000007.

       

                                      Sample Input

      Output for Sample Input

      2

      2 3

      1 2

      0 1 2

      1 3

      1

      0 1 2

      Case 1: 1

      Case 2: 0

       

       

       Problem Setter: Nafis Sadique

      Special Thanks: Ahmad Faiyaz


      Added by:Ahmad Faiyaz
      Date:2013-12-24
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17730. Maximum Radius

      Problem code: MAXRAD


      Maximum Radius | MAXRAD

      Time Limit: 2 seconds

      You will be given some 2D points. You need to draw circles with each point considering as a center of a circle with minimum radius 1. And no two drawn circles should intersect with each other or contain each other. Now you have to find the maximum radius any circle can have so that all the circles have radius greater or equal to 1 and no two circles intersect with each other or contain each other. You have to print the maximum radius. If it is not possible to maintain the restriction for any radius, then you should print -1.000000.

      Input

      Input starts with an integer T (≤ 50), denoting the number of test cases.

      Each case starts with a line containing an integer N (2 ≤ N ≤ 1000) denoting the number of 2D points. Each of the next N lines contains two integers xi yi (-104 ≤ xi, yi ≤ 104) denoting the co-ordinate of a point. These points may not be distinct.

      Output

      For each case, print the maximum radius a circle can have. If it is not possible to maintain the restriction then you should print -1.000000. Errors less than 10-6 will be ignored.

      Sample Input

      Output for Sample Input

      2

      2

      1 1

      3 1

      2

      1 1

      2 1

      1.000000

      -1.000000

       

      Problem Setter: Ahmad Faiyaz

      Special Thanks: Aninda Majumder


      Added by:Ahmad Faiyaz
      Date:2013-12-24
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17731. Buying Integers

      Problem code: BUYINT


      Buying Integers

       

      Let's assume that you have n integers, A1, A2, A3 An

       

      Let's define,

       

      E = Number of pairs (i,j) such that i<j and ( Ai + Aj ) are even .

      O = Number of pairs (i,j) such that i<j and ( Ai + Aj ) are odd .

      D = | E-O |

       

      That means, D = (E-O) if (E-O) ≥ 0 , -(E-O) otherwise .

       

      Unfortunately, you do have n but those n integers are lost . You will have to buy them again. Before going to the market, you have decided that you will buy n integers in such a way that the value of D will be as small as possible, as you will have to pay D golden coins, to buy them.

       

      Now,you are wondering, what that minimum D [Let's say it Dmin] will be .

       

      Input

       

      First line of the input file will contain the number of test cases, T ≤ 1000000, followed by T lines, each containing an integer n (1 n 109) .

       

      Output

       

      For each case, print the case number starting from 1 and Dmin for the value of n in that particular case. See the sample output for exact formatting.

       

      Sample Input

      Output for Sample Input

      3

      3

      4

      5

      Case 1: 1

      Case 2: 0

      Case 3: 2

      Warning : Input file is huge, please use faster input and output methods (e.g. printf and scanf in C++) .

      Problem Setter: Momontho Mashak Monmoy

      Special Thanks: Muhammad Ridowan


      Added by:Ahmad Faiyaz
      Date:2013-12-24
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      17732. Salary Management

      Problem code: SALMAN


      Salary Management

      You are working as a software engineer of Moogle! Now the boss of Moogle wants you to create a program which will efficiently handle some operations. At first, we should tell you about the structure of the employees at Moogle! Each employee has an integer id from 1 to N. Where 1 is the id of the Managing Director of Moogle! , who is the greatest boss of all the employees. Then except the Managing Director, each employee has an immediate boss. No employees have more than one immediate boss. Now your boss wants to have some operation like this –

      1. He will give you an ID of an employee; you need to find the sum of salary of all the employees under that employee including him/herself.
      2. He will give you an ID of an employee; you need to increase the salary of all the employees under that employee including him/herself by the minimum of minimum salary of all the employees under that employee including him/her and 1000.

      Let’s see the structure, hope you will get a clear idea about the problem.

        Employee Hiearchy

      Employee Hierarchy

      Salary Table:

      ID

      1

      2

      3

      4

      5

      6

      7

      Salary (BDT)

      500

      300

      200

      100

      10

      200

      100


      Now if your boss wants to do the first operation for Employee ID 2. Then the output will be

      300+100+200= 600 BDT

      If your boss wants to do the second operation for the Employee ID 1, then the salary table becomes -

      ID

      1

      2

      3

      4

      5

      6

      7

      Salary (BDT)

      510

      310

      210

      110

      20

      210

      110


      As minimum salary is 10 for Employee id 5 and which is less than 1000.

      Input

      Input starts with an integer T (≤ 3), denoting the number of test cases.

      The first line of a case is a blank line. The next line contains two integers N (1 ≤ N ≤ 105)q (1 ≤ q ≤ 50000) where N denotes the number of nodes and q denotes the number of queries. The nodes are numbered from 1 to N.

      Then there will be N lines. The ith (1 ≤ i ≤ N) line contains two integers pi and si (0 ≤ pi ≤  N, 1 ≤ si < 500)pi denotes the parent and si denotes the salary of the ith employee, respectively. You can assume that the employee id with 1 is the managing director and only its parent is 0.

      Each of the next q lines contains a query. Each query contains two integers: c and v (1 ≤ c ≤ 2, 1 ≤ v ≤ N), where c denotes operation type, and v denotes the employee id. If the c = 1, then it means to do the first operation. If c=2, then the second operation.

      You can assume that the input builds a valid rooted tree.

      Output

      For each case, print the case number in a line. Then for each query type 1, print the sum of the salary.


      Sample Input

      Output for Sample Input

      1


      7 3

      0 500

      1 300

      1 200

      1 100

      3 10

      2 200

      2 100

      1 2

      2 1

      1 2

      Case 1:

      600

      630

      Note

      Dataset is huge. Use faster I/O methods.



      Problem Setter: Ahmad Faiyaz

      Special Thanks: Syed Shahriar Manjur


      Added by:Ahmad Faiyaz
      Date:2013-12-24
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17755. Tree and Palindrome

      Problem code: TREEPAL


       

       

      Tree and Palindrome | TREEPAL

      You are given a tree with N nodes. The tree has following properties


      1. It is rooted at node 1

      2. Node 1 situated in level 0. The children of node 1 is situated in level 1 ,  the children of the level 1 nodes is situated in level 2  , the children of the level 2 nodes is situated in level 3 and so on ….... .

      3. Every node is marked by an alphabet. The nodes of the same level are marked by the same alphabet.

      4. Level zero nodes are marked by 'a' , level 1 nodes are marked by 'b' , level 2 nodes are marked by 'c'
      5. …... level 25 nodes are marked by 'z', level 26 nodes are marked again by 'a', level 27 nodes are marked by 'b' and so on … (the leveling is rotational).


      6. If we take all the alphabets of the nodes serially which are in the path from node a to node b (including a, b) and concatenate them, then we find a string. The name of the string is Bokkor string of pair (a, b).

      You will be given a pair of distinct nodes. You don't know in advance which pair will be given. The probability of choosing every pair is same. Now your job is to calculate the probability that the Bokkor string of the given pair is a palindrome in p/q format (where p and q are co-prime).


        Tree Structure


        Figure: Tree Structure


      Here the pair (2, 3) forms the Bokkor string “bab” which is a palindrome.
      And the pair (4, 5) forms the Bokkor string “cbabc” which is also a palindrome.
      There are no other palindromic Bokkor pairs.
      Equation

        

       

       

       Total numbers of Bokkor pairs       2      1  
       -----------------------------  =   --  =   -  
       Total numbers of Bokkor pairs      10      5  

      Input 

      There will be multiple testcases. The first line of each test case starts with a number N (3<=N<=105) which denotes the number of nodes in the tree. Next N-1 line of the test-case each consists of a pair of integers u, v (1<= u, v<=N and u! = v) which denotes there is an edge between u and v. It is guaranteed that the input is legal (no multiple edges and it forms a valid tree)
       

      Output
      For each test case output is just a single line “p/q” (without the quotes) as described above. It is guaranteed that p>=1.

       

      Sample Input

      Output for Sample Input

      5

      1 2

      1 3

      2 4

      3 5


      6

      1 2

      1 3

      3 4

      3 5

      2 6

      1/5

      4/15

      N.B. Dataset is huge, use faster IO

      Problem Setter: Syed Shahriar Manjur

      Special Thanks: Abdullah Al Maruf , Ahmad Faiyaz


      Added by:Ahmad Faiyaz
      Date:2013-12-25
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      17761. Gopu and Digits Divisibility

      Problem code: SPCQ


      One day Little Gopu was playing with numbers. As he is little boy, he was wondering about divisibility rules that how they apply and what is the logic behind them. Few days ago he has also learnt how to find sum of digits of a number. 

      He thought about finding the smallest number greater than or equal to n, which is a "nice" number. A number is called "nice" if it is divisible by sum of its digits. He is unable to solve this puzzle. Can you write a program to help the Little Gopu?

      eg. if n = 11, 11 is not divisible by 1 + 1 = 2, But 12 is divisible by 1 + 2 = 3. So answer for case n = 11 should be 12.

      Input

      First line contains T : number of test cases. (1 <= T <= 10^4).

      For each test case, It contains a single integer n in a line, (1 <= n <= 10^18).

      Output

      For each test case, output the smallest "nice" number greater or equal to n.

      Example

      Input:
      3
      11
      22
      2 Output: 12
      24

      Added by:praveen123
      Date:2013-12-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      17779. Charlie and the Chocolate Factory

      Problem code: CHARCHOC


      Charlie and the Chocolate Factory

      Charlie Bucket is a loving and kind boy, who lives in poverty with his mother, father and four bedridden grandparents. Down the street, there is Willy Wonka’s chocolate factory who is famous for both his chocolates and the factory. After long years of conducting business with chocolate, now Wonka finally decided to make an heir to the factory.

      So, instead of putting golden tickets in ordinary Wonka bars (which is old fashioned….:P) he decided to take a programming contest to choose 5 candidates for the heir. And, then he will give a tough problem to them (among these five) and the first to answer will be the winner.

      After taking the contest Wonka eventually gets his five candidates and Charlie is one of them.Now, before throwing the heir deciding problem towards them he decided to give them 2 hints.

      1st hint is an algorithm whose pseudo code is given below

      Pseudo Code 

      2nd hint is Kuddus array. A Kuddus array is a sorted array of Kuddus numbers. Kuddus numbers are such prime numbers which can be expressed as the summation of squares of two distinct positive integers.For, example 5 can be expressed as 12+22. So it is a Kuddus number. Also 13(32+22) and 17(42+12) are Kuddus number. So, first few numbers of Kuddus array are 5,13,17…. etc.

      Now, it’s time for the heir deciding problem. The problem is as follows. There are n boxes and all of them are initially empty(no chocolate). Now in every step (starts from 1st step to the last) Wonka will do some sets of operation. The operation are of four kinds. The operation is indicated by an integer op.

      i)  If op=1. Then it is an add operation and it is followed by two integers a,b. It means Wonka will    add b chocolates in box number a.

      ii) If op=2. Then it is a multiplication operation which is also followed by two integers a,b. It means Wonka will multiply the number of chocolates in box number a by b.

      iii) If op=3. Then it is a swap operation which is also followed by a,b. It means the boxes a and b will exchange their chocolates.

      iv) If op=4. Then it is a clear operation which is followed by only a single integer a. This means Wonka will remove all chocolates from box a.

      There are 2 sets of operation. One is an ordinary set and another is special set. In normal steps he will perform the ordinary set of operation serially (as it appears in the input). And in the special steps he will perform the special set of operation serially. Special step number is stored in an array called Special array.

      More precisely, he has an array named Special of infinite numbers. It is a sorted array. The elements of the array are denoted by Special[1],Special[2],Special[3]....etc [normal array system].So he will perform the special operation only at Special[1]th,Special[2]th, Special[3]th…... etc steps.

      Now,

               Special:=MakeNewArray(Kuddus,d).

      Here MakeNewArray and Kuddus are described previously. d is an integer which will be given in the input. At last Wonka will tell the number of steps s.

      Now, Charlie is busy in some other works. So, he needs your help. You will have to answer after s steps what is the total number of chocolates in all the boxes (summation of all the chocolates in every box).

      Input:

      Input consists of some test cases (not more than 15).

      Every case begins with two integer n (>=2) and d (1<=d<=5). Then there is an integer op1 which denotes the number of operation for ordinary steps. The next op1 lines each contain a number op (1<=op<=4) and if op<=3 then it is followed by two integers a and b, otherwise (op=4) it is followed by a. The meaning of them is described above. Then there is another integer op2 which denotes the number of operations for special steps and the next op2 steps is also followed by same format of input as op1 is followed.Finally comes the number of steps s (1<=s<=108).

      The meaning of every symbol is described above. Every input is a non-negative integer and not more than 1000 unless stated otherwise. There are no illegal input (i.e. there is no illegal box where operation will be performed). It is also guaranteed that there are equal number of cases for each possible values of d and n<=2*d2.

      Output:

      For each testcase the answer will be just a single line denoting the total number of chocolates in the boxes after s steps. You should return the answer%264.


      Sample Input                                                      

      Sample Output

      2 1

      5

      1 1 1

      1 2 1

      2 1 2

      2 2 3

      3 1 2

      3

      1 1 1

      1 2 1

      3 1 2

      4


      2 1

      5

      1 1 1

      1 2 1

      2 1 2

      2 2 3

      3 1 2

      3

      1 1 1

      1 2 1

      3 1 2

      5

      119

      121

       

      Problem Setter: Syed Shahriar Manjur

      Special Thanks: Nafis Ahmed


      Added by:Ahmad Faiyaz
      Date:2013-12-26
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17789. Space Bridges

      Problem code: SPACEBRG


      Space Bridges

      A long time ago, in a galaxy far, far away…. war is going on between the Galactic Empire and the Rebel Alliance. During wars like these, space bridges are really resourceful as they can transfer almost anything including Storm Trooper armies from one space region to another in just mere seconds. Each space region consists of many sectors. The sectors are connected with each other via space roads in such a way that there is exactly one path from one sector to another within a space region. Note that space roads and space bridges are not the same.

      The sectors of two space regions of the empire have already been arranged. To find if the arrangement is strong enough, the Supreme Commander of the Imperial Forces has ordered you, their top programmer to calculate the total strength of the two regions.

      graph

      Two regions can be connected using exactly one Space Bridge from one sector of a region to one sector of the other region. The value of a space bridge connection is the maximum path length you need to travel from any sector of one region to any sector of the other region using any space road or space bridge at most once. The total strength of two regions is the summation of the power of all possible space bridge connections. 

      Given the sector arrangements of both space regions, your task is to find the total strength of the two regions. Unfortunately, if the strength isn’t as expected, the Supreme Commander will use his “Force Choke” on you, so good luck!

      Input

      Input starts with an integer T (≤ 20), denoting the number of test cases.

      Each case starts with a line containing two integers n and m (1 ≤ n,m ≤ 105) denoting the number of sectors in the two space regions correspondingly. The next n-1 lines denotes the sector arrangement of the first region. Each line will contain u and v (1 <= u,v <= n, u!=v) denoting that there is a space road connection between the sectors u and v of the first region. It is guaranteed that the arrangement is such that there will be exactly one path from any sector to another and no same space road will occur twice in the given input. The next m-1 lines denotes the sector arrangements of the second region containing p and q (1 <=p,q <= m, p!=q) which is analogous to the arrangement of the first region.

      Output

      For each case, in a single line print the case number and the strength of the combined region the space regions.

      Sample Input

      Output for Sample Input

      2

      2 4

      2 1

      2 3

      3 1

      3 4

      2 1

      2 1

      Case 1: 30

      Case 2: 4


      Note: In the second sample, there are 2 possible space bridge connections. The first connection is by connecting the first sector of the first region to the first sector of the second region and the second connection is by connecting the second sector of the first region to the first sector of the second region. The values of both the space bridge connections is 2, as you need no more than 2 space roads and space bridges to travel from any sector of the first region to the only sector of the second region. So the total strength is 2+2=4. Look at the figures for better understanding.

      N.B. Dataset is huge, use faster IO

      Problem Setter: Aninda Majumder

      Special Thanks: Momontho Mashak Monmoy, Nafis Sadique, Ahmad Faiyaz


      Added by:Ahmad Faiyaz
      Date:2013-12-27
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17804. Gopu And Palindromes

      Problem code: SPCS


      Gopu loves palindromes. A palindrome is a string which is same even when it is reversed. eg. aba, a, abba are palindromes whereas, ab is not a palindrome. 

      Once Gopu was playing with string s, he thought of whether he can change this string into a palindrome or not.

      A "cool operation" takes some substring of string with the property that all the characters in the substring should be same. Let us say that substring has size L. Then he can reduce ther size of this substring by alteast 0 and atmost L - 1. eg. string is abbb, He can change substring bbb into b, bb, bbb (corresponding to not changing it at all) which will make the string s into ab, abb, abbb respectively.

      He can apply a "cool operation" as many times as he wishes.

      Find out whether he can convert the string into a palindrome or not?

      Output "YES" if possible, else output "NO".

      Input

      First line of input contains number of test cases T, (1 <= T <= 100).

      For each test case, there is a single line representing the string with which Gopu is playing with. (length of string >= 1 and <= 10^5). String will only contain small letters of english alphabet ie 'a' to 'z'.

      Output

      For each test case output a single line containing "YES" or "NO" (without quotes) respectively to situation whether he can convert given string into palindrome or not?

      Example

      Input:
      5
      aba
      aabaaa
      aabbba
      aaab
      abca 
      Output:
      YES
      YES
      YES
      NO
      NO 

      Explanation:

      For first test case string "aba", string is already a palindrome, so no need to apply "cool operation".
      For second test case string "aabaaa", take aaa and convert it into aa, So string becomes aabaa which is a palindrome.
      For fifth test case string "abca", Gopu can not convert it into palindrome despite applying any "cool operation".

      Added by:praveen123
      Date:2013-12-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      17819. XYI

      Problem code: XYI



      You are quite new to Bioinformatics studies. While working in the lab you have met Professor Shakil, who is a bit crazy. You know that there are twenty-two chromosomes and there is the X chromosome and the Y chromosome.

      Now Professor Shakil is very determined that there are mutants hiding among us (After watching the new Wolverine movie he went nuts). And he is very positive about a new type of chromosome, which is the I chromosome.

      As the Professor is very excited and not suitable for lab work, he will give you a chromosome each time. You have to determine which type it is (X, Y, I or NotValid).

      Chromosomes can be viewed as a set of nodes and edges. Look at the images for details. The dotted line represents that there can be an arbitrary number of nodes and edges in these directions (they have to represent a straight line, though).

      XIY

       

      Input

      In the first line, you will be given the number of test cases T, where T<=200. Then the test cases will follow. Each test case will have two integers at the beginning, N and M. Here N is the number of nodes and M is the number of edges, where 4<=N<=500 and 3<=M<=(N*N-1)/2. Then M lines will follow, each consisting of two integers, U and V, which specifies that there is an edge between node U and node V. It is guaranteed that and given graph will be connected and there will be at most one edge between two nodes.

       

      Output

      You have to output the correct chromosome each test case represents, or NotValid if the test case doesn’t represent the three given chromosomes. You have to print “Case T: Z”, (without the braces) for each test case, where T is the test case number and Z is the correct chromosome or “NotValid”. Please look at the sample I/O for details.

      Sample Input

      Output for Sample Input

      2

      4 4

      1 2

      2 3

      3 4

      4 1

      4 3

      1 2

      2 3

      2 4

       

      Case 1: NotValid

      Case 2: Y

      Problem Setter: Nafis Ahmed
      Special Thanks: Nafis Sadique

      Added by:Ahmad Faiyaz
      Date:2013-12-29
      Time limit:0.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17821. My Name is UMMM!

      Problem code: MNIU



      My Name is UMMMM….

      In a country far away there is a kind of a competition called programming contests. As they are becoming increasingly popular, they get regular coverage on newspapers. That's the only positive part of the story. The quality of their reports are not up to the mark and often hilarious for the competitive programming community. The reporters often mix up names - exchanging words from one person's name to someone else's name.

      Chowdhury Shaheb - a curious programmer analyzed the reports and found a very interesting pattern. He saw whenever any word of two person's names have the same first and last letters and at least one additional common letter, journalists will mix them up. For example: The words ‘Manjur’ and ‘Mazumder’ have same first and last letters and two common letters 'a' and 'u'.

      You'll be given a pair of names. List all possible confusing name variations of those two names. A confusing variation of a name is obtained by changing at least one word of that name to a similar word (according to the aforementioned pattern) from the other’s name. A variation is not considered confusing if it is exactly same to any of the given names. See the input and output format section for more details.

      Input

      First line of input will contain a single integer T (1 <= T <= 15), the number of testcases. It will be followed by T sets of testcases. Each set of testcase will contain two lines, each line will contain a name. Each name will contain no more than 20 characters. Names will have no more than 3 words, each word will consist of only Engish letters (‘A’- ‘Z’ , ‘a’-‘z’). First letter of a word will always be capitalized and others are in lowercase. Each word of a name will be separated by exactly one space between them.

      Output

      First line of the output of each test case should contain the case number (In this format: Case <casenumber>:). From the next line, print all the confusing variations - one per line in ascending lexicographic order. A name X is lexicographically smaller than another name B if it contains a smaller letter at the first position they differ or if X is a prefix of Y. A space is smaller than any other English character. If there is no confusing name, print "None" (without the quotes). Print a blank line between testcases.

      Sample Input

      Output for Sample Input

      3

      Syed Shahriar Manjur

      Pratyai Mazumder

      Tasnim Imran Sunny

      Sabbir Yousuf Sanny

      Md Hafiz Uddin

      Sohel Hafiz

      Case 1:

      Pratyai Manjur

      Syed Shahriar Mazumder


      Case 2:

      Sabbir Yousuf Sunny

      Tasnim Imran Sanny


      Case 3:

      None

      Problem Setter: Mir Wasi Ahmed

      Special Thanks: Ahmad Faiyaz


      Added by:Ahmad Faiyaz
      Date:2013-12-30
      Time limit:0.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17877. Two Swamills

      Problem code: SAWMILL


      There are old trees planted along a road that goes from the top of a hill to its bottom. Local government decided to cut them down. In order not to waste wood each tree should be transported to a sawmill.

      Trees can be transported only in one direction: downwards. There is a sawmill at the lower end of the road. Two additional sawmills can be built along the road. You have to decide where to build them, as to minimize the cost of transportation. The transportation costs one cent per meter, per kilogram of wood.

      Input

      The first line of the input contains one integer - the number of trees (). The trees are numbered , starting from the top of the hill and going downwards. Each of the following lines contains two positive integers separated by single space. Line contains: - weight (in kilograms) of the -th tree and - distance (in meters) between trees number and , , . The last of these numbers, , is the distance from the tree number to the lower end of the road. It is guaranteed that the total cost of transporting all trees to the sawmill at the end of the road is less than cents.

      Output

      The first and only line of output should contain one integer: the minimum cost of transportation.

      Example

      Input:
      
      9
      1 2
      2 1
      3 3
      1 1
      3 2
      1 6
      2 1
      1 2
      1 1
      Output:
      26

      Added by:acheron
      Date:2014-01-04
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:CEOI 2004









      SPOJ Problem Set (classical)

      17918. Gopu and Validity of Arrangement

      Problem code: SPCU


      N persons are standing in a line. Height of each person is between 1 and N and height of each person is distinct. 

      You are  given an array A where A[i] denotes how many persons are there before the i_th person having heights greater than the height of the ith person. For a person i, all the persons from 1 to i - 1 are considered to be before him. eg, For person 2, person 1 is considered before him.

      You have to find out whether this array can be valid for some arrangement of persons. If you can uniquely do so then output "YES" Otherwise output "NO".

      Input

      First line contains T : number of test cases. (1 <= T <= 20).

      For each test First line contains an integer n. ( 1 <= N <= 10^5)

      Next line contains n space seperated integers denoting A[i]. (0 <= A[i] <= N)

      Output

      For each test case, output "YES" or "NO" according to answer.

      Example

      Input:
      2
      2
      0 1
      2
      1 1 
      Output:
      YES
      NO

      Explanation

        For the first test case, [2, 1] is a valid case, First person has height 2, second person has height 1. 

        For the second test case, no valid test case exists.


      Added by:praveen123
      Date:2014-01-08
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      17943. Mickey Mouse Magic Trick v3

      Problem code: MMMAGIC3


      MMMAGIC3

      Mickey Mouse and Donald Duck love magic. They spacialize with card tricks. Mickey invented a new trick and they are going to surprise the world. They've contracted series of shows on whole the globe, worth many milion of dolars $$. The first show is coming up but unfortunately Mickey lost secret of the trick. He remembers only trick description, but it's not enough to satisfy the contract conditions. Help them!

      Trick description

      Mickey has n cards with values 1, 2, ..., n. He invites a spectator from the audience, Donald is outside the stage and see nothing on the stage. The spectator chooses randomly k cards from the pack and discard the remaining n-k cards. Mickey chooses one card from this k cards, shows it to everyone (except Donald) and hides it to the spectator's pocket. Next Mickey leaves the remaining k-1 cards in some order on the table. Donald is coming back. He is the only person, who don't know, what is the number in the hiden card. He can see only k-1 cards on the table. Donald thinks for a while, the drum rumbles, at the begining very silent, then lauter and lauter, everyone is waiting, the drum stops, a few seconds of deep silence and... Donald says the number on the hidden card. It's correct, applause! How did he discover the number? It's magic!

      Help request

      Mickey and Donald know, that's not magic only smart math manipulations. They asked You to help them. You have to write computer program, that can help them with the trick. The program should be able to do two things: help Mickey to select one card from given k cards and describe order of remaining k-1 cards on the table, then help Donald to guess the hidden card value basing only on k-1 cards left by Mickey on the table. You can use any strategy that You want, but remember - Donald needs to guess the number during the show, because the huge profit $$ depends on it.

      Input

      All integers in the same line are single-space separated (the same concerns problem output).

      Values n, k are constant. In this problem n=8 and k=3. There are also problems with different values: MMMAGIC4, MMMAGIC5, MMMAGIC6

      The first line of input contains two integers M, D, where M is the number of test cases in which Mickey needs help, D is the number of test cases in which Donald needs help (M+D < 200) .

      Every of next M lines contains k distinct integers from range [1, n] - the values on cards given to Mickey. The order of values is casual.

      Every of next D lines contains k-1 distinct integers from range [1, n] - the cards left to Donald on the table. The order is the same, as on the table, from left to right.

      Output

      For each Mickey's query write a line with k-1 integers - the values on the cards, that Mickey have to leave on the table, from left to right.

      For each Donald's query write a line with one integer - the value of hidden card or (if in Your strategy such situation is impossible) any of remaining values.

      Example

      Input 1 Output 1
      3 0
      1 2 3
      4 6 2
      8 7 4

      2 1
      4 6
      4 7

       

      Input 2 Output 2
      0 3
      2 1
      4 6
      4 7

      3
      2
      8

      Explanation

      The example above don't show any concrete strategy. It just shows, that strategy must be coherent (when Mickey for given set of cards 1 2 3 leave on the table 2 1, then Donald for given cards 2 1 should answer with the number 3).

      Generally You can implement Your own strategy satisfying the conditions below:

      • for Mickey's query "a1 a2 ... ak" You should reply "b1 b2 ... bk-1", such that {b1, b2, ..., bk-1} is subset of {a1, a2, ..., ak}
      • for Donald's query "b1 b2 ... bk-1" reply the number c, such that {b1, b2, ..., bk-1, c} = {a1, a2, ..., ak}

       

      Note

      The similar problem appeared in MWPZ 2007 contest in Poland, with different story (in original problem there was Polish characters Bolek and Lolek). The main page of contest is http://mwpz.poznan.pl


      Added by:miodziu
      Date:2014-01-09
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:MWPZ 2007 http://mwpz.poznan.pl/









      SPOJ Problem Set (classical)

      17944. Mickey Mouse Magic Trick v4

      Problem code: MMMAGIC4


      MMMAGIC4

      Mickey Mouse and Donald Duck love magic. They spacialize with card tricks. Mickey invented a new trick and they are going to surprise the world. They've contracted series of shows on whole the globe, worth many milion of dolars $$. The first show is coming up but unfortunately Mickey lost secret of the trick. He remembers only trick description, but it's not enough to satisfy the contract conditions. Help them!

      Trick description

      Mickey has n cards with values 1, 2, ..., n. He invites a spectator from the audience, Donald is outside the stage and see nothing on the stage. The spectator chooses randomly k cards from the pack and discard the remaining n-k cards. Mickey chooses one card from this k cards, shows it to everyone (except Donald) and hides it to the spectator's pocket. Next Mickey leaves the remaining k-1 cards in some order on the table. Donald is coming back. He is the only person, who don't know, what is the number in the hiden card. He can see only k-1 cards on the table. Donald thinks for a while, the drum rumbles, at the begining very silent, then lauter and lauter, everyone is waiting, the drum stops, a few seconds of deep silence and... Donald says the number on the hidden card. It's correct, applause! How did he discover the number? It's magic!

      Help request

      Mickey and Donald know, that's not magic only smart math manipulations. They asked You to help them. You have to write computer program, that can help them with the trick. The program should be able to do two things: help Mickey to select one card from given k cards and describe order of remaining k-1 cards on the table, then help Donald to guess the hidden card value basing only on k-1 cards left by Mickey on the table. You can use any strategy that You want, but remember - Donald needs to guess the number during the show, because the huge profit $$ depends on it.

      Input

      All integers in the same line are single-space separated (the same concerns problem output).

      Values n, k are constant. In this problem n=27 and k=4. There are also problems with different values: MMMAGIC3, MMMAGIC5, MMMAGIC6

      The first line of input contains two integers M, D, where M is the number of test cases in which Mickey needs help, D is the number of test cases in which Donald needs help (M+D < 40000).

      Every of next M lines contains k distinct integers from range [1, n] - the values on cards given to Mickey. The order of values is casual.

      Every of next D lines contains k-1 distinct integers from range [1, n] - the cards left to Donald on the table. The order is the same, as on the table, from left to right.

      Output

      For each Mickey's query write a line with k-1 integers - the values on the cards, that Mickey have to leave on the table, from left to right.

      For each Donald's query write a line with one integer - the value of hidden card or (if in Your strategy such situation is impossible) any of remaining values.

      Example

      Input 1 Output 1
      3 0
      1 2 3 4
      4 13 6 2
      8 20 7 4

      3 2 1
      13 4 6
      4 20 7

       

      Input 2 Output 2
      0 3
      3 2 1
      13 4 6
      4 20 7

      4
      2
      8

      Explanation

      The example above don't show any concrete strategy. It just shows, that strategy must be coherent (when Mickey for given set of cards 1 2 3 4 leave on the table 3 2 1, then Donald for given cards 3 2 1 should answer with the number 4).

      Generally You can implement Your own strategy satisfying the conditions below:

      • for Mickey's query "a1 a2 ... ak" You should reply "b1 b2 ... bk-1", such that {b1, b2, ..., bk-1} is subset of {a1, a2, ..., ak}
      • for Donald's query "b1 b2 ... bk-1" reply the number c, such that {b1, b2, ..., bk-1, c} = {a1, a2, ..., ak}

       

      Note

      The similar problems appeared in MWPZ 2007 contest in Poland, with different story (in original problems there was Polish characters Bolek, Lolek and Jacek, Placek). The main page of contest is http://mwpz.poznan.pl


      Added by:miodziu
      Date:2014-01-09
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17945. Mickey Mouse Magic Trick v5

      Problem code: MMMAGIC5


      MMMAGIC5

      Mickey Mouse and Donald Duck love magic. They spacialize with card tricks. Mickey invented a new trick and they are going to surprise the world. They've contracted series of shows on whole the globe, worth many milion of dolars $$. The first show is coming up but unfortunately Mickey lost secret of the trick. He remembers only trick description, but it's not enough to satisfy the contract conditions. Help them!

      Trick description

      Mickey has n cards with values 1, 2, ..., n. He invites a spectator from the audience, Donald is outside the stage and see nothing on the stage. The spectator chooses randomly k cards from the pack and discard the remaining n-k cards. Mickey chooses one card from this k cards, shows it to everyone (except Donald) and hides it to the spectator's pocket. Next Mickey leaves the remaining k-1 cards in some order on the table. Donald is coming back. He is the only person, who don't know, what is the number in the hiden card. He can see only k-1 cards on the table. Donald thinks for a while, the drum rumbles, at the begining very silent, then lauter and lauter, everyone is waiting, the drum stops, a few seconds of deep silence and... Donald says the number on the hidden card. It's correct, applause! How did he discover the number? It's magic!

      Help request

      Mickey and Donald know, that's not magic only smart math manipulations. They asked You to help them. You have to write computer program, that can help them with the trick. The program should be able to do two things: help Mickey to select one card from given k cards and describe order of remaining k-1 cards on the table, then help Donald to guess the hidden card value basing only on k-1 cards left by Mickey on the table. You can use any strategy that You want, but remember - Donald needs to guess the number during the show, because the huge profit $$ depends on it.

      Input

      All integers in the same line are single-space separated (the same concerns problem output).

      Values n, k are constant. In this problem n=124 and k=5. There are also problems with different values: MMMAGIC3, MMMAGIC4, MMMAGIC6

      The first line of input contains two integers M, D, where M is the number of test cases in which Mickey needs help, D is the number of test cases in which Donald needs help (M+D < 106).

      Every of next M lines contains k distinct integers from range [1, n] - the values on cards given to Mickey. The values are sorted in ascending order.

      Every of next D lines contains k-1 distinct integers from range [1, n] - the cards left to Donald on the table. The order is the same, as on the table, from left to right.

      Output

      For each Mickey's query write a line with k-1 integers - the values on the cards, that Mickey have to leave on the table, from left to right.

      For each Donald's query write a line with one integer - the value of hidden card or (if in Your strategy such situation is impossible) any of remaining values.

      Example

      Input 1 Output 1
      3 0
      1 2 3 4 5
      2 4 6 40 80 
      4 7 8 72 123

      4 3 2 1
      4 6 80 2
      4 7 123 8

       

      Input 2 Output 2
      0 3
      4 3 2 1
      4 6 80 2
      4 7 123 8

      5
      40
      72

      Explanation

      The example above don't show any concrete strategy. It just shows, that strategy must be coherent (when Mickey for given set of cards 1 2 3 4 5 leave on the table 4 3 2 1, then Donald for given cards 4 3 2 1 should answer with the number 5).

      Generally You can implement Your own strategy satisfying the conditions below:

      • for Mickey's query "a1 a2 ... ak" You should reply "b1 b2 ... bk-1", such that {b1, b2, ..., bk-1} is subset of {a1, a2, ..., ak}
      • for Donald's query "b1 b2 ... bk-1" reply the number c, such that {b1, b2, ..., bk-1, c} = {a1, a2, ..., ak}

       

      Note

      The problem appeared in MWPZ 2007 contest in Poland, with different story (in original problem there was Polish characters Jacek and Placek). The main page of contest is http://mwpz.poznan.pl


      Added by:miodziu
      Date:2014-01-09
      Time limit:50s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:MWPZ 2007 http://mwpz.poznan.pl/









      SPOJ Problem Set (classical)

      17946. Mickey Mouse Magic Trick v6

      Problem code: MMMAGIC6


      MMMAGIC6

      Mickey Mouse and Donald Duck love magic. They spacialize with card tricks. Mickey invented a new trick and they are going to surprise the world. They've contracted series of shows on whole the globe, worth many milion of dolars $$. The first show is coming up but unfortunately Mickey lost secret of the trick. He remembers only trick description, but it's not enough to satisfy the contract conditions. Help them!

      Trick description

      Mickey has n cards with values 1, 2, ..., n. He invites a spectator from the audience, Donald is outside the stage and see nothing on the stage. The spectator chooses randomly k cards from the pack and discard the remaining n-k cards. Mickey chooses one card from this k cards, shows it to everyone (except Donald) and hides it to the spectator's pocket. Next Mickey leaves the remaining k-1 cards in some order on the table. Donald is coming back. He is the only person, who don't know, what is the number in the hiden card. He can see only k-1 cards on the table. Donald thinks for a while, the drum rumbles, at the begining very silent, then lauter and lauter, everyone is waiting, the drum stops, a few seconds of deep silence and... Donald says the number on the hidden card. It's correct, applause! How did he discover the number? It's magic!

      Help request

      Mickey and Donald know, that's not magic only smart math manipulations. They asked You to help them. You have to write computer program, that can help them with the trick. The program should be able to do two things: help Mickey to select one card from given k cards and describe order of remaining k-1 cards on the table, then help Donald to guess the hidden card value basing only on k-1 cards left by Mickey on the table. You can use any strategy that You want, but remember - Donald needs to guess the number during the show, because the huge profit $$ depends on it.

      Input

      All integers in the same line are single-space separated (the same concerns problem output).

      Values n, k are constant. In this problem n=725 and k=6. There are also problems with different values: MMMAGIC3, MMMAGIC4, MMMAGIC5

      The first line of input contains two integers M, D, where M is the number of test cases in which Mickey needs help, D is the number of test cases in which Donald needs help (M+D < 106).

      Every of next M lines contains k distinct integers from range [1, n] - the values on cards given to Mickey. The values are sorted in ascending order.

      Every of next D lines contains k-1 distinct integers from range [1, n] - the cards left to Donald on the table. The order is the same, as on the table, from left to right.

      Output

      For each Mickey's query write a line with k-1 integers - the values on the cards, that Mickey have to leave on the table, from left to right.

      For each Donald's query write a line with one integer - the value of hidden card or (if in Your strategy such situation is impossible) any of remaining values.

      Example

      Input 1 Output 1
      3 0
      1 2 3 4 5 6
      2 4 6 100 200 500
      4 7 8 111 222 666

      5 4 3 2 1
      6 500 4 100 200
      4 111 7 8 222

       

      Input 2 Output 2
      0 3
      5 4 3 2 1
      6 500 4 100 200
      4 111 7 8 222

      6
      2
      666

      Explanation

      The example above don't show any concrete strategy. It just shows, that strategy must be coherent (when Mickey for given set of cards 1 2 3 4 5 6 leave on the table 5 4 3 2 1, then Donald for given cards 5 4 3 2 1 should answer with the number 6).

      Generally You can implement Your own strategy satisfying the conditions below:

      • for Mickey's query "a1 a2 ... ak" You should reply "b1 b2 ... bk-1", such that {b1, b2, ..., bk-1} is subset of {a1, a2, ..., ak}
      • for Donald's query "b1 b2 ... bk-1" reply the number c, such that {b1, b2, ..., bk-1, c} = {a1, a2, ..., ak}

       

      Note

      The similar problems appeared in MWPZ 2007 contest in Poland, with different story (in original problems there was Polish characters Bolek, Lolek and Jacek, Placek). The main page of contest is http://mwpz.poznan.pl


      Added by:miodziu
      Date:2014-01-09
      Time limit:99s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      17955. Lalith Dosa

      Problem code: DOSA


       

      Lalith is going to have dinner and he has  N dosas in front of him with their prices represented by sequence of integers a1,a2,a3...an. 
      And he has decided to eat in a different manner . You are free to replace the price of any dosa with any positive integer. 
      How many prices(integers) must be replaced to make the resulting sequence strictly increasing?

      Lalith is going to have dinner and he has  N dosas in front of him with their prices represented by sequence of integers a1,a2,a3...an. 

      And he has decided to eat in a different manner . You are free to replace the price of any dosa with any positive integer. 

      How many prices(integers) must be replaced to make the resulting sequence strictly increasing?

       

      Input

      The first line of the test case contains an integer N - the number of dosas.

      The next line contains N space separated integers where the ith integer is ai , representing thr price of i-th dosa.

      Output

      Output the minimal number of prices(integers) that should be replaced to make the sequence strictly increasing.

      Constraints

      0 < N <= 10^6

      0 < ai <= 10^9

       

      Sample Input #01

      6

      1 7 10 2 20 22

      Sample Output #01

      1

       

      Sample Input #02

      5

      1 2 2 3 4 

      Sample Output #02

      3

      Explanation 

      In the first sample input, we can replace 2 with any integer between 11 and 19 to make the price sequence strictly increasing, hence the output is 1. 

      In the second sample input, we can obtain 1, 2, 3, 4, 5 by changing the last three elements of the price sequence.

       


      Added by:Arun Lakshman
      Date:2014-01-09
      Time limit:0.5s-1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      18050. Robert Langdon & Class Attendance

      Problem code: RLCAT


      With growing popularity of Robert in Harvard, many students have started opting for his course on Symbolism as institute elective course. Class strength has increased to an extent that even with his eidetic memory; Robert is having a hard time remembering faces of the students in his class. This made him switch to using attendance sheet to take attendance of the class.
      Imagine N students sitting in a straight row, students are numbered 1 to N. Attendance sheet is first given to student 1, who uses his own pen to sign the sheet. Then he passes the sheet to student 2, and chooses wheather or not to give him the pen too. If student 2 doesn't get a pen from student 1, he will take out his own pen. Student 2, after signing the sheet, will pass the sheet to student 3, and again makes a choice wheather or not to pass the pen. Note that he can even pass the pen that came to him from student 1.
      So first student's pen might end up being used by the entire class.
      A person becomes annoyed if his pen is used by someone who is not his friend. Each person has a "compatibility value", and two students are friends if the absolute difference of their compatibility values is less than or equal to a given threshold D.
      Given compatibility values of each student in the class, find the minimum number of students that must take out their pens to sign so that no one gets annoyed.
      NOTE : it is not allowed that a person gets a pen from his neighbour, and passes it along without using it (i.e., uses his own pen for his attendance and passes ahead the pen of his neighbour).
      INPUT:
      First line contains T, number of test cases
      Each test case has two lines
      First line of each test case contains two space separated integers N and D, indicating the number of students in the class and friendship threshold respectively.
      Next line contains a space separated array A of N elements, A[i] being the compatibility value of ith student.
      OUTPUT:
      For each testcase, output in a single line minimum number of pens that must be taken out so that the whole class is able to mark the attendance and no one gets annoyed.
      EXAMPLE INPUT:
      2
      5 2
      3 1 2 4 5
      5 3
      1 4 7 1 5
      EXAMPLE OUTPUT:
      1
      2
      CONSTRAINTS:
      1<=T<=1000
      1<=N<=300000
      1<=D<=10^9
      Sum of all N over all test cases will not exceed 300000
      1<=A[i]<=10^9

      With growing popularity of Robert in Harvard, many students have started opting for his course on Symbolism as institute elective course. Class strength has increased to an extent that even with his eidetic memory; Robert is having a hard time remembering faces of the students in his class. This made him switch to using attendance sheet to take attendance of the class.

      Imagine N students sitting in a straight row, students are numbered 1 to N. Attendance sheet is first given to student 1, who uses his own pen to sign the sheet. Then he passes the sheet to student 2, and chooses wheather or not to give him the pen too. If student 2 doesn't get a pen from student 1, he will take out his own pen. Student 2, after signing the sheet, will pass the sheet to student 3, and again makes a choice wheather or not to pass the pen. Note that he can even pass the pen that came to him from student 1.

      So first student's pen might end up being used by the entire class.

      A person becomes annoyed if his pen is used by someone who is not his friend. Each person has a "compatibility value", and two students are friends if the absolute difference of their compatibility values is less than or equal to a given threshold D.

      Given compatibility values of each student in the class, find the minimum number of students that must take out their pens to sign so that no one gets annoyed.

       

      NOTE : it is not allowed that a person gets a pen from his neighbour, and passes it along without using it (i.e., uses his own pen for his attendance and passes ahead the pen of his neighbour).

       

      INPUT:

      First line contains T, number of test cases

      Each test case has two lines

      First line of each test case contains two space separated integers N and D, indicating the number of students in the class and friendship threshold respectively.

      Next line contains a space separated array A of N elements, A[i] being the compatibility value of ith student.

       

      OUTPUT:

      For each testcase, output in a single line minimum number of pens that must be taken out so that the whole class is able to mark the attendance and no one gets annoyed.

       

      EXAMPLE INPUT:

      2

      5 2

      3 1 2 4 5

      5 3

      1 4 7 1 5

       

      EXAMPLE OUTPUT:

      1

      2

       

      CONSTRAINTS:

      1<=T<=1000

      1<=N<=300000

      1<=D<=109

      Sum of all N over all test cases will not exceed 300000

      1<=A[i]<=109


      Added by:Piyush Kumar
      Date:2014-01-15
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:IIT Bombay Coding GC









      SPOJ Problem Set (main)

      18056. Robert Langdon & Cipher

      Problem code: RLCIPHER


      Robert and Sienna are running, with Florence police catching up fast. They make a swift left, and found a shallow alley, with a strange looking metal gate at the end. Their only way out : open the gate.
      The gate has a horizontal bar, with N sections on it. Each section has an input portal, and a number written below that portal. They have to enter correct number at each portal to open the gate.
      The hint given below the portals :
      "Take out three, take out four,
      Below the voids, take no more.
      Tire your brain, let the blood flow,
      Plunge it deepest, let it go."
      Robert figured : For each section, keep subtracting 3 or 4 from the number written in that section, till the number becomes negative. Try to get the smallest number possible using these operations. Then enter the number in that portal.
      They entered the numbers and quickly got in. Can you guess what they answered?
      INPUT:
      First line contains T, number of test cases. Then each test case contains two lines.
      First line of each test case contains N, the number of sections on the horizontal bar.
      Second line contains N space separated numbers, containing the numbers on the N sections.
      OUTPUT:
      For each testcase, output one line of N space separated number, containing the numbers that must be entered in the portals to get the gate open.
      EXAMPLE INPUT:
      2
      3
      0 2 1
      4
      3 2 1 -1
      EXAMPLE OUTPUT:
      -4 -2 -3
      -4 -2 -3 -1
      CONSTRAINTS:
      1<=T<=1000
      1<=N<=100000
      Sum of all N's in a test file will not exceed 10^5
      Each number in each section is between -10^9 to +10^9 inclusive.

      Robert and Sienna are running, with Florence police catching up fast. They make a swift left, and found a shallow alley, with a strange looking metal gate at the end. Their only way out : open the gate.

      The gate has a horizontal bar, with N sections on it. Each section has an input portal, and a number written below that portal. They have to enter correct number at each portal to open the gate.

      The hint given below the portals :

      "Take out three, take out four,

      Below the voids, take no more.

      Tire your brain, let the blood flow,

      Plunge it deepest, let it go."

       

      Robert figured : For each section, keep subtracting 3 or 4 from the number written in that section, till the number becomes negative. Try to get the smallest number possible using these operations. Then enter the number in that portal.

      They entered the numbers and quickly got in. Can you guess what they answered?

       

      INPUT:

      First line contains T, number of test cases. Then each test case contains two lines.

      First line of each test case contains N, the number of sections on the horizontal bar.

      Second line contains N space separated numbers, containing the numbers on the N sections.

       

      OUTPUT:

      For each testcase, output one line of N space separated number, containing the numbers that must be entered in the portals to get the gate open.

       

      EXAMPLE INPUT:

      2

      3

      0 2 1

      4

      3 2 1 -1

       

      EXAMPLE OUTPUT:

      -4 -2 -3

      -4 -2 -3 -1

       

      CONSTRAINTS:

      1<=T<=1000

      1<=N<=100000

      Sum of all N's in a test file will not exceed 105

      Each number in each section is between -109 to +109 inclusive.


      Added by:Piyush Kumar
      Date:2014-01-15
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IIT Bombay Coding GC









      SPOJ Problem Set (main)

      18094. Robert Langdon & Florence

      Problem code: RLTOUR


       

      As a token of thanks for his help, Elizabeth Sinskey has gifted Robert Langdon an amazing set of Russian dolls. The dolls have the property that if doll A has height HA and doll B has height HB, then B can fit inside A if HA>=HB.
      Robert noted the heights of the dolls (two dolls can have same height), and then arranged the dolls in a line beautifully. For each doll he noted down the number of dolls that are before this doll in the line and can contain this doll. He wrote this down on another piece of paper.
      Accidentally, the dolls fell out of line, and Robert wants to arrange them back beautifully. Given the two pieces of information (heights of the dolls and number of dolls before this in line that can contain this doll), can you rearrange the dolls beautifully?
      INPUT:
      First line contains T, number of test cases
      Each test case consists of 3 lines
      First line of each test case has a single number N, number of dolls.
      Second line contains array H, space separated array of size N containing the heights of dolls.
      Third line contains array C, space separated array of size N, C[i] indicating number of dolls before this in the beautiful arrangement that can contain doll i.
      OUTPUT:
      For each test case, output a single line containing the heights of dolls in order as they were when Robert arranged them beautifully.
      Assume that a valid solution always exists.
      EXAMPLE INPUT:
      2
      3
      12 13 14
      0 0 2
      3
      12 14 13
      0 1 0
      EXAMPLE OUTPUT:
      13 14 12
      13 12 14
      EXPLAINATION:
      For the first case, (arrangement 13,14,12) 13 and 14 cannot be contained by any doll prior to them, but 12 can be put in doll 13 as well as doll 14, hence the array 0 0 2
      For the second case, (arrangement 13,12,14) 12 can be contained in 13, hence the array 0 1 0
      CONSTRAINTS:
      1<=T<=500
      1<=N<=500
      1<=H[i]<=10^9

      As a token of thanks for his help, Elizabeth Sinskey has gifted Robert Langdon an amazing set of Russian dolls. The dolls have the property that if doll A has height HA and doll B has height HB, then B can fit inside A if HA>=HB.

      Robert noted the heights of the dolls (two dolls can have same height), and then arranged the dolls in a line beautifully. For each doll he noted down the number of dolls that are before this doll in the line and can contain this doll. He wrote this down on another piece of paper.

      Accidentally, the dolls fell out of line, and Robert wants to arrange them back beautifully. Given the two pieces of information (heights of the dolls and number of dolls before this in line that can contain this doll), can you rearrange the dolls beautifully?

       

      INPUT:

      First line contains T, number of test cases

      Each test case consists of 3 lines

      First line of each test case has a single number N, number of dolls.

      Second line contains array H, space separated array of size N containing the heights of dolls.

      Third line contains array C, space separated array of size N, C[i] indicating number of dolls before this in the beautiful arrangement that can contain doll i.

       

      OUTPUT:

      For each test case, output a single line containing the heights of dolls in order as they were when Robert arranged them beautifully.

      Assume that a valid solution always exists.

       

      EXAMPLE INPUT:

      2

      3

      12 13 14

      0 0 2

      3

      12 14 13

      0 1 0

       

      EXAMPLE OUTPUT:

      13 14 12

      13 12 14

       

      EXPLAINATION:

      For the first case, (arrangement 13,14,12) 13 and 14 cannot be contained by any doll prior to them, but 12 can be put in doll 13 as well as doll 14, hence the array 0 0 2

      For the second case, (arrangement 13,12,14) 12 can be contained in 13, hence the array 0 1 0

       

      CONSTRAINTS:

      1<=T<=500

      1<=N<=500

      1<=H[i]<=109

       


      Added by:Piyush Kumar
      Date:2014-01-19
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IIT Bombay Coding GC









      SPOJ Problem Set (classical)

      18095. Faridi and Yadav

      Problem code: CHOTU


      Once it happend that the two scientists(perhaps mad) Mr Yadav and Mr Faridi discovered an unusual radioactive compound named mahobanium , that decays at constant rate. And as the compund decays it looses weight.The two of them start playing a game, in which both of them sit at equal distance from a point C , one sits in west and the other in east. Being famous scientists a lot of students have come to see them(basically not to them but the compund , they had discovered) .The students have gathered around the two .The scientist also have a small robot , named CHOTU.

      Initially Mr Faridi has all the stones of mahobanium compound with him and all have equal weight. Faridi gives stones (one at a time)to CHOTU and directs him to show the compound to one of the student (who has'nt seen the compound yet) and then immediately go towards Mr Yadav.(Assume no loss of time in showing the stone to students , also CHOTU follows the shortest path while moving and always runs at same speed = 5m/s).The students , actually have placed themselves in such a way that all the stones that have reached Yadav have the same weight(Assume that radioactive decay starts as soon as it is placed in CHOTU'S hand).A child can place itself to atmost distance of X units from the centre along east or west . and to atmost distance of Y units from the centre C along north or south.

      Given test cases t ( < 1000 ) the values of X and Y (say X > Y) and (X < 1000 ) , scratch your brain to find out the maximum distance that can exist between Mr Yadav and Faridi so that above conditions are always followed.Print your answer upto 3 digits of decimal point.

      Input

      First Line has test cases t ( < 1000 )

      The next t lines has two Integers X and Y separated by space[the values of X and Y (say X > Y) and (X < 1000 )]

      Output

      Print Required answer upto 3 digits of decimal point.

      Sample Input
      1
      4 2

      Sample Output
      6.928


      Added by:Neo
      Date:2014-01-19
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      18149. Rama and Friends

      Problem code: GSHOP


      Mahesh and Ramashish are good friends. Each day Ramashish gives an array arr[0,1,2...,n-1] of size 'n' to Mahesh and asks him to modify it.
      Modifying an array means to execute the following operation exactly 'k' times:
      "Replace any array element 'x' by '-x' i.e multiply it by -1."
      Note that this operation can be performed on an array element zero,one or more times.
      But while modifying the array, Mahesh should also keep in mind that the sum of the elements of the final array should be maximum possible. Mahesh wants to go to sleep so he has to finish this job as soon as possible. Can you help him?

      Input

      First line of the input contains the number of test cases 'T'.
      Then follow 2T lines describing the test cases(Two lines for every test case).
      For each test case, First line has two space separated integers 'n'(Number of elements in the array) and 'k'(Number of times to execute the operation described above) and the next line has 'n' space separated integers in non-decreasing order which are the array elements.
      Constraints:
      1<=T<=10.
      1<=n<=100.
      1<=k<=100.
      For each 0<=i<=n-1,-10^5<=arr[i]<=10^5.

      Output

      Output T lines, one for each test case denoting the maximum possible sum which can be obtained after modifying the array.

      Example

      Input:
      1
      3 1
      -1 -1 1
      Output:
      1
      

      Added by:Mahesh Mishra
      Date:2014-01-24
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:BF C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict JAVA PAS fpc PYTH 2.7 PYTH 3.2.3 n
      Resource:My Own Problem









      SPOJ Problem Set (classical)

      18150. SHAKTIMAN AND KILWISH

      Problem code: SHAKTI


      Since very long time shaktiman and kilwish have been fighting with each other but the fight never came to end . So finally I came to rescue . I decided that the result of the fight will be decided by a mathematical game , in which I will write a number (N) . Kilwish and shaktiman will play the game alternatively and each of them would subtract a number(n) [n is less than N] such that N modulo n gives zero. The game is repeted turn by turn until the one , who now cannot make a further move looses the game

      Shaktiman being weak at mathematics asks you for help , whether or not he can win in that particular case. If Shaktimaan wins that game then print "Thankyou Shaktiman" otherwise print "Sorry Shaktiman".The game begins with shaktimaan playing first move.It is well understood that both of them will make moves in optimal way.

      INPUT

      Input contains test cases t (< 10^5) and followed by t numbers (1 <= N <= 10^6 ).

      OUTPUT

      If Shaktimaan wins that game then print "Thankyou Shaktiman" otherwise print "Sorry Shaktiman".


      Sample Input:
      2
      212
      424

      Sample Output:

      Thankyou Shaktiman
      Thankyou Shaktiman


      Added by:αqfαяι∂ι
      Date:2014-01-24
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18153. Robert Langdon & The Rule of Three

      Problem code: RLTHREE


      Many people know that when we think deeply about something, it even begins to show up in our dreams. Much like the story of structure of carbon attributed to Kekule. The rule of three has haunted Robert for weeks now, and has crept into his subconscious.
      Robert finds himself in an N dimensional space, on a cube land of N dimensions and side 1 unit. The land is haunted by the mythological hounds Gwyllgi, three of them. Each of the 2^N vertices of the cube land is hunting ground of one of the three Gwyllgi, except those vertices that are equidistant from all three. These neutral grounds are the only places where Langdon can stand on the cube. Help Langdon find these safe grounds while he thinks of his next move to escape the cube land.
      Note that the distances are Manhattan distances, the smallest distance that you need to cover if movement is restricted parallel to one of the axis. Eg, distance between (0,0,0,0) and (1,0,1,1) is 3.
      INPUT:
      Input consists of three lines, each line has a binary string of equal length (=N).
      Each string represents coordinates of a Gwyllgi in the N dimensional space, 0 meaning coordinate 0 and 1 meaning coordinate 1.
      Eg : if the input is
      001
      111
      101
      It means that in the 3D space, first Gwyllgi is at coordinate (0,0,1), second one at (1,1,1) and third one at (1,0,1)
      OUTPUT:
      Output a single line containing number of vertices of the cube land that are safe. Since the number can be large, output the value modulo 1000000007 (10^9+7)
      EXAMPLE INPUT:
      111
      001
      100
      EXAMPLE OUTPUT:
      2
      EXPLAINATION:
      Points (1,0,1) and (0,1,0) are equidistant from the three points.
      CONSTRAINST:
      2<=N<=100000

      Many people know that when we think deeply about something, it even begins to show up in our dreams. Much like the story of structure of carbon attributed to Kekule. The rule of three has haunted Robert for weeks now, and has crept into his subconscious.

      Robert finds himself in an N dimensional space, on a cube land of N dimensions and side 1 unit. The land is haunted by the mythological hounds Gwyllgi, three of them. Each of the 2N vertices of the cube land is hunting ground of one of the three Gwyllgi, except those vertices that are equidistant from all three. These neutral grounds are the only places where Langdon can stand on the cube. Help Langdon find these safe grounds while he thinks of his next move to escape the cube land.

      Note that the distances are Manhattan distances, the smallest distance that you need to cover if movement is restricted parallel to one of the axis. Eg, distance between (0,0,0,0) and (1,0,1,1) is 3.

       

      INPUT:

      Input consists of three lines, each line has a binary string of equal length (=N).

      Each string represents coordinates of a Gwyllgi in the N dimensional space, 0 meaning coordinate 0 and 1 meaning coordinate 1.

      Eg : if the input is

      001

      111

      101

      It means that in the 3D space, first Gwyllgi is at coordinate (0,0,1), second one at (1,1,1) and third one at (1,0,1)

       

      OUTPUT:

      Output a single line containing number of vertices of the cube land that are safe. Since the number can be large, output the value modulo 1000000007 (109+7)

       

      EXAMPLE INPUT:

      111

      001

      100

       

      EXAMPLE OUTPUT:

      2

       

      EXPLAINATION:

      Points (1,0,1) and (0,1,0) are equidistant from the three points.

       

      CONSTRAINST:

      2<=N<=100000


      Added by:Piyush Kumar
      Date:2014-01-25
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IIT Bombay Coding GC









      SPOJ Problem Set (classical)

      18155. abs(a-b) I

      Problem code: ABSP1


       

      Recently Mr. Kopa Samsu is learning programming. On a very renowned online judge, he
      found a
      problem:
      You are given an array of N numbers in non-decreasing order. You have to answer the
      summation of the absolute difference of all distinct pairs in the given array.
      Do you know what distinct pair means? Suppose you have an array of 3 elements: 3 5 6
      Then all the distinct pairs are:
      3 5
      3 6
      5 6
      For this problem, Mr. Kopa Samsu implemented an algorithm to find the summation of the
      absolute
      difference of all distinct pairs. His algorithm was:
      int ABS(int a[],int n)
      {
          int sum = 0;
          for (int i=1;i<=n;i++)
          {
              for (int j=i+1;j<=n;j++)
              {
                  sum += abs(a[i]a[j]);
              }
          }
      }
      After a great hard work, he finished the code. But alas!!! Frustration came around him when he
      submitted his code, the judge gave the verdict “TLE” (Time Limit Exit). “How can I get rid of
      TLE?” he thought a lot but couldn't find any way. Then suddenly, he remembered about you
      that you(his friend) is very good at programming. So, he came to you seeking your help. Can
      you help him solving this problem?

      Recently Mr. Kopa Samsu is learning programming. On a very renowned online judge, he

      found a

      problem:

      You are given an array of N numbers in non-decreasing order. You have to answer the

      summation of the absolute difference of all distinct pairs in the given array.

      Do you know what distinct pair means? Suppose you have an array of 3 elements: 3 5 6

      Then all the distinct pairs are:

      3 5

      3 6

      5 6

      For this problem, Mr. Kopa Samsu implemented an algorithm to find the summation of the

      absolute

      difference of all distinct pairs. His algorithm was:

      int ABS(int a[],int n)

      {

          int sum = 0;

          for (int i=1;i<=n;i++)

          {

              for (int j=i+1;j<=n;j++)

              {

                  sum += abs(a[i]-a[j]);

              }

          }

      }

      After a great hard work, he finished the code. But alas!!! Frustration came around him when he

      submitted his code, the judge gave the verdict “TLE” (Time Limit Exit). “How can I get rid of

      TLE?” he thought a lot but couldn't find any way. Then suddenly, he remembered about you

      that you(his friend) is very good at programming. So, he came to you seeking your help. Can

      you help him solving this problem?

       

      Input

      The input data set starts with an integer T (T<=1000), the number of test cases. Then every test

      case starts with a integer N (N<=10000), the number of elements in the array. After that, the

      next line contains N integers A[i], where 1<=i<=N and 1<=A[i]<=1000000000 & A[i] <=

      A[i+1].

      Output

      Every test case should output an integer “X”, where X is the summation of the absolute

      difference of all the distinct pair.

      Example

      Input:
      
      3
      3
      1 2 3
      3
      1 4 5
      3
      2 4 6
      
      Output:
      4
      8
      8
      Problem Set: S.M. Shaheen Sha, Raihat Zaman Neloy
      Data Set & Solution: Raihat Zamane Neloy

      Added by:Raihat Zaman Neloy
      Date:2014-01-25
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18164. Atoms in the Lab

      Problem code: ATOMS


      Mr. Yagami is a scientist in the Bhabha Atomic Research Centre. They are conducting a lab experiment on nuclear fission. In nuclear fission, one atom breaks into more than one atom of the same type.

      Initially, there are N atoms in the lab. Starting from now (t=0), after each second, every atom will break into K atoms of the same type. They don’t want the number of atoms to exceed M, so they have to stop the reaction at some time t=T. Can you find this value T for Mr. Yagami.

      Input Format:

      First line contains P, the number of test cases. Next P lines contain three integers each. These three integers represent the values of N, K and M respectively.

      Output Format:

      For each test case print the time at which the reaction will have to be stopped.

      Constraints:

      1 ≤ P ≤ 10^4
      2 ≤ N, K, M ≤ 10^18

      Sample Input:

      2
      2 2 7
      2 2 8

      Sample Output:

      1
      2

      Explanation:

      1st test case:
      at t=1, number of atoms=4
      at t=2, number of atoms will be 8.
      So reaction has to be stopped at t=1.

      2nd test case:
      at t=1, number of atoms=4
      at t=2, number of atoms will be 8.
      at t=3, number of atoms will be 16.


      Problem Setter: Lalit Kundu


      Added by:Lalit Kundu
      Date:2014-01-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18165. Coprime Pairs

      Problem code: NCOPRIME


      Mr. Yagami is playing a game of arrays. He is given two random arrays A and B consisting of N positive integer elements. Game starts by Mr. Yagami assigning 0 or 1 to each element in A and B.

      After this assignment is done, a graph is constructed with a node for each element in the array A and B (2N nodes) and no edges. The game proceeds with a valid move being defined in the following way:

      • One of the arrays from A or B is selected. From the selected array, an element which has been marked 0 is chosen. Let us call this element as X.

      • A set of elements, Y, are chosen from the array, which was not chosen in the first step, such that all elements of Y should be marked as 1 and all elements of Y should be greater than X and no element of Y should be coprime to X.

      • Finally an edge is drawn from the node labelled X to all the nodes corresponding to the elements in set Y. There can only be a single edge between any 2 nodes in the graph.

      He can make as many valid moves. Mr. Yagami receives 1 point for each edge that is drawn in the graph.

      Mr. Yagami is very clever, so he makes the initial assignment in such a way that it maximizes the number of points he receives in the game. You have to return the maximum number of points that Mr. Yagami can receive.

      Input Format:

      The first line of the input contains a single integer, N (1 ≤ N ≤ 40)
      The second line of input contains N integers separated by a single space character, which represent the elements of the array A. (2 ≤ A[i] ≤ 10^9)
      Similarly, the last line of input also contains N integers separated by a single space character, which represent the elements of the array B. (2 ≤ B[i] ≤ 10^9)

      Output Format:

      A single integer representing the maximum score which Mr. Yagami can receive.

      Sample Input:

      4
      16 3 2 9
      12 18 13 4

      Sample Output:

      8

      Explanation:

      He picks 2 from first array. So he gets to put 3 edges ie. 2->4, 2->12, 2->18.
      Next he picks 3 from the first array. So he gets to put 2 edges ie. 3->12, 3->18.
      Next he picks 9 from the first array. So he gets to put 2 edges ie. 9->12, 9->18.
      Next he picks 16 from the first array. So he gets to put 1 edge ie. 16->18. Total edges=8.


      Problem Setter: Lalit Kundu


      Added by:Lalit Kundu
      Date:2014-01-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18167. SubXor

      Problem code: SUBXOR


      A straightforward question. Given an array of positive integers you have to print the number of subarrays whose XOR is less than K.
      Subarrays are defined as a sequence of continuous elements Ai, Ai+1, ..., Aj . XOR of a subarray is defined as Ai^Ai+1^ ... ^Aj.
      Symbol ^ is Exclusive Or. You can read more about it here:
      http://en.wikipedia.org/wiki/Exclusive_or

      Input Format:

      First line contains T, the number of test cases. Each of the test case consists of N and K in one line, followed by N space separated integers in next line.

      Output Format:

      For each test case, print the required answer.

      Constraints:

      1 ≤ T ≤ 10
      1 ≤ N ≤ 10^5
      1 ≤ A[i] ≤ 10^5
      1 ≤ K ≤ 10^6
      Sum of N over all testcases will not exceed 10^5.

      Sample Input:

      1
      5 2
      4 1 3 2 7	

      Sample Output:

      3

      Explanation:

      Only subarrays satisfying the conditions are [1],[1,3,2] and [3,2].


      Problem Setter: Lalit Kundu


      Added by:Lalit Kundu
      Date:2014-01-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18168. Entangled Circles

      Problem code: TWOCIR


      The description of this problem is extremely simple. You are given 2 non-intersecting circles in 3-dimensional world. Each of the circle is defined by 3 non - collinear points lying on the circle. All you have to return is whether the circles are entangled or not (just like two links of a chain). Two circles are entangled if they cannot be separated from each other without breaking any of the circles.

      Input Format:

      The first line contains a single integer, T, the number of test cases. Each of the T test cases are defined by 2 lines. The first line of each test case contains 9 integers representing the 3 points as (x1, y1, z1), (x2, y2, z2), (x3, y3, z3) which define the first circle. Similarly, the second line for each test case contains 9 integers representing the 3 points which define the second circle.

      Output Format:

      For every query output "YES" without quotes if the circles are entangled and "NO" otherwise (quotes for clarity).

      Constraints:

      1 ≤ T ≤ 100
      -10000 ≤ Each Coordinate in the Input ≤ 10000

      Sample Input:

      1
      0 1 0 1 0 0 0 -1 0
      0 0 0 1 0 -1 1 0 1

      Sample Output:

      YES


      Problem Setter: Lalit Kundu


      Added by:Lalit Kundu
      Date:2014-01-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18170. Takeover Wars

      Problem code: TKV1000


       

      You are studying a takeover war between two large corporations, Takeover Incorporated and Buyout
      Limited. Each of these corporations controls a number of subsidiaries. The aim in this war is simply
      to drive the competition out of the market. There are N subsidiaries of Takeover Incorporated and M
      subsidiaries of Buyout Limited, and you know the market value of each subsidiary.
      Each company can designate one of its subsidiaries to perform a takeover. The takeover can either be
      friendly or hostile. A friendly takeover means a subsidiary of a corporation merges with a different
      subsidiary of the same corporation. The market value of the merged subsidiary is the sum of the market
      values of the constituent subsidiaries. There is no constraint on the relative sizes of the subsidiaries
      participating in a friendly takeover.
      A hostile takeover means a subsidiary A of a corporation attempts to take over a subsidiary B of the
      other corporation. For this to succeed, the market value of A has to be greater than the market value of
      B. After this move, B disappears from the market. The market value of A does not change (the gain of
      incorporating B’s assets is offset by the monetary cost of the takeover). For simplicity we assume that
      no sequence of moves leads to two subsidiaries of different corporations having the same market value.
      The companies take turns making moves in this takeover war, with Takeover Incorporated going first.
      A company will do nothing on its turn only if it cannot make a takeover. A company loses the takeover
      war if all its subsidiaries are taken over.
      Your aim is to learn which company can guarantee a victory from this war. In the first case of the
      sample data, Takeover Incorporated can simply take over one of the companies of Buyout Limited in
      its first move with the 7-value subsidiary. Then it will lose one of its small (1-value) subsidiaries to a
      hostile takeover, and then it will take over the second subsidiary of Buyout Limited. In the second case,
      Takeover has to make a friendly takeover in its first move. Buyout Limited will join its two subsidiaries
      into a single company with market value 10. Takeover will have to make a friendly takeover again
      (as again it will not have a large enough subsidiary to take over Buyout’s giant). Now Takeover will
      have two subsidiaries, valued either 9 and 3 or 6 and 6. In either case, Buyout takes over one of these
      subsidiaries, Takeover has to pass, and Buyout takes over the other one.

      You are studying a takeover war between two large corporations, Takeover Incorporated and Buyout

      Limited. Each of these corporations controls a number of subsidiaries. The aim in this war is simply

      to drive the competition out of the market. There are N subsidiaries of Takeover Incorporated and M

      subsidiaries of Buyout Limited, and you know the market value of each subsidiary.

       

      Each company can designate one of its subsidiaries to perform a takeover. The takeover can either be

      friendly or hostile. A friendly takeover means a subsidiary of a corporation merges with a different

      subsidiary of the same corporation. The market value of the merged subsidiary is the sum of the market

      values of the constituent subsidiaries. There is no constraint on the relative sizes of the subsidiaries

      participating in a friendly takeover.

       

      A hostile takeover means a subsidiary A of a corporation attempts to take over a subsidiary B of the

      other corporation. For this to succeed, the market value of A has to be greater than the market value of

      B. After this move, B disappears from the market. The market value of A does not change (the gain of

      incorporating B’s assets is offset by the monetary cost of the takeover). For simplicity we assume that

      no sequence of moves leads to two subsidiaries of different corporations having the same market value.

      The companies take turns making moves in this takeover war, with Takeover Incorporated going first.

      A company will do nothing on its turn only if it cannot make a takeover. A company loses the takeover

      war if all its subsidiaries are taken over.

       

      Your aim is to learn which company can guarantee a victory from this war. In the first case of the

      sample data, Takeover Incorporated can simply take over one of the companies of Buyout Limited in

      its first move with the 7-value subsidiary. Then it will lose one of its small (1-value) subsidiaries to a

      hostile takeover, and then it will take over the second subsidiary of Buyout Limited. In the second case,

      Takeover has to make a friendly takeover in its first move. Buyout Limited will join its two subsidiaries

      into a single company with market value 10. Takeover will have to make a friendly takeover again

      (as again it will not have a large enough subsidiary to take over Buyout’s giant). Now Takeover will

      have two subsidiaries, valued either 9 and 3 or 6 and 6. In either case, Buyout takes over one of these

      subsidiaries, Takeover has to pass, and Buyout takes over the other one.

       

       

      Input

      Each test case is described by three lines of input. The first line contains two numbers 1 ≤ N ≤ 10 5 and

      1 ≤ M ≤ 10 5 denoting respectively the number of subsidiaries of Takeover Incorporated and Buyout

      Limited. The next line lists the N sizes a i of the subsidiaries of Takeover Incorporated (1 ≤ a i ≤ 10 12 ),

      and the third line lists the M sizes b j of the subsidiaries of Buyout Limited (1 ≤ b j ≤ 10 12 ).

      Output

      For each test case, display the case number and either the phrase Takeover Incorporated or the

      phrase Buyout Limited depending on who wins the takeover war if both corporations act optimally.

      Example

      Input:
      3 2
      7 1 1
      5 5
      4 2
      3 3 3 3
      5 5
      Output:
      Case 1: Takeover Incorporated 
      Case 2: Buyout Limited

      Added by:Konrad Krystecki
      Date:2014-01-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:http://icpc.baylor.edu/worldfinals/problems









      SPOJ Problem Set (classical)

      18174. REAL ROOTS

      Problem code: RROOT


       

      Anurag is not so good at probability,infact he tends to avoid any probability questions.Bhavik being his friend knows this and also knows that Anurag is excellent with quadratic equations.
      In order to help he gives Anurag a quadratic equation of the form x^2+2*b*x+c=0 and asks him to find the probability that the given equation has real roots.
      To make this question non-trivial he gives Anurag,side of the square centered at origin assuming values of b and c will not go outside that square given.
      Help Anurag to find the probability?

      Anurag is not so good at probability,infact he tends to avoid any probability questions.Bhavik being his friend knows this and also knows that Anurag is excellent with quadratic equations.

      In order to help he gives Anurag a quadratic equation of the form x^2+2*b*x+c=0 and asks him to find the probability that the given equation has real roots.

      To make this question non-trivial he gives Anurag,side of the square centered at origin assuming values of b and c will not go outside that square given.

      Help Anurag to find the probability?

       

      Input

      First line contains a number of test cases T(<25).Next T lines contain the side of the square S(<=1000000).

      Output

      Output the required probability in new line for each case upto 6 decimal places.

      Example

      Input:
      1
      8
      
      Output:
      0.833333
      

      Added by:Bhavik
      Date:2014-01-26
      Time limit:0.300s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18175. TENNIS CHAMPIONSHIP

      Problem code: TENNIS1


      N (2<=N<=10^18) players take part in tennis championship. In every match loser is out. Two players can play a game if in that moment the difference of played games of that two players is not more than 1. They are interested, how many matches will be in the champioship (maximal possible number) and what's the maximal possible number of games in which can take part the champion in that case.

      Input

      Single number N.

      Output

      Two numbers - answers to the questions.

      Example

      Input:
      4
      
      Output:
      2 3
      

      Added by:Albert Gevorgyan
      Date:2014-01-26
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      18176. FRIENDSHIP!!!

      Problem code: FRND


      Q[b] has recently been visited by extraterrestrials from planet Quan_Lank , where everyone’s name is a positive integer. All residents of the planet know each other. Two Quan_Lank-ians calculate the strength of their friendship by converting their names to binary, aligning them one under the other, and writing a digit in each column: 0 if the two binary digits in that column are equal, 1 if they differ. The binary result is then converted back to the decimal system.

      For example, the friendship value of 19 and 10 equals 25:

      1   0   0   1   1 = 19

      0   1   0   1   0 = 10

      -------------------

      1   1   0   0   1 = 25

       

      The value of a planet in the Universe is defined as the sum of all friendship values. Q[b] has asked you to help him compute the value of planet Quan_Lank!

       

      INPUT

      The first line of input contains the positive integer N (the number of residents of planet Quan_Lank , 1<=N<=10^6).
      The next N lines contain the names of residents - positive integers smaller than 10^6, one per line.

      OUTPUT

      The only line of output must contain the value of planet Quan_Lank.

      SAMPLE

      Input
      2
      19
      10
      Output
      25

      Input

      3
      7
      3
      5
      Output
      12

      Second sample description: The friendship value of residents 1 and 2 equals 4, for residents 1 and 3
      it equals 2, and for residents 2 and 3 it equals 6. The solution is 4 + 2 + 6 = 12.


      Added by:[bLanK]
      Date:2014-01-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18182. Naughty and Balls

      Problem code: NAUGHTY


      Mr. Naughty likes to play with balls. So his friend, Mr Nice, gave him n balls to play a game. Each ball has exactly two numbers (the number on the top and the number on the bottom). In one move Mr Naughty can rotate any ball so that its bottom now becomes the top. Mr Nice knows the minimum number of such moves that can make at least half of the balls show same number on their top. So to win Mr Nice's game, Mr Naughty should figure out the minimum number of moves. Its not always possible to make such moves that satisfy the given condition.In this case Mr Naughty should figure out that it is "Impossible" to make such moves.

      Help Mr Naughty to win the game.

      Input Format:

      The first line contains a single integer n - the number of balls. The following n lines contain the description of all balls, one ball per line. Each description has a pair of non-negative integers not exceeding 10^5 - numbers on top and bottom. The first number in a line is the number on top, the second one - on the bottom. The number on the top of the ball may be same as the number on the bottom.
      The numbers in the lines are separated by single spaces.

      Output Format:

      On a single line print a single integer - the minimum number of moves to win the game. If it is impossible to make the set funny, print "Impossible" (quotes for clarity).

      Constraints:

      1 ≤ n ≤ 10^5

      Sample Input:

      3
      3 100
      100 3
      5 4

      Sample Output:

      1

      Explanation:

      In this case Mr Naughty can rotate the first ball so that number on the top becomes 100. Since two of the three balls have same number on their top (100), you do not need to change anything else, so the answer is 1.

      Sample Input:

      5 
      5 9
      5 9
      3 2
      1 4
      5 7

      Sample Output:

      0

      Sample Input:

      3
      1 2
      3 4
      5 6 

      Sample Output:

      Impossible


      Problem Setter: Prateek Sachdev


      Added by:Lalit Kundu
      Date:2014-01-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18183. Drunk Game

      Problem code: DRUNK


      Alice and Bob were getting bored and decided to play a game. The game involves a pile of coins. Both players take turns in picking a certain number of coins from the pile. Initially, the pile contains N coins. Alice makes the first move. The player who is unable to pick up any coins in his/her turn loses the game. Some of the details of the game are:


      1. In each turn a player can only decide on picking up 1, 4, 9, 16 coins from the pile.

      2. As both the players are drunk and not in complete control of their actions, even if they decide on picking up some coins, they might end up picking something else completely. So, if a person decides on picking up X coins from the pile, he/she might end up with (X - 1), X or (X + 1) coins with the relative probability of C1: C2: C3

      3. In each turn a player has to eventually pick up at least 1 coin.


      Note that a player cannot decide on picking up X coins from the pile if the pile contains less than X coins at the time. Also, if a player decided on picking up X coins and it happens that picking up (X + 1) is not valid (This might happen if there are only X coins in the pile), then the relative probability distribution for the valid moves will be C1: C2. Similarly, if picking up (X - 1) coins is not valid, then the relative probability distribution for the valid moves will be C2: C3.

      As both of them are not in their right minds, they sometimes want to win and sometimes want to lose. But Bob still wonders what is his probability of winning/losing the game (depending on what he wants for a particular game). Help him find out his probability!

      Input Format:

      The first line of the input contains a single integer, T, which represents the number of test cases. Each test case contains 3 lines. The first line of each test contains a single integer, N, which represents the number of coins in the pile initially. The second line contains 3 integers C1, C2 and C3. The last line of each test contains 2 integers describing the mood of Alice and Bob respectively. 0 is for losing and 1 is for winning.

      Output Format:

      For each test cases, the probability of winning/losing (depending on the test case) rounded to 4 places of precision.

      Constraints:

      1 ≤ T ≤ 10
      1 ≤ N ≤ 1000000
      1 ≤ (C1,C2,C3) ≤ 100000

      Sample Input:

      2
      1
      1 2 3
      0 0
      5
      1 2 3
      0 1

      Sample Output:

      1.0000
      0.4333


      Problem Setter: Sukhjashan Singh


      Added by:Lalit Kundu
      Date:2014-01-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18184. Durins Day

      Problem code: DURIN


      Reference:: The Hobbit : Desolation of Smaug
      The_Hobbit:_The_Desolation_of_Smaug


      J. R. R. Tolkien decided to make Thorin Oakenshield’s task more difficult. This time he was given an infinite number of keys represented by a small string. The hidden entrance has a lot of keyholes side by side represented by one long string. The key fits only into a slit that matches it completely. Oakenshield does not know how many keys he would require and which all keyholes he will have to try out. So if there are n keyholes where the key fits, he might need any number of keys between 1 to n (both inclusive). Moreover he does not know which keyholes among the ones where the keys fit, he will have to use. All he knows is that there is a unique way to open the door. Trying out each configuration takes 1 second. The last light of Durin’s day does not last long and will have to try out all possibilities before it goes. He wants you to find out how long, in the worst case, it will take for him to try out all possibilities.

      Since the answers may be huge, output it modulo 1000000007. If there are no keyholes where the key fits, output 0.

      Input Format:

      First line containing a string representing the key. Second line containing a string representing the keyholes.

      Output Format:

      Single line containing an integer for the required answer.

      Notes:

      1. Key fits into a keyhole at index i if key is a substring of keyhole string at index i.
      2. If there are two overlapping keyholes where the key may fit, you cannot insert a key in both simultaneously

      Constraints:

      1 ≤ key ≤ 10^4
      1 ≤ keyholes ≤ 5*(10^5)

      Sample Input:

      c
      a	

      Sample Output:

      0

      Sample Input:

      aba
      abababa

      Sample Output:

      4

      Explanation:


      Explanation for Test Case #1:
      The key fits into keyholes at positions {1, 3, 5}
      If he requires only 1 key he may put them at {1} or {3} or {5} = 3 seconds.
      If he required 2 keys, he may put them at {1,5} = 1 second.
      Total = 1+3 = 4 seconds.
      He cannot use 3 keys without overlapping them.

      Explanation for Test Case #2:
      There is no slit where the key fits hence 0 seconds.



      Problem Setter: Vidit Gupta


      Added by:Lalit Kundu
      Date:2014-01-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18185. Give Away

      Problem code: GIVEAWAY


      You are given a 1-indexed array X, consisting of N integers, and a set of Q queries.
      There are two kinds of queries:
      1. 0 a b c
      Here you are required to return the number of elements with indices in [a,b]
      greater than or equal to c
      2. 1 a b
      Here you are required to change the ath element of array to b.

      Input Format:

      First line contains N, the number of elements in the array X. The next line contains N space separated integers representing the elements of X. The third line of input contains a single integer, Q, the number of queries. The next Q lines of input each contain queries of two kinds as described above.

      Output Format:

      Q lines with the ith line contains the answer for the ith query

      Constraints:

      1 ≤ N ≤ 5*10^5
      1 ≤ Q ≤ 10^5
      1 ≤ X[i] ≤ 10^9
      1 ≤ a ≤ b ≤ N for query type 0
      1 ≤ a ≤ 10^5, 1 < b ≤ 10^9 for query type 1
      1 ≤ c ≤ 10^9

      Sample Input:

      5
      1 2 3 4 5
      3
      0 1 5 10
      1 2 20
      0 1 3 10

      Sample Output:

      0
      1


      Problem Setter: Pulkit Goel and Vidit Gupta


      Added by:Lalit Kundu
      Date:2014-01-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18186. Machine Mayhem

      Problem code: MACHMAY


      It's the year 4224 and Giant Machine Corporation has started working on it’s 42nd Generation Robots. These robots are designed to have peculiar specifications.

      The company has N different parts (numbered from 1 to N), each of which impart a very specific property to the robot. The formation of a single robot R consists of M steps. At the ith step, one of the N parts is chosen and added to the current robot. After the Mth step, the robot is ready. Let num(i, j) be the count of part number j till the ith step used for making the robot R.

      The 41st Generation Robots were found to be defective in the sense that one of their properties overshadowed their other properties significantly. Hence, for the 42nd Generation, it was decided that for any robot R, |num(i, j) – num(i, k)| ≤ 2 for every 1 ≤ i ≤ M and for every pair of j, k where 1 ≤ j,k ≤ N .

      Now, the Giant Machine Corporation is interested to know the number of different 42nd Generation Robots that they can make which satisfy the above criteria and hence they have hired you for the task. Since, this number can be very large, output the result modulo 10^9 + 7.

      Note : Two robots R1 and R2 are considered different, if a different part is used in any of the corresponding i steps out of M steps.

      Input Format:

      The first line starts with an integer T, denoting the number of test cases. T lines follow with each line consisting of two space separated integers M and N.

      Output Format:

      For each test case, print in a single line the required number.

      Constraints:

      1 ≤ T ≤ 20
      1 ≤ N ≤ 50
      1 ≤ M ≤ 10^18

      Sample Input:

      3
      1 1
      2 2
      3 2

      Sample Output:

      1
      4
      6


      Problem Setter: Vivek Hamirwasia


      Added by:Lalit Kundu
      Date:2014-01-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18187. Ingredients

      Problem code: INGRED


      You are given n cities with m bi-directional roads connecting them and the length of each road. There are two friends living in different cities who wish to collect some ingredients available at different stores to make cake. There are s such stores. They need not come back home after purchasing the ingredients. Petrol is expensive and they would hence like to travel minimum total distance (sum of distance distance traveled by both kids). Help them find out what this distance is.

      Input Format:

      n m
      (m lines of the form ai bi ci)
      Here n is number of cities, m is number of roads, ai and bi are the cities(0 indexed) the roads connect and ci is the length of this road
      s where s is the number of stores
      (1 line containing s space separated integers indicating the city number in which the stores are located.)
      (two space separated integers indicating the cities in which the two kids live)

      Output Format:

      Single integer x where x is the minimum distance that the duo will travel that is minimum sum of distance travelled by first kid and second kid.

      Constraints:

      2 ≤ n ≤ 100
      1 ≤ m ≤ (n*(n-1))/2
      0 ≤ a,b < n
      0 ≤c≤ 1000
      1 ≤ s ≤ 8

      Sample Input:

      5 6
      0 1 5
      1 4 1
      0 4 10
      0 2 2
      1 2 3
      2 3 4
      2
      2 4
      0 1

      Sample Output:

      3


      Problem Setter: Vidit Gupta


      Added by:Lalit Kundu
      Date:2014-01-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18188. Queen and Stable Relationships

      Problem code: QSTABLE


      Swayamvara, in ancient India, was a practice of choosing a husband, from a list of suitors by a girl of marriageable age.

      It is the swayamvara of gossip queen of IIIT, Akshata. Now, Akshata is always interested in knowing the stability of the relationships among various students of IIIT. Nowadays she is very busy in her swayamvara’s preparation and is not able to update herself about the latest gossips. As you know she is the gossip queen. She would love if someone could do her a favor and collect answers of her questions about relationships in IIIT. It might increase the collector’s chance of getting selected for marriage.

      Before starting preparations for the swayamvara, Akshata used to maintain notes about the relationships in IIIT and knew all about them. So she thought she can help you by providing the notes.

      There are various ways in which two people can be acquaintances :

      1. If A and B are in a relationship, then A and B are acquaintances of each other.
      2. If A and B are acquaintances of each other and B and C are acquaintances of each other, then A and C are also acquaintances of each other.

      In Akshata's notes, a relationship between person1 and person2 is represented as "person1 person2". The Queen's questions are also special.

      There are two types of questions:

      1. First type of query is whether two people, say A and B, still remain each others’ acquaintances even if two people, say C and D, break-up and end their relationship.
      2. Second type of query is whether two people, say A and B, still remain acquaintances even if a person, say C, leaves the college (It’s obvious that before leaving college, C ends all his/her relationships).


      Input Format:

      First line of the input contains two integers, N and M where N represents the number of people in IIIT and M represents the number of relationships in Akshata’s notes.

      The next M lines contain 2 strings each, containing the names of 2 people who are in a relationship.

      Next line contains a single integer Q, which represents the number of questions asked by the Queen. Each of the next Q lines represents a query. For every query first integer represents the query type.

      If the query type is 1 then it is followed by four strings in the same line, representing A B C and D. you have to output "STABLE" if A and B remain acquaintance of each other even if C and D break up and "NOT STABLE" otherwise.

      If the query type is 2 then it is followed by three strings in the same line, representing A B and C. You have to output "STABLE" if A and B remain acquaintances even if C leaves college otherwise output "NOT STABLE". (All quotes for clarity)

      Output Format:

      For every query output "STABLE" or "NOT STABLE" without quotes.

      Constraints:

      1 ≤ N ≤ 10000
      1 ≤ M ≤ 50000
      1 ≤ Q ≤ 10000
      Size of all strings will be less than 50 characters.

      Sample Input:

      3 2
      Person1 Person2
      Person1 Person3
      2
      2 Person2 Person3 Person1
      1 Person1 Person2 Person1 Person3

      Sample Output:

      NOT STABLE
      STABLE

      Explanation:

      Person1 is in a relationship with Person2 and Person1 is also in a relation with Person3. So Person3 and Person2 are acquaintance.
      First Query:
      But Person2 and Person3 are acquaintance of each other only because of person1, if person1 leaves the college, then Person2 and Person3 are also not acquaintance of each other.
      Second Query:
      Person1 will remain being acquaintance of Person2 even if Person1 breaks-up with Person3.

      Sample Input:

      17 18
      Person1 Person2
      Person1 Person4
      Person2 Person4
      Person4 Person6
      Person2 Person6
      Person2 Person3
      Person3 Person5
      Person1 Person7
      Person7 Person8
      Person7 Person9
      Person7 Person10
      Person9 Person12
      Person8 Person12
      Person8 Person11
      Person12 Person13
      Person14 Person15
      Person15 Person16
      Person16 Person17
      8
      2 Person1 Person14 Person7
      2 Person1 Person2 Person2
      1 Person1 Person14 Person2 Person4
      1 Person5 Person13 Person1 Person2
      1 Person6 Person2 Person1 Person4
      1 Person13 Person6 Person7 Person8
      2 Person13 Person6 Person7
      2 Person13 Person6 Person8
      2 Person13 Person8 Person7

      Sample Output:

      NOT STABLE
      NOT STABLE
      NOT STABLE
      STABLE
      STABLE
      STABLE
      NOT STABLE
      STABLE


      Problem Setter: Mayank Natani


      Added by:Lalit Kundu
      Date:2014-01-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18201. RK Sorting

      Problem code: RKS


      RK is a great code breaker. He knows any cipher in the world can be broken by frequency analysis. He intercepted an enemy message. The message consists of N numbers, smaller than or equal to C. RK belives freqency analysis consists of sorting this sequence so that more frequent numbers appear before less frequent ones.

      Formally, the sequence must be sorted so that given any two numbers X and Y , X appears before Y if the number of times X appears in the original sequence is larger than the number of time Y does. If the number of appearances is equal, the number whoes value appears sooner in the input should appear sooner in the sorted sequence.
      Help RK by creating a "frequency sorter".

      INPUT

      First line of input contains two integers, N (1<=N<=1000), length of message, and C (1<=C<=10^9), the number from task description. Next line contains N integers smaller than or equal to C, message itself.

       

      OUTPUT

      First and only line of output should contain N numbers, the sorted sequence.

      SAMPLE

      Input
      9 3
      1 3 3 3 2 2 2 1 1
      Output
      1 1 1 3 3 3 2 2 2

      Input
      5 2
      2 1 2 1 2
      Output
      2 2 2 1 1


      Added by:[bLanK]
      Date:2014-01-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18202. HUGE GCD

      Problem code: HG


      RK has received a homework assignment to compute the greatest common divisor of the two positive integers A and B. Since the numbers are quite large, the professor provided him with N smaller integers whose product is A, and M integers with product B.

      RK would like to verify his result, so he has asked you to write a program to solve his problem. If the result is more than 9 digits long, output only the last 9 digits.

      INPUT

      The first line of input contains the positive integer N (1<= N<= 1000).
      The second line of input contains N space-separated positive integers less than 10^9, whose product is the number A.
      The third line of input contains the positive integer M (1 <=M <= 1000).
      The fourth line of input contains M space-separated positive integers less than 10^9, whose product is the number B.

       

      OUTPUT

      The first and only line of output must contain the greatest common divisor of numbers A and B. If the result is more than 9 digits long, output only the last (least significant) 9 digits.

      SAMPLE

      Input
      3
      2 3 5
      2
      4 5
      Output
      10

      Input
      3
      358572 83391967 82
      3
      50229961 1091444 8863
      Output
      000012028

      First sample description: The greatest common divisor of numbers A = 30 and B = 20 equals 10.


      Added by:[bLanK]
      Date:2014-01-28
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18240. GENIE SEQUENCE

      Problem code: KURUK14


      A Genie Sequence is a sequence in which every element indicates the number of elements present before or after it. Given an array of numbers, find whether you can form a Genie sequence or not.

      Input

      First line contains a single integer T, the number of test cases. It is followed by T cases each of which contains two lines. First line of each test case contains a single integer N. The next line contains N integers separated by a single space.

             Output

      For each test case output a single line containing "YES" (without quotes) if it is possible to form a genie sequence or "NO" (without quotes) if it is not possible.


      Constraints

      1<=T<=20

      2<=N<=1000

      1<=ai<=10^3

      Example

      Input:

      1

      4

      1 3 3 2


      Output:

      YES


      Explanation for the test case :

      The Genie sequence is {3,1,2,3}. The first element '3' in the sequence indicates that three numbers are after it, the 2nd element '1' indicates that one number if before it, the 3rd element '2' indicates that two elements are before it and the last element indicates that three elements are before it. So the answer is YES.


      Added by:785227
      Date:2014-01-31
      Time limit:0.050s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict JAVA PERL PYTH 2.7 PYTH 3.2.3
      Resource:Kurukshetra Onsite Programming Contest









      SPOJ Problem Set (classical)

      18243. Maggu and Strings

      Problem code: IITWPC4A


      Maggu and Coder were playing a game with strings. In each turn of the game, Maggu gives Coder a string. Coder can replace m consecutive 'a' in the string by n consecutive 'b' any number of times. This way he has to create 2 strings, one of maximum possible length and one of minimum possible length.

      Maggu and Coder were playing a game with strings. In each turn of the game, Maggu gives Coder a string. Coder can replace m consecutive 'a' in the string by 
      n consecutive 'b' any number of times. This way he has to create 2 strings, one of maximum possible length and one of mimimum possible length. 
        

       

      Input

      First line of input contains a single integer T : number of test cases.(1<=T<=100).
      For each test case there are exactly two lines.
      First line contains a string s (1 <= length(s) <= 10^5) containing letters only from 'a' to 'z'.
      Second line contains two space separated integers representing m and n respectively.(1 <= m,n <= 10^5).
      Sum of length(s) over all test cases is <= 10^6. 

      Output

      For each test case, print in a single line containing two space separated integers representing minimum and maximum length of string s that Coder can obtain.

      Example

      Input:
      3
      abc
      1 2
      aa
      1 2
      aba
      1 1 Output: 3 4
      2 4
      3 3

      Explanation

      For the first test case, you can convert abc to abc (by not changing at all), bbbc (changing 'a' to 'bb'). minimum length of s is 3 and maxium length is 4.


      Added by:praveen123
      Date:2014-01-31
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18245. Maggu and Triangles

      Problem code: IITWPC4B


      Maggu has a wire of length n. He has to make triangles out of it such that the side lengths of each triangle are integers. He now wants to know the number of distinct (not congruent) triangles that he can create using the wire of length n. Note that he has to use all of the wire in making the triangle.

      Input

      First line contains T: number of test cases. (1 <= T <= 10^5)
      For each test case, there is a single line containging an integer n (n >= 1 && n <= 10^9)

      Output

      Each test case output a single integer representing the number of triangles he can create.

      Example

      Input:
      3
      5
      7
      9 Output:
      1
      2
      3

      Added by:praveen123
      Date:2014-01-31
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18246. Maggu and Vectors

      Problem code: IITWPC4C


      Maggu was teaching vectors using triangle diagrams to to his little brother. Now in the midst of lesson he went for a coffee and on returning finds all his triangles disassembled into constituent vectors by his naughty brother. He needs to recreate the triangles. He needs your help in doing this task quickly as he has to go for an internship interview.

      Input

      First line will contain T (1 <= T <= 10), the number of test cases. Each test case will consist of first line N, number of vectors. Next line will contain N (1 <= N <= 1000)  vectors of the form of a b  -1000<=a,b<=1000. 

      Output

      You have to print, in a new line for every test case,  “YES”  if any 3 vectors among N form a triangle, “NO” otherwise.

      Example

      Input:
      

      3 5

      3 4 3 -4 5 0 6 0 3 5

      2

      4 5 -4 -5

      3

      1 2 3 4 -5 -6

      Output:

      YES

      NO NO


      Added by:praveen123
      Date:2014-01-31
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18247. Arrangement Validity

      Problem code: IITWPC4D


      n persons are standing in a line. Height of each person is between 1 and n and height of each person is distinct. 

      You a given array A where A[i] denotes how many persons are before i_th person having heights greater than H[i]. eg. For person 2, person 1 is considered before him. If A is given to be [0, 1] then one valid arrangements of height could be [2, 1] as number of persons having height > 1 before 2 are 1 because H[1] > H[2]

      You have to find out whether this array can be valid for some arrangement of persons. If you can uniquely do so, then find out the array H. Otherwise output -1.

      Input

      First line contains T : number of test cases. (1 <= T <= 20).

      For each test First line contains an integer n. ( 1 <= n <= 10^5)

      Next line contains n space seperated integers denoting A[i]. (0 <= A[i] <= n)

      Output

      For each test case output single line 

      If there is a unique way of H. Then print n space seprated integers in the line.

      Otherwise output -1.

      In starting of each test case also put "Test : testNumber" (without quotes). Note that there is a space before colon and one space after colon.

      Example

      Input:
      2
      3
      0 1 1
      3
      0 1 0 
      Output:
      Test : 1
      3 1 2
      Test : 2
      2 1 3

      Added by:praveen123
      Date:2014-01-31
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18248. Maggu’s Solar Panels

      Problem code: IITWPC4E


      Summer is here and so is the season of powercuts, everybody here in IITK has installed there own solar panels over the roof. Now while setting panels, nobody cared of there panel was overlapping with others, the end result looks something likes the one shown below.  


      Clearly, a panel cannot produce electricity from the part where light does not fall. Our Maggu has been given the task of estimating the total electricity output from panels from Hall Office. This task is haunting him. Even Coder cannot do it alone, he needs your help. Assume that all panels produce the same power per unit area and that the area not directly under the sun does not produce any electricity.


      You need to print the power that will be produced given the end points of rectangular panels and the power per unit area that panels produce.


      Note : The sides of the panel will be parallel to the X-axis or Y-axis. Meaning, panels will never be tilted. Hence, a panel can be represented by 4 integers x, y, X and Y. Where (x,y) is the co-ordinate of the bottom left corner of the panel and (X,Y) is the co-ordinate of the top right corner of the panel.


      Input

      First line contains two space separated integers N, number of solar panels and R, power per unit area. Next N lines contains the description of N panels. Each line containing 4 space separates integers x, y, X and Y respectively.

      Output

      You need to output a single integer, the total power that can be generated.

      Constraints

      -10^8<=x<=X<=10^8

       -10^8<=y<=Y<=10^8

      1<=N<=100000

      1<=R<=100

      Example

      Input:
      

      3 2

      -6 0 3 6

      0 4 6 10

      4 -2 9 6

      Output:
      240

      Added by:praveen123
      Date:2014-01-31
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18249. Gopu and the Grid Problem

      Problem code: IITWPC4F


      Gopu is interested in the integer co-ordinates of the X-Y plane (0<=x,y<=100000). Each integer coordinate contain a lamp, initially all the lamps are in off mode. Flipping a lamp means switching it on if it is in off mode and vice versa. Maggu will ask gopu 3 type of queries.


       

      Type 1:  x l r,  meaning: flip all the lamps whose x-coordinate are between l and r (both inclusive) irrespective of the y coordinate.


       

      Type 2:  y l r, meaning: flip all the lamps whose y-coordinate are between l and r (both inclusive) irrespective of the x coordinate.


       

      Type 3: q x y X Y, meaning: count the number of lamps which are in ‘on mode’(say this number be A) and ‘off mode’ (say this number  be B) in the region where x-coordinate is between x and X(both inclusive) and y-coordinate is between y and Y(both inclusive).

      Input

      First line contains Q-number of queries that maggu will ask to gopu. (Q <= 10^5)

       

      Then there will be Q lines each containing a query of one of the three type described above.

      Output

      For each query of 3rd type you need to output a line containing one integer A.

      Example

      Input:
      

      3

      x 0 1

      y 1 2

      q 0 0 2 2

      Output: 
       4

      Added by:praveen123
      Date:2014-01-31
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18261. Maggu and Weird things

      Problem code: IITWPC4G


      Maggu is a weird guy. Whenever he gets bored, he starts playing weird games. As he is an odd boy, he likes to play only with arrays of even length n. Maggu cannot play with large numbers, so he will do all the operations modulo 10^9 + 7.

      He likes performing "weird operations" on the array very much. A Weird Operation#1 on an array seq[] is defined as follows: 

      tempSeq[n] ; //is a temporary array

      for (i = 0; i < n; i++)  {

           int cnt = 0;

          for (cnt = 0; cnt < k; cnt++) {

              int j = (i + cnt) % n;

              if (cnt % 2 == 0) tempSeq[i] += seq[j];

              else tempSeq[i] -= seq[j];

           }

      }

      for (int i = 0; i < n; i++) seq[i] = tempSeq[i];


      Weird operation#2 is even more cooler than this. In this operation, he swaps the adjacant entries of the array.

      Pseudo code is as follows:


      for (int i = 0; i < n; i += 2) swap (seq[i], seq[i + 1]);


      A "Super Weird operation" is applying weird operation#1 followed by weird operation#2 on the array seq[] .He wants to apply this operation m times and desires to know the final contents of the seq.

      He is bored of playing this game, So he asks you to find out the final content of the seq.


      Input

      First line contains number of test cases: T (1 <= T <= 100).

      For each test case, first line contains three space seperated n, k, m (1 <= n <= 50, 1 <= k <= n, 1 <= m <= 10^9). n is always even.

      The next line contains n space separated integers seq[i](starting from 0), -10^9 <= seq[i] <= 10^9.


      Output

      For each test case, output n space separated integers where ith element represents seq[i] after m "Super Weird Operations".


      Example

      Input:
      

      1

      4 3 1

      2 4 -3 5

      Output: 
      12 1000000002 7 1000000001

      Added by:praveen123
      Date:2014-02-01
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18273. Encode Integer

      Problem code: SNGINT


      Given an integer N (N > -1 and N < 107). Encode N into another possible smallest integer M (M > 0), such that product of digits of M equals to N.

      Input

      First line input is T (total no. of test cases), followed by T (T < 10001) lines containing integer N.

      Output

      For each N output M or -1 (if encoding is not possible) in each line.

      Example

      Input:
      3
      24
      5
      11
      
      Output:
      38
      5
      -1
      

      Added by:Abhimanyu Singh
      Date:2014-02-03
      Time limit:0.400s-1.100s
      Source limit:1024B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Abhimanyu Singh
      My Problems









      SPOJ Problem Set (classical)

      18283. Maggu and Cuteness of Strings

      Problem code: IITWPC4H


      Given two strings s and t of size n and m respectively. You can construct a string w of size n+m using s and t such that it should contain both s and t as its subsequences.
                 
      String w must satisfy this condition: For each character from 'a' to 'z', count of the character in w should be equal to sum of count in s and t. Additionally every character of w must belong to the subsequence for either s or t. 

      eg. if s = ab and t = cd, Then w can be abcd, acbd, cdab, cabd, acdb, cadb. Note that adcb is not correct, As t is not a subsequence in it.

      “Cuteness value” of a string is defined as the maximum length of consecutive equal characters in the string.

      For all possible string w that you can construct, find out the maximum value of “Cuteness value”.

      Input 

      First line contains T: number of test cases

      For each test you case you are given a single line containing two space separated strings s and t. (1 <= size (s), size (t) <= 10^5).

      Both the strings s and t will have characters from 'a' to 'z' of English alphabet only.

      Note:Sum of length of all the input string is less than 5*10^6.

      Output

      For each test case, output the answer as given in problem statement.

      Example

      Input:
      1
      ab ab Output: 2

      Added by:praveen123
      Date:2014-02-03
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18284. Petya and Repairment of Roads

      Problem code: IITWPC4I


      Petya live in a city named Mayapur. As the in the morning, everybody likes to drink hot tea in bed. So the citizens needs milk to produce tea. For this purpose, they want that they should be able to go to atleast some milkmen using bi-directoinal roads. There are m roads in the city but all of them are currently unrepaired, hence not a state of use.
      As Petya cares about his city a lot. He got a project about reparing these roads. So he has to select some roads to repair such that every citizen is connected to atleast one milkman. For reparing each road he needs to pay a cost. As he does not want to spend a lot of money in it, He wants to minimize the cost needed in this project. Note that a milkmen does not need to go to some other milkmen for milk as he can take milk from his own home. 

      Help Petya in finding out minimum cost needed to repair the roads in the above given way. If it is not possible for a citizen to connect to any of the milkmen, output "impossible" (without quotes).

      Input

      First line contains T : number of test cases. (1 <= T <= 100)

      For each test case, First line contains two space seperated number n, m: number of citizens in Mayapur and m denotes number of unrepaired roads.

      Next line contains n space integers either 0 or 1 which indices that citizen is milkmen or not[1 means he is a milkman]. (1 <= n <= 10^5)

      Then For each of the next m lines, each line contains three space seperated integers u, v and c, denoting that there exists a unrepaired road between u and v such that cost of repairing of road is c. (1 <= u, v <= n and u != v)  

      (1 <= m <= min (n * (n - 1) / 2, 2 * 10^5). 1 <= c <= 10^9.) 

      Output

      For each test case output the cost as required.

      Example

      Input:
      1
      5 7
      0 1 0 1 0
      1 2 11
      1 3 1
      1 5 17
      2 3 1
      3 5 18
      4 5 3
      2 4 5
      Output:
      5
      

      Added by:praveen123
      Date:2014-02-03
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18286. Gopu and Fishes

      Problem code: IITWPC4J


      Gopu is playing with fishes, He likes playing them very much because they are lovely creatures. There are n fishes, All the n fishes are kept in n aquariums. Each fish is kept in different aquarium.

      While he is playing with them, there comes a magic instant in his play. At that instant, fish in aquarium i can go to aquarium j with probability p[i][j]. At this magic instant, all the fishes go to aquariums according to their probabilities.

      Now there is a slight issue in this, If more than one fishes land on the same aquarium, Then they can not survive because of lack of space. You have to find the probability that none of Gopu's fishes dies, otherwise he would be very sad. 

      Please help our little Gopu so that he could keep playing with his fishes :)

      Input

      First line contains number of test cases : T (1 <= T <= 1000)

      Next line contains n : number of fishes (1 <= n <= 15).

      For next n lines, each line contains n space seperated real numbers. In line i, jth number is p[i][j]. p[i][j] is precise upto 6 decimal digits.

      Output

      For each test case, print the probability that none of Gopu's fishes dies. (probability is a real number and it should not have error more than 1e-6), That is your answer should be correct upto 6 decimal digits.

      Example

      Input:
      2
      2
      1 0
      0 1
      2
      0.5 0.5
      0.5 0.5 Output: 1.000000
      0.500000

      Added by:praveen123
      Date:2014-02-03
      Time limit:1s-10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18287. Maggu and Magguness Level

      Problem code: IITWPC4K


      Until now you would have known that Maggu is a big geek. His class has n students. All the students are geeks like him. You are given m informations of form a, b which denotes that a th guy is less geeky than b th guy (geekiness(a) < geekiness (b)). Note that geekiness of each person is unique and can be from 1 to n. Now Maggu wonders what are the possible values of his geekiness. If such a distribution of geekiness value is not possible, then output -1. 

      Input

      First line contains T: number of test cases (1 <= T <= 100).

      For each test case, first line contains n, m, idx where n is number of boys in the class, m is number of informations, idx is the index corresponding to Maggu. 1 <= n <= 10^6, 1 <= m <= min (10^5, n * (n - 1) / 2), 1<= idx <= n.

      Then next m line contains two space separated integers representing a, b. (1 <= a, b <= n).

      No pair of information is repeated twice in the input.

      Output

      For each test case, You have to output one or two lines depending on the situation. In the former case, If the  disribution of geekiness can not exist, output -1.

      In the second case (ie two lines), In the first line, output a single integer number of possible geekiness values of Maggu.
      Then in the next line output in the increasing order all the possible geekiness values of Maggu in ascending order. All the values should be space seperated.

      Example

      Input:
      2
      3 2 1
      1 2
      2 3
      4 2 1
      1 2
      3 4 Output: 1
      1
      3 1 2 3

      Added by:praveen123
      Date:2014-02-03
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18289. Maggu and Mystery

      Problem code: IITWPC4L


      Once Maggu went for an adventerous trip to mysteryland. Mysteryland is full of mysteries. There are n doors for entering into mysteryland. Maggu has to open atleast d doors to enter into mysteryland. Each door of mysteryland can only be opened by specific mystery key. Each of the door has a number lock on it and door opens only by a key of that number.

      As Maggu is a small boy, he is given a mystery power for each door. A mystery power is as follows, He can increase or  decrease the number of key of i^th door by atmost v[i]. Needless to say that msyteryland is so mysterious that keys to the locks are not fixed, they could be any integer (No need to be positive). But there is a problem, no two doors of the doors of mysteryland can be opened by same numbered keys ie if there are two or more doors that have same key, then only the first door will open. So he wants to apply mystery power operations so as to open atleast d doors. He can a apply a mystery operation on any of the door and as much times as he wishes.

      As he is in haste for doing adventure, he wants to do this by using as less Mystery power operations as possible. Find out the minimum number of mystery power he needs to apply to enter into mysteryland so that he could enjoy himself :)

      Input

      First line of the input contains T denoting number of test cases (1 <= T <= 20).
      For each test case, you are given 3 lines as follows.
      First line contains two space separated integers n and d. (n will be between 1 and 50 inclusive), (1 <= d <= n)
      Then next line contains n integers denoting the number written on the i^th lock. (each number will be between 1 and 1000 inclusive.
      The next line contains n space separated integers denoting v[i]. (1 <= v[i] <= 5).

      Output

      For each test case, output a single line representing the answer to the problem.

      Example

      Input:
      
      4
      3 2 5 1 3 1 1 1
      3 3
      1 1 1
      2 1 1
      4 4
      1 1 1 2
      1 2 1 1
      4 3
      1 1 1 2
      1 2 1 1
      Output:
      0
      2
      2
      1

      Explanation of the test case. For the second test case, the configuation of keys according to doors can be as follows -1, 1, 2.
      He only needs 2 Mystery powers for doing this.
      Explanation of last test case: For opening two doors, You can use key configutation of 0, 1, 1, 2 (reducing the first door
      number by 1). Then use 0, 1, 2 keys to open 3 doors.
      You can also use key configutation of 1 -1 1 2 (reducing the second door number by 2), Then use -1, 1, 2 for
      opening 3 doors.

      Added by:praveen123
      Date:2014-02-03
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IITK ACA CSE online judge









      SPOJ Problem Set (classical)

      18297. Problem4

      Problem code: CODEM4


      "Roadies" is back!!! In India,"Roadies" is a reality based tv show and is very popular among the youth.

      This time to get selected into "Roadies" they challenge you to solve the given problem....if you can solve it you will be selected!

      Challenge is as follows: Suppose you are given an array with even number of integers.Player 1 and player 2 take turns to pick numbers,either the leftmost element or the rightmost element.You have to find the maximum possible score (sum of numbers chosen) by player 1.Assume player1 always starts the game and plays optimally.

      Note:when an element is picked it is removed from the array.

      But as usual this is "Roadies" hence cometh the twist.It is not known whether the second player plays like a dumb or smart.As you know result will be different if player 2 is either dumb or smart.

      NOTE: when player 2 plays like a dumb there is no fixed strategy of how he would choose the numbers i.e he would choose the number either from start or end of an array without thinking...so there can be multiple answers possible when player 2 plays like a dumb...

      So you have to tell the maximum possible score of player 1 when player 2 plays like a dumb and smart.

      Input description: 

      T:no of test cases(t<20)

      For eact case two lines follow,first line contains the size of array(<=30) and next line contains elements of array.

      T:no of test cases(t<20)

      For eact case two lines follow,first line contains the size of array(<=30) and next line contains elements of array.

      Output description:

      For each case print in new line two space separated integers: score when player 2 is dumb and score when player 2 is smart.

       

      Input:

      2

      4

      5 8 4 2

      4

      8 5 4 2

       

      Output:

      13 10

      13 12

       

      NOTE:All values will fit in int type.

      Explanation:In first test case (when player 2 is dumb) then player 1 first chooses 5 then player 2 can choose 8 or 2 but chooses 2. so now player 1 can choose either 8 or 4 so chooses 8.Hence total score is 13. 

      (when player 2 is smart) player 1 can choose 5 or 2 but chooses 2(so that player 2 cannot choose 8 in his turn) so now player 2 can choose 5 or 4.Irrespective of what player 2 chooses player 1 will have option to choose 8 in his next turn hence total (8+2)=10.


      Added by:Bhavik
      Date:2014-02-04
      Time limit:30s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own problem(for CODE MARATHON)









      SPOJ Problem Set (classical)

      18302. Identity crisis

      Problem code: IDC1948


      For every given number n we define x(n) as distance from n to the first number after n in form of 99...99. For example x(100)=899, x(45)=54, etc. Given several n numbers you have to find the Zp, where x(n)n mod p.

      Input

      First line of input icontains one number T (T<20) - the number of test cases. In each of the next T lines contains one number each to represent n (0<n<30000000).

      Output

      In each line you have to write one number - the least p>1 that x(n)n mod p. If there is no such p the line should contain -1.

      Example

      Input:
      2
      234
      5
      
      Output:
      3
      
      -1
      Explanation:
      x(234)=765. 765 mod 3=0, 234 mod 3=0 => 765234 mod 3

      Added by:Konrad Krystecki
      Date:2014-02-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18336. Search Bit Sum

      Problem code: BIT2


      Deepan is a palantir incredible guy who once had a trip in Switzerland. He saw a weird shop where he liked a teddy. But he din have enough dollars with him to buy this teddy. But there was a scheme ongoing like solve a equation and get the teddy && pay whatever we wish.Thats why this shop is weirdo. He had no eager to buy this teddy as not much of people can solve the equation, so he was sure he can get this teddy as soon as he solve the problem. He need your help to solve the equation. You will be given a number N, and you have to tell whether there exist a number K so that sum of BITS in all the numbers from 1 to K is equal to N. If there exist a K, then print it, else print "Does Not Exist." without quotes.

      Constraints: 1<=N<=10^15, 1<=T<=10^5.

      Input :

      First line contains t, number of testcases. For each testcase, first line contains N.

      Output:

      Output as described above.


      Example

      Input:

      6

      282657

      377636

      472615

      567594

      662573

      1992279

      Output:

      38050

      49299

      Does Not Exist.

      Does Not Exist.

      82953

      227394


      ID RESULT TIME
      code...



      Added by:Rishav Goyal
      Date:2014-02-07
      Time limit:5s-10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      18393. Hamiltonian Cycles

      Problem code: IE5


      You are given a complete undirected graph with n nodes numbered from 1 to n. You are also given k forbidden edges in this graph.

      You are asked to find the number of Hamiltonian cycles in this graph that don't use any of the given k edges. A Hamiltonian cycle is a cycle that visits each vertex exactly once. A cycle that contains the same edges is only counted once. For example, cycles 1 2 3 4 1 and 1 4 3 2 1 and 2 3 4 1 2 are all the same, but 1 3 2 4 1 is different.

      Input

      The first line of input gives the number of cases, N (≤ 10). N test cases follow. The first line of each test case contains two integers, n (≤ 300) and k (≤ 15). The next k lines contain two integers each, representing the vertices of a forbidden edge. There will be no self-edges and no repeated edges.

      Output

      For each test case, output one line containing "Case #X: Y", where X is the case number (starting from 1) and Y is the number of Hamiltonian cycles that do not include any of those k edges. Print your answer modulo 9901.

      Example

      Input:
       2
      4 1
      1 2
      8 4
      1 2
      2 3
      4 5
      5 6
      Output: Case #1: 1
      Case #2: 660

      Added by:acheron
      Date:2014-02-09
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:GCJ Practice Round









      SPOJ Problem Set (classical)

      18408. The Valentine Confession

      Problem code: CRNVALEN


      We are talking about DTU here. Just like most engineering colleges in India, the gender ratio is pretty skewed at DTU. But the girls over here are very generous and noble. Many of them double date guys as a social service ;) .

      Now its the valentines week , 11 at the night and "n" girls residing at the hostel are gossipping in the tv room of the hostel. Every girl is either dating a single person or double dating. These girls decide to confess, so they tell each other that whether they are dating a single guy or they are more noble and dating 2 guys. And mind you these are the noble girls of DTU, they NEVER LIE( at least no DTU girl  lies to other DTU girl ). But the hostel warden, Chameli, is interested in knowing the secret of the girls too.

      So these girls decide to play a Game: Each of the "n" girls tell the warden the number of girls among the remaining n-1 girls who are double dating. You have to help the warden, Chameli, to figure out the total number of girls who are double dating.

      Input

      The first line contains an integer "T", the no. of test cases.

      Each test case consists of 2 lines. The first line contains an integer n- number of girls at the hostel.

      The next line contains n space separated integers. ith number denotes the number that the ith girl told the warden.

      Output

      Print the total number of girls who are double dating, or -1 if the girls are making a fool of the warden and the data is invalid, one test case per line.

      T<=100

      2<=n<=10000

      All of the n numbers are <= 10^9

      Example

      Input:
      
      1
      3
      2 2 2
      Output:
      3

      Added by:CSI
      Date:2014-02-10
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18425. Polynomial Multiplication

      Problem code: POLYMUL


      Sam and Dean fight the supernatural creatures to protect the humans. Now they have come across a creature called the Vedala, which are always found in pairs. Each vedala can be represented by a polynomial. Both the Vedalas need to be killed at once or else they can't be killed. They can be killed only by using the product of the two polynomials representing the two Vedala.
      Help Sam and Dean find the product of the polynomials fast, so they can do thier work. 

      Input

      First line contains an integer T(≤10), number of test cases.
      Each test case will have n(n≤10000), maximum degree of the polynomials on the first line. 
      Next two lines will have n+1 space separated integers each representing the coeffiecients of first and second polynomials respectively.

      All input coefficients vaues are <=1000

      Output

      For each test case ouput a line of 2n space seperated integers indicating coefficients of the polynomial created after multiplication.

      Example

      Input:
      2
      2
      1 2 3
      3 2 1
      2
      1 0 1
      2 1 0 Output: 3 8 14 8 3 
      2 1 2 1 0 
      Explaination:
      1st test case n=2, the plonomials are
      x^2 + 2x + 3 and 3x^2 + 2x + 1. 
      On multiplying we get 3x^4 + 8x^3 + 14x^2 + 8x + 3 and hence the answer 3 8 14 8 3. 

      2nd test case n=2, the polynomials are
      x^2 + 1 and 2x^2 + x. 
      On multiplying we get 2x^4 + x^3 + 2x^2 + x and hence the answer 2 1 2 1 0. 

      Added by:Abhra
      Date:2014-02-12
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18438. Happy Valentine Day (Valentine Adventure Game)

      Problem code: VAL_GAM4


      Happy valentine day! In this problem you'll play adventure game, where you should bring chocolate to your home on 1D virtual world. You start from location 0 and your home located on h. You will take the journey from 0 to h but in the middle of your way to home there could be some bad person who want to steal your chocolate, so you will war with them, if you win, you'll continue the journey, else you'll restart the game. There also some flag, if you successfully take the flag, when you restart the game you'll continue at that flag location but you lose that flag and try to take that flag again, if you take multiple flag, the latest flag that you take will be used and the other flag that you successfully take will be keep.

      Illustraition

      Now given the map that contain all flag location + probability that you'll successfully take that flag, all war location + probability that you'll win the war, and your home location. Calculate the expected time needed to finish the game. Assume your move speed is constant: 1 unit per time and you do the war and take the flag in no time.

      Input

      There are multiple test case in one file,

      For each test case:

      - First line there are two integers h and q denoting the home location and number of object between 0 and h.

      - Next q lines there are one character and 3 integers, c, n, a, b:

      --> c is denoting the type of object ('X' means war, and 'F' means flag)
      --> n is denoting the location of object, it's guaranteed that n will be strictly increasing (larger than previous n)
      --> a and b denoting numerator and denominator the probability, so the probability is a/b.

      The last line in input file there are two zeros, indicating end of sequence of cases, and your program should terminate.

      Output

      For each test case output the expected time needed to finish the game. Since the answer could be very large, output it modulo 109+7. All cases is designed such that it's guaranteed the expected time will be an integer.

      Constraints

      0 < h ≤ 1018

      0 ≤ q ≤ 104

      0 < n < h

      0 < b < 109+7

      0 < ab

      Input File Size < 500 KB

      Example

      Input:
      32 0
      32 1
      X 16 1 2
      32 2
      F 8 1 1
      X 16 1 2
      32 2
      F 8 1 2
      X 16 1 2
      0 0
      
      Output:
      32
      48
      40
      44

       

      See also: Another problem added by Tjandra Satria Gunawan


      Added by:(Tjandra Satria Gunawan)(曾毅昆)
      Date:2014-02-14
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      18450. Largest Increasing Sub-Matrix

      Problem code: MXSBMTRX


      Mosa loves all sorts of properties of matrices. One day his coach Fegla asked him to draw a matrix with size N × M and insert random numbers in each cell, then he asked him to find the largest increasing sub-matrix.

      It's defined as a matrix that each cell in the position (i, j) is greater than the cells in positions:

      (i - 1, j), (i, j - 1) and (i - 1, j - 1).

      Maximum increasing sub-matrix

      Help Mosa to find the size of the largest increasing sub-matrix.

      Input

      t - the number of test cases, then t test cases follows. [t <= 50]

      Each test case contains two integers N and M indicating the matrix dimensions [1 <= N * M <= 105].

      Each of the next N lines contains M integers, separated by a space, describing the elements of the matrix.

      Element Xi,j of the matrix is the jth integer of the ith line in the input [-109 <= Xi,j <= 109].

      Output

      For each test case in the input your program must print on single line, containing the solution of the problem.

      Example

      Input:
      2
      2 3
      2 2 2
      2 2 2
      3 3
      1 2 5
      4 6 7
      10 8 3 Output: 1
      6

      Added by:Mohamed Ahmed
      Date:2014-02-14
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18457. Very Friends

      Problem code: VFRIENDS


      You are creating a new soical network for dogs. Wow. The dogs don't have many possibilities for interacting with your website, but they can bark how many friends they want. E.g. if a dog wants to have much 8 friends it will bark 8 times, and if it doesn't want any friends, it'll just stay quiet.

      After spending a good year of your life collecting these barks, you are finally ready to assign a friend list for each dog. The only problem is: You are not sure whether it is actually possible. Thus before you proceed you would like to write a program, that given a list of N wishes wi, outputs HAPPY if it is possible to make a friend list for each dog i of length wi, or SAD if some dog will have to get more or fewer friends than it wished for.

      Notice: Being friends is considered an irreflexive, symetric relation.

      Update: If you manage to solve this problem much efficiently, have a look at VFRIEND2, which is a so harder version of this problem.

      Input

      The first line will contain a single integer T - the number of test cases to process.

      Each following lines will start with an integer 0 ≤ N ≤ 105 followed by an ordered list of N wishes 0 ≤ wi ≤ 105.

      Output

      Write the answer - HAPPY or SAD - for each test case on a separate line.

      Example

      Input:
      3
      3 0 1 1
      5 0 1 2 3 4
      6 1 1 2 2 3 3 Output: HAPPY
      SAD
      HAPPY

      Explanation

      In the first case we can make dog 2 and 3 be friends.

      In the second case no assignment that works, since dog 5 would have to be friends with everyone, but dog 1 doesn't want that.


      Added by:Thomas Dybdahl Ahle
      Date:2014-02-17
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18458. Very Friends 2

      Problem code: VFRIEND2


      You are creating a new soical network for dogs. Wow. The dogs don't have many possibilities for interacting with your website, but they can bark how many friends they want. E.g. if a dog wants to have much 8 friends it will bark 8 times, and if it doesn't want any friends, it'll just stay quiet.

      After spending a good year of your life collecting these barks, you are finally ready to assign a friend list for each dog. The only problem is: You are not sure whether it is actually possible. Thus before you proceed you would like to write a program, that given a list of N wishes wi, outputs HAPPY if it is possible to make a friend list for each dog i of length wi, or SAD if some dog will have to get more or fewer friends than it wished for.

      Notice: Being friends is considered a reflexive relation.

      Input

      The first line will contain a single integer T - the number of test cases to process.

      Because of I/O constraints, the sequence of wishes is not given explicitly. Each of the T lines will consist of 5 integers N, a, b, c, m in the range [0, 10^7] (except m which is in [1, 10^7]). These integers describe the sequence

      x0 = 0
      xi+1 = (a*xi + b) % m

      The sequence of wishes is wi = xi + c.

      Output

      Write the answer - HAPPY or SAD - for each test case on a separate line.

      Example

      Input:
      3
      3 2 1 0 2
      5 1 1 0 5
      6 1 1 1 3
      
      Output:
      HAPPY
      SAD
      HAPPY

      Explanation

      In the first case we get the wishes "0 1 1", and we  can make dog 2 and 3 be friends.

      In the second case we get the wishes "0 1 2 3 4". No assignment that works, since dog 5 would have to be friends with everyone, but dog 1 doesn't want that.

      In the third case we get the wishes "1 2 3 1 2 3".


      Added by:Thomas Dybdahl Ahle
      Date:2014-02-17
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18465. A Subtle Surf

      Problem code: UOFTCC


      Alice has received an invitation from Bob to watch some TV on $D$ ($1 \leq D \leq 100$) days! Though spending time with him is nice, she's more concerned about exactly what channels they'll be watching. After all, being a guy, Bob is sure to be interested in viewing less sophisticated programs than she is.

      On each day, a different set of $N$ ($1 \leq N \leq 100,000$) channels are available, numbered $1..N$. Each channel $i$ has a girliness value of $G_i$ ($0 \leq G_i \leq 10^9$) associated with it, indicating how much Alice would like to watch it. When she arrives at Bob's house, the TV is set to channel 1, but she'd like to surf to a channel with maximal girliness, and as quickly as possible.

      Alice wants to be subtle about her channel surfing, however. She believes that Bob may notice if they stay on any channel for less than $T$ ($1 \leq T \leq 1000$) seconds before switching, or if the girliness value of the new channel is more than $C$ ($1 \leq C \leq 10^9$) greater than that of the current one. She needs a plan of action to maximize the girliness of the channel they end up watching, while minimizing the amount of time it'll take her to surf to such a channel.

      Input

      Line 1: 1 integer, $D$

      For each day:

      Line 1: 3 integers, $N$, $C$, and $T$

      Line 2: $N$ integers, $G_{1..N}$

      Output

      For each day:

      2 integers, the maximum channel girliness which Alice can surf to, and the minimum number of seconds required to arrive at a channel with this girliness, respectively

      Example

      Input:
      2
      6 3 5
      3 4 0 8 12 6
      4 1 2
      5 7 7 5
      Output:
      8 10
      5 0
      Explanation of Sample:

      On the first day, Alice should switch to channel 6 after 5 seconds, and to channel 4 after another 5 seconds.

      On the second day, Alice can't surf to either channel 2 or 3, so she should stay on channel 1.


      Added by:Jacob Plachta
      Date:2014-02-18
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2013 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      18466. A Frightening Evening

      Problem code: UOFTCD


      Bob is taking Alice out for an evening at the movies! He'll be deciding what movies they see, of course, and he's got $N$ ($1 \leq N \leq 100$) awesome ones in mind. All of them happen to be horror movies.

      A given movie is $D$ ($1 \leq D \leq 10^9$) minutes long, and has $M$ ($0 \leq M \leq 100$) key moments. The $i$th moment occurs $T_i$ minutes into the movie, and causes Alice's fright level (which starts at 0) to instantly increase by $F_i$ ($-10^6 \leq F_i \leq 10^6$). If her fright level would become negative, it instead becomes 0. The moments are given in chronological order, so $0 \leq T_1 < T_2 < \dots < T_M \leq D$. As soon as the movie ends, Alice's fright level is instantly reset to 0.

      During each movie, Alice has two fright thresholds, $H$ and $L$ ($1 \leq H < L \leq 10^9$). Whenever her fright level is at least $H$, Bob is obligated to hold her hand. However, as soon as her fright level is at least $L$, she'll be scared enough to leave the theatre - at which point, Bob will stay inside and finish the movie, and will of course no longer need to hold her hand.

      Bob enjoys brilliant films such as Night of the Dead Living and Return of the Revenge of the Attack of the Killer Foxen, and he'd prefer to not be distracted. As such, he'd like to minimize the amount of time he spends holding Alice's hand. To help with this, he may choose to cover her eyes during at most one key moment in each movie. Alice's fright level will be unaffected by this key moment.

      Input

      Line 1: 1 integer, $N$

      For each movie:

      Line 1: 4 integers, $D$, $M$, $H$, and $L$

      Next $M$ lines: 2 integers, $T_i$ and $F_i$, for $i=1..M$

      Output

      For each movie:

      1 integer, the minimal number of minutes for which Bob needs to hold Alice's hand

      Example

      Input:
      2
      90 5 5 50
      12 8
      14 -4
      40 6
      45 11
      73 -50
      105 3 5 20
      33 15
      39 -1
      52 5
      Output:
      30
      19
      Explanation of Sample:

      While watching the first movie, Bob should cover Alice's eyes during the third key moment. With this strategy, Alice's fright level will be at least 5 between moments 1 and 2, and between moments 4 and 5. Therefore, Bob will need to hold her hand for $2+28=30$ minutes.

      While watching the second movie, Bob should cover Alice's eyes during the second moment. He will then need to hold her hand between moments 1 and 3, at which point her fright level will become 20, and she'll have to leave the theatre.


      Added by:Jacob Plachta
      Date:2014-02-18
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2013 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      18467. A Brief Expedition

      Problem code: UOFTCE


      Alice has convinced Bob to accompany her on a shopping trip! For some reason, he seems reluctant to spend too much time on it, but she has every intention of hitting every single store at $M$ ($1 \leq M \leq 100$) different malls today. Still, she's promised to get it over with as quickly as possible.

      A given mall can be modelled as a two-dimensional grid of cells, with $R$ ($1 \leq R \leq 100$) rows and $C$ ($1 \leq C \leq 100$) columns. Each cell contains either a wall (represented by a "#"), open space ("."), a store ("S", of which there is at least one), or Bob's car ("C", of which there is exactly one). Alice and Bob can walk from one cell to a horizontally- or vertically-adjacent one in 1 minute if neither cell is blocked by a wall.

      The two of them will start at Bob's car, and walk to a store (possibly passing through other stores on the way) so that Alice can do what she does best, which only takes her 60 minutes. At that point, due to the large volume of items purchased, they'll need to return to the car to drop them off. This process will repeat until all stores in the mall have been visited, in some order. It's guaranteed that each store is reachable from the car.

      To reassure Bob that they won't spend too much time at each mall, Alice will leave a stopwatch running until the final items have been dropped off in the car. However, sneaky as she is, Alice will only start timing when she actually starts shopping at the first store they decide to visit. She'd like to know how much time will be spent at each mall - though she's sure that it won't be much at all.

      Input

      Line 1: 1 integer, $M$

      For each mall:

      Line 1: 2 integers, $R$ and $C$

      Next $R$ lines: $C$ characters, representing the $i$th row of the mall grid, for $i=1..H$

      Output

      For each mall:

      1 integer, the minimal number of minutes required to visit all stores and return to the car, as per Alice's stopwatch.

      Example

      Input:
      2
      4 4
      ..S#
      .##C
      ....
      S.#S
      1 5
      SSCSS
      Output:
      202
      250
      Explanation of Sample:

      At the first mall, Alice and Bob can decide to visit the top store, followed by the bottom-left, and finally the bottom-right. In this case, they'll spend 60 minutes shopping, 8 minutes returning to the car, 5 minutes walking to the second store, 60 minutes shopping, 5 minutes returning to the car, 2 minutes walking to the third store, 60 minutes shopping, and 2 minutes again returning to the car. This is a total of 202 minutes.

      At the second mall, they can decide to visit the stores left-to-right. This shopping trip will take $60+2+1+60+1+1+60+1+2+60+2=250$ minutes.


      Added by:Jacob Plachta
      Date:2014-02-18
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2013 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      18468. A Pleasant Stroll

      Problem code: UOFTCF


      This evening, Alice and Bob have decided to simply go out on a nice walk together. On the way, they'll traverse $S$ ($1 \leq S \leq 50$) different sidewalks. Now that they won't be watching engrossing movies, Bob really wouldn't mind holding Alice's hand - however, this can sometimes be difficult to maintain, due to potential obstacles in their way.

      A given sidewalk can be modelled as a two-dimensional grid of cells, with $R$ ($1 \leq R \leq 50$) rows and $C$ ($1 \leq C \leq 50$) columns. The $j$th cell in the $i$th row is referred to as cell ($i$, $j$). Each cell is either walkable (represented by a "."), or is blocked by the neighbourhood dog's droppings ("#"). Alice and Bob will be walking Southwards along it, independently of one another, but both at a rate of exactly one row per second. Needless to say, they'll never walk through cells containing droppings, nor can they ever occupy the same cell as one another. Each of them can start in any cell on row 1, and each second, will move down by a cell, as well as optionally left or right by a cell. In other words, if Alice or Bob is in cell ($i$, $j$), they can then move to either cell ($i+1$, $j-1$), ($i+1$, $j$), or ($i+1$, $j+1$), as long as they don't step off the sidewalk. This continues until they've both made it to row $R$, at which point they step off and make their way towards the next sidewalk on their route. It might also be the case that they're unable to both navigate to the end of the sidewalk, in which case they'll take a detour around it entirely.

      Along the way, whenever Alice and Bob find themselves side-by-side (in other words, in cells ($i$, $j$) and ($i$, $j+1$), for some $i$ and $j$), they can hold hands for that second! Bob is interested in coordinating their walk to enable them to hold hands for as long as possible.

      Input

      Line 1: 1 integer, $S$

      For each sidewalk:

      Line 1: 2 integers, $R$ and $C$

      Next $R$ lines: $C$ characters, representing the $i$th row of the sidewalk grid, for $i=1..R$

      Output

      For each sidewalk:

      1 integer, the maximal number of seconds Alice and Bob can spend holding hands, or the string "Detour" if they can't both make it to the end.

      Example

      Input:
      2
      5 5
      #....
      ..##.
      .#...
      #.#..
      ....#
      2 4
      .##.
      ..## 
      Output:
      4
      Detour
      Explanation of Sample:

      On the first sidewalk, Bob can ask Alice to walk through cells (1, 3), (2,2), (3, 3), (4, 4), and (5, 3), while he goes through cells (1, 4), (2, 5), (3, 4), (4, 5), and (5, 4). The two of them will then get to hold hands while on rows 1, 3, 4, and 5, for a total of 4 seconds.

      However, there's no way for both Alice and Bob to navigate the second sidewalk. They must start in cells (1, 1) and (1, 4), and no walkable cells on the second row can be reached from cell (1, 4).


      Added by:Jacob Plachta
      Date:2014-02-18
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2013 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      18469. Office Mates

      Problem code: UOFTCG


      Dr. Baws has an interesting problem. His $N$ graduate students, while friendly with some select people, are generally not friendly with each other. No graduate student is willing to sit beside a person they aren't friends with.

      The desks are up against the wall, in a single line, so it's possible that Dr. Baws will have to leave some desks empty. He does know which students are friends, and fortunately the list is not so long: it turns out that for any subset of $K$ graduate students, there are at most $K-1$ pairs of friends. Dr. Baws would like you to minimize the total number of desks required. What is this minimum number?

      Input

      The input begins with an integer $T \le 50$, the number of test cases. Each test case begins with two integers on their own line: $N \le 100000$, the number of graduate students (who are indexed by the integers $1$ through $N$), and $M$, the number of friendships among the students. Following this are $M$ lines, each containing two integers $i$ and $j$ separated by a single space. Two integers $i$ and $j$ represent a mutual friendship between students $i$ and $j$.

      The total size of the input file does not exceed 2 MB.

      Output

      For each test case output a single number: the minimum number of desks Dr. Baws requires to seat the students.

      Example

      Input:
      1
      6 5
      1 2
      1 3
      1 4
      4 5
      4 6
      Output:
      7
      Explanation of Sample:

      As seen in the diagram, you seat the students in two groups of three with one empty desk in the middle.


      Added by:Jacob Plachta
      Date:2014-02-18
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Cowritten by Andrew Henrey, used in the 2013 UofT ACM Tryouts









      SPOJ Problem Set (classical)

      18510. Ross generates Data

      Problem code: AKVOD05


      Ross wants to complete the data set for his next research work. He has to generate a set of “N” non negative integers. He already knows the first “K” values out of them. He knows how to generate the remaining values. Any of the remaining values will be the minimum non negative integer that does not exist in the previous “K” values.

      For example, let the value of “N” is 7 and the value of “K” be 4 and the first “K” values be 0 4 3 2 then the next 3 values will be 1 0 4.

      You just have to generate the “N”th value for his work.

      Input

      The first line will contain "T", the no. of test cases. Then "T" test cases follows. For each test case, the first line will contain two integers "N" and "K". The next line will contain "K" integers denoting the "K" values that he already knows.

      Output

      For each test case, output a single integer value that denotes the "N"th integer in his data set.

      Constraints

      1 <= T <= 10

      1 <= K <= 10^5

      K < N <= 10^8

      0 <= Each of the first K values <= 10^8

      Example

      Input:
      
      2
      7 4
      0 4 3 2
      8 5
      4 7 2 3 0
      
      Output:
      
      
      4
      5

      Added by:Ankit Kumar Vats
      Date:2014-02-22
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Self









      SPOJ Problem Set (main)

      18511. Cartman and Butters Game

      Problem code: AKVOD06


      Cartman and Butters are playing a simple game. They have “N” boxes and each box has some amount of money inside it. The boxes are numbered as 1, 2 up to N. In each turn a player can remove a maximum of X(i) amount of money from box i. Inititally the value of X(i) ( 1 <= i <= N) is “Z” for all the boxes. At any point a player can select the box i and a value K ( 1 <= K <= X(i)) and remove K amount of money from the box i and update the value of X(i) = K. That means at any point, the amount of money removed from the box can not exceed the amount of money removed from the same box previously. Now let us suppose that both the players play optimally and Cartman takes the first turn. If at any point a player can not remove any money from any box then he loses. Can you predict who will win the game?

      Input

      The first line will contain "T" the no. of test cases. Then "T" test cases follow. The first line of each test case will contain two integers "N" and "Z". The next line will contain "N" integers Ai (1 <= i <= N), where Ai denotes the amount of money in ith box.

      Output

      For each test case, print the name of winner "Cartman" or "Butters" in a separate line (without quotes). 

      Constraints

      1 <= T <= 100
      1 <= N <= 50
      1 <= Z <= 10^4
      1 <= Ai <= 1000

      Example

      Input:
      4
      1 1
      2 4
      4
      1 1
      2
      2 2
      3 3
      4 8
      3 8 5 10
      5 10
      8 5 10 20 15
      
      Output:
      
      Butters
      Butters
      Cartman
      Cartman

      Added by:Ankit Kumar Vats
      Date:2014-02-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Self









      SPOJ Problem Set (classical)

      18521. Fortunate Wheels

      Problem code: FBWHEELS


      Kit is competing on the latest popular gameshow, Fortunate Wheels. On this show, there is a secret word $S$ ($2 \leq |S| \leq 10^5$) consisting only of uppercase letters, known only to the host, and contestants can pay points to buy sequences of letters in hopes of matching part of $S$ and earning more points! This show is clearly a scam, as the probability of earning more points than are spent is extremely low. Fortunately, Kit has come prepared - he knows the secret word! Even so, getting as many points as possible will not be easy.

      There are $N$ ($1 \leq N \leq 20$) basic deals which constestants can take. The $i$th deal costs $A_i$ points ($1 \leq A_i \leq 10^4$), and allows any sequence of $B_i$ letters ($1 \leq B_i < |S|$) to be purchased. Furthermore, deals can be combined to purchase longer sequences! Combining a deal with cost $C_1$ and length $L_1$ with another deal (potentially the same one) with cost $C_2$ and length $L_2$ creates a new deal with cost $C_1+C_2+W$ ($0 \leq W \leq 10^4$) and length $L_1+L_2$ (as long as $L_1+L_2 < |S|$), which can in turn be used to create even bigger deals. For example, if $W=0$, then a basic deal with cost and length equal to 1 could be combined with itself repeatedly to yield a new deal with both cost and length equal to any positive integer smaller than $|S|$.

      Once Kit purchases a sequence of letters using one (potentially non-basic) deal, it will be matched against the secret word - twice! The host will spin the First Fortunate Wheel to select the starting index in $S$ for the first matching, which is chosen uniformly at random such that the sequence will fit entirely within $S$. Then, the host will spin the Second Fortunate Wheel to select the starting index for the second matching, which is chosen uniformly at random such that the sequence will fit entirely within $S$ {\it and} such that the value given by the First Fortunate Wheel will not be repeated. For example, if the sequence consists of a single letter, the First Fortunate Wheel might yield any of the indices in $S$ with probability $\frac{1}{|S|}$ each, and then the Second Fortunate Wheel might yield any of the remaining indices with probability $\frac{1}{|S|-1}$ each. On the other hand, if the sequence has length $|S|-1$, then the first Wheel might yield either 0 or 1, and the second Wheel must yield the other. If, for both generated indices, the sequence miraculously happens to be equal to the substring of $S$ of the same length starting at that index, then Kit will earn back $Y (|S| - |X-\ell|)^2 + Z$ points ($1 \leq X < |S|$, $0 \leq Y,Z \leq 10^9$), where $\ell$ is the length of the sequence. If even one letter is off in either matching, however, Kit will earn no points at all! What has the game show industry come to?

      Kit is carefully considering his first turn of the game. He obviously wants to maximize the number of points he'll gain, but worries that choosing the very best move might be suspicious. As such, he'd like to find the expected point values of the $M$ ($1 \leq M \leq 20$) best distinct moves before making his decision. Two moves are distinct if they involve purchasing different sequences of letters - the deal(s) used are ignored. Note that moves can have negative expected point values, due to the costs of deals.

      Input

      Line 1: 1 integer, $T$ ($1 \leq T \leq 150$), the number of test cases

      For each test case:

      Line 1: 6 integers, $N$, $M$, $W$, $X$, $Y$, and $Z$

      Line 2: 1 string, $S$

      Next $N$ lines: 2 integers, $A_i$ and $B_i$, for $i=1..N$

      Output

      For each test case:

      $M$ real numbers on one line (acurrate to within $10^{-2}$ in absolute or relative value), the $M$ largest expected point values which can be earned, in descending order

      Example

      Input:
      2
      1 3 0 1 5 6
      ZZ
      2 1
      3 4 1 4 3 2
      FOXENINBOXEN
      5 2
      1000 11
      2 2
      Output:
      24.00000 -2.00000 -2.00000
      7.05556 3.49091 3.49091 3.49091
      Explanation of Sample:

      In the first test case, Kit's best move is to use the basic deal, costing 2 points, to purchase the sequence of letters "Z". No matter what pair of indices the two Fortunate Wheels yield, this sequence will match and earn Kit $5(2-|1-1|)^2+6=26$ points. Any other sequence shorter than $S$ cannot match $S$ at even a single index, so Kit's second- and third-best moves consist of using the basic deal to purchase any other single-letter sequence, and simply losing the 2 points.

      In the second test case, Kit's best move consists of combining the third basic deal with itself to yield a deal with cost 5 and length 4, and then purchasing the sequence "OXEN". His three next-best moves, which are the only other moves which get him a positive expected point value, involve using the third basic deal to purchase the sequences "OX", "XE", and "EN".


      Added by:Jacob Plachta
      Date:2014-02-23
      Time limit:60s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2014 Facebook Hacker Cup finals









      SPOJ Problem Set (classical)

      18522. Tours

      Problem code: FBTOURS


      Facebook Headquarters - a mysterious, intimidating place, full of magical code and trade secrets. If outsiders were ever to breach the walls of the compound, which are protected by a legion of security guards and, more importantly, security foxes, the entire company could well be brought to its knees!

      Actually, wait, tours of the place are given regularly...

      The compound consists of $N$ ($1 \leq N \leq 10^5$) buildings, with $M$ ($1 \leq M \leq 10^6$) walkways running amongst them. The $i$th walkway connects buildings $A_i$ and $B_i$ ($1 \leq A_i,B_i \leq N$, $A_i \neq B_i$), and no two buildings are directly connected by more than one walkway. There are no other ways to move from building to building.

      Over a period of $D$ ($1 \leq D \leq 10^6$) days, some events will occur at the Headquarters daily. One of two types of events will happen on the $i$th day, indicated by the value of the character $E_i$. If $E_i=$ "T" then a tour will take place - otherwise, $E_i=$ "S", and a security sweep of a building will take place.

      If a tour is given on the $i$th day, visitors will enter the compound at building $X_i$, and leave from building $Y_i$ ($1 \leq X_i,Y_i \leq N$, $X_i \neq Y_i$). If it turns out that these two buildings are not actually connected by any sequence of walkways, then the tour will be cancelled, and the unfortunate visitors will be given Facebook T-shirts and promptly kicked out. Otherwise, a large number of groups of people will be led from building $X_i$ to building $Y_i$ along various routes. No route will involve travelling along the same walkway multiple times (even in different directions), but a route might revisit the same building repeatedly, including buildings $X_i$ and $Y_i$. Along the way, some visitors will inevitably get "lost", and fail to rejoin their tour group. How many of them will get away with this will depend on the security levels that day, but it's safe to say that, in total, $O_i$ ($1 \leq O_i \leq 1000$) new outsiders will be left behind in each building which could possibly be part of any valid tour route from building $X_i$ to building $Y_i$. Good thing they'll no doubt have brought cameras to amuse themselves with while they wait to be found.

      On the other hand, if a security sweep is conducted on the $i$th day, then the security guards (and foxes) will carefully search building $Z_i$ ($1 \leq Z_i \leq N$) for any trespassers remaining from previous tours, who will be kindly escorted out of the Headquarters (after being given Facebook T-shirts for the road, of course).

      Because this company likes to collect data about everything, you've been hired to record how many outsiders were found in each sweep. However, to make things more interesting, you'll instead simply write a program to predict these values based on the map of the compound and the schedule of events!

      Input

      Line 1: 1 integer, $T$ ($1 \leq T \leq 20$), the number of test cases

      For each test case:

      Line 1: 3 integers, $N$, $M$, and $D$

      Next $M$ lines: 2 integers, $A_i$ and $B_i$, for $i=1..M$

      Next $D$ lines: 1 character, $E_i$, followed by the three integers $X_i$, $Y_i$, and $O_i$ if $E_i=$ "T", or the single integer $Z_i$ if $E_i=$ "S", for $i=1..K$

      Output

      For each test case:

      1 integer, the total number of people escorted out of the compound, modulo $10^9+7$

      Example

      Input:
      1
      6 5 9
      1 2
      2 3
      3 4
      4 5
      5 3
      T 1 2 5
      T 5 6 1000
      S 2
      S 6
      T 2 3 1
      T 5 3 14
      S 1
      S 2
      S 4
      Output:
      26
      Explanation of Sample:

      On the first day, a tour is given from building 1 to building 2. The only valid route consists of simply crossing the walkway between these two buildings. As such, by the end of the day, 5 outsiders are left hiding in each of buildings 1 and 2.

      On the second day, the planned low-security tour unfortunately cannot take place, due to no routes existing between buildings 5 and 6. Facebook should probably hire some new tour planners, as well as architects.

      On the following two days, security sweeps of buildings 2 and 6 are carried out, with 5 and 0 outsiders found and removed, respectively.

      On the fifth day, a tour is given from building 2 to building 3. There are exactly three valid routes, passing through buildings 2-3, 2-3-4-5-3, and 2-3-5-4-3. As such, one new outsider remains behind in each of buildings 2, 3, 4, and 5.

      On the sixth day, a tour is given from building 5 to building 3. There are exactly two valid routes, passing through buildings 5-3 and 5-4-3. As such, 14 new outsiders take up residence in each of buildings 3, 4, and 5.

      Finally, security sweeps of buildings 1, 2, and 4 are conducted, evicting 5, 1, and 15 people, respectively. In total, then, 5+0+5+1+15=26 people will have been escorted out of the compound, which is still 26 when taken modulo $10^9+7$. Following these events, buildings 3 and 5 still contain 15 outsiders, while the others contain none.


      Added by:Jacob Plachta
      Date:2014-02-23
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem, used in the 2014 Facebook Hacker Cup finals









      SPOJ Problem Set (classical)

      18530. Font Size

      Problem code: FONTSIZE


      Description

      John bought a billboard. He knows what text he wants to put on it, and he has chosen a monospace font to use, but he doesn't know what the font size should be.
      Naturally, John wants to use the largest font size possible.
      Sizing works as follows:
      • The height of a line is the font size.
      • The width of a character is two-thirds of the font size.
      • Lines can only break between the space-separated words.
      • If a space ever falls at the beginning or end of a line, it is omitted.
      Don't worry about details like kerning and line spacing.
      For example, consider the message "The lazy brown dog".
      On a billboard 60 inches wide and 25 inches tall, the maximum font size is 10 inches:
      The lazy
      brown dog
      On a billboard 50 inches wide and 50 inches tall, the maximum size is 12.5 inches:
      The
      lazy
      brown
      dog
      Given the size of the billboard and the message, find the largest font size that will allow the entire message to fix.

      Input

      The first line is the width of the billboard in inches, 0 <= W <= 7500, and the height of the billboard in inches, 0 <= H <= 7500.
      The third line is the non-empty message, which is comprised of alphanumeric words separated by single spaces. The message is most 10,000 characters long.

      Output

      Print the maximum possible font size, in inches. Your answer must be accurate to within 0.001 of the actual value.
      Input Input
      60 25
      The lazy brown dog
      50 50
      The lazy brown dog
      Output Output
      10
      12.5

      Added by:BYU Admin
      Date:2014-02-23
      Time limit:0.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18531. Barrelrider

      Problem code: BRLRIDER


      Description

      Bilbo the Barrelrider is attempting to elude Smaug the Terrible in the treasure-filled halls of Erebor.
      He uses the obstacles (piles of gold, columns, etc.) in the room to hide from Smaug's view. These obstacles can be approximated by circles.
      Smaug may approach Bilbo from any direction. Bilbo's concealment is the proportion of directions for which an obstacle would be between himself and the dragon.
      In total, how much concealment do the obstacles offer Bilbo?
      In the example below to the left, the obstacle affords him 90 degrees (25%) concealment.
      In the middle example, Bilbo is right next to the obstacle, and it offers 180 degrees (50%) concealment.
      If Bilbo is inside an obstacle (say, inside a pile of gold), he cannot be seen at all.
      > > B > > B > > B
      Obstacles can overlap.
      In the example below to the left, Bilbo has 100% concealment.
      In the right example, he has 90 + 53.1 = 143.1 degrees (40%) concealment.
      > > B > > B

      Input

      The first line is 0 <= N <= 1000, the number of obstacles.
      The next N lines are the obstacles, each represented by 3 space-separated integers. The first two integers are -5000 <= X <= 5000 and -5000 <= Y <= 5000, which are the x- and y-coordinates, respectively, of the center of the obstacle. (Bilbo is standing at (0,0).) The third integer is its radius 0 < R <= 1000.

      Output

      Print the percentage of concealment the obstacles offer Bilbo, rounded to the nearest whole percent.
      Input Input Input Input Input
      1
      2 2 2
      1
      2 0 2
      1
      1 0 2
      8
      0 -1 1
      -1 0 1
      -2 1 1
      -1 2 1
      0 -1 1
      1 -2 1
      2 -1 1
      1 0 1
      4
      -3 2 1
      -2 2 2
      2 -1 1
      3 -1 1
      Output Output Output Output Output
      25%
      50%
      100%
      100%
      40%

      Added by:BYU Admin
      Date:2014-02-23
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18532. Tree _order

      Problem code: TREEORD


      Description

      A tree is a connected acyclic graph.
      A binary tree is a tree for which each node has a left child, a right child, both, or neither, e.g.
          1
         / \
        2   3
       / \   \
      4   5   6
      There are three common ways to recursively traverse such a tree.
      1. Preorder: parent, left subtree, right subtree
      2. Postorder: left subtree, right subtree, parent
      3. Inorder: left subtree, parent, right subtree
      Given preorder, postorder, and inorder traversals, determine if they can be of the same binary tree.
      For example,
      1 2 4 5 3 6
      4 5 2 6 3 1
      4 2 5 1 3 6
      are the preorder, postorder, and inorder traversals of the tree above.
      But
      1 2 4 5 3 6
      4 5 2 6 1 3
      4 2 5 1 6 3
      cannot be the preorder, postorder, and inorder tranversals of the same binary tree.

      Input

      The first line is the number of nodes in each traversal, 0 < N <= 8000.
      The second line is the N space seperated nodes of the preorder traveral.
      The third line is the N space separated nodes of the postorder traversal.
      The fourth line is the N space separated nodes of the inorder traversal.
      Each traversal is a sequence of the nodes, numbered 1 to N, without repitition.

      Output

      Print "yes" if all three traversals can be of the same tree, and "no" otherwise.
      Input Input
      6
      1 2 4 5 3 6
      4 5 2 6 3 1
      4 2 5 1 3 6
      6
      1 2 4 5 3 6
      4 5 2 6 1 3
      4 2 5 1 6 3
      Output Output
      yes
      no

      Added by:BYU Admin
      Date:2014-02-23
      Time limit:0.5s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18598. Encode Message

      Problem code: SNGMSG


      Everyone knows that how much Shahjahan loved Mumtaaz, that he got built the Taj Mahal in the memory of his beloved Mumtaaz. Once Mumtaaz had fight with Shahjahan and she went to her father's home. Shahjahan then wrote a letter to Mumtaaz requesting her to come back, but then suddenly he realized that it is not safe to write letter in plain format (non-encoded message), so he thought whole day for a good method of encryption and then came up with a great idea of decoding his messages.

      The technique of encoding messages used by Shahejahan is describes as-
      1. A key K is set of digits (0-9) such that its value doesn't exceed 106.
      2. A message M is set of small letters (a-z) such that its length doesn't exceed 500.
      3. The encoding function F(m, k) = m' is a function that takes one digit from key and one character from message and encode it to another character.

      The encoding algorithm is given by following pseudo code-

      start of code

        1. Repeat until message has characters to be encoded.
          2. Read next character c, of message.
          3. Read next digit k, of key.
          4. Encode using the function F(m, k) = m' : m' = m + k.
            5. If last digit k, of key is read then start reading in reverse order.
            6. If first digit k, of key is read while reading in reverse order, then start again reading in forward direction.

      end of code

      The addition operation to characters is cyclic. Consider the following examples demonstrating the operator-
      1. 'a' + 2 = 'c'
      2. 't' + 1 = 'u'
      3. 'z' + 2 = 'b'
      4. 'y' + 0 = 'y'

      Consider the following encoding of message "mumtaaz" with key 132-

      Character c Digit k F(c, k)
      m1n
      u3x
      m2o
      t2v
      a3d
      a1b
      z1a

      So message "mumtaaz" is encoded as "nxovdba"


      .

      Input

      First line of input it T (T < 10001), total number of test cases.
      Each test case is consist of two lines, the first line contains key and second line contains encoded message.

      Output

      For each test cases, output the original message in single line.

      Example

      Input:
      6
      132
      nxovdba
      212
      uitktjvjmc
      011
      lfbejngafspsasfjnposubot
      123
      jnrygzpw
      11
      lfbejngafspsasfjnposubot
      130
      behipbobu
      Output: mumtaaz shrishtika leadingzerosareimportant iloveyou keadimfzerorzreimonrtans abhimanyu

      Added by:Abhimanyu Singh
      Date:2014-02-27
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Abhimanyu Singh
      My Problems









      SPOJ Problem Set (classical)

      18637. Lawrence of Arabia

      Problem code: LAWRENCE


      Description

      T.E. Lawrence, popularized by the movie Lawrence of Arabia, was a British officer during World War I. He is best known for disrupting the railroads of the Ottoman Empire.
      For this problem, the railroad of concern runs uninterrupted without branches through several outposts.
      P ----- P ----- P ----- P
      Each outpost has a value. The strategic value of a group of connected outposts is the sum of the pairwise products of the outposts. A single outpost
      a
      has no strategic value; two connected outposts
      a
      and
      b
      have strategic value
      a*b
      ; three connected outputs
      a
      ,
      b
      , and
      c
      have stategic value
      a*b + a*c + b*c
      ; and so on.
      The total stategic value of the railroad is the sum of the strategic values of these connected groups
      Lawrence can attack and destroy a certain number of railroad segments. His goal is to reduce the strategic value of the railroad as much as possible.
      For example, consider the following railroad
      4 ----- 5 ----- 1 ----- 2
      The stategic value is 4*5 + 4*1 + 4*2 + 5*1 + 5*2 + 1*2, or 49.
      Suppose Lawrence has one attack, which is marked by an x.
      1. He could attack the left segment.
        4   x   5 ----- 1 ----- 2
        The left group has no value, and the right group has value 5*1 + 5*2 + 1*2, for a total of 17.
      2. Or he could attack the middle segment.
        4 ----- 5   x   1 ----- 2
        The left group has value 4*5, and the right group has value 1*2, for a total of 22.
      3. Or he could attack the right segment.
        4 ----- 5 ----- 1   x   2
        The left group has value 4*5 + 4*1 + 5*1, and the right group has no value, for a total of 29.
      In this case, it would be best for Lawrence to attack the left segment.

      Input

      The first line is the number of outposts, 0 < P <= 500.
      The second line is the number of railroad segments Lawrence can destroy, 0 <= N < P.
      The third line is the space-separated values of the S outposts. Each value is an integer from 0 to 20, inclusive.

      Output

      The minimum possible stategic value of the railroad after Lawrence's attack.
      Input Input
      4
      1
      4 5 1 2
      4
      2
      4 5 1 2
      Output Output
      17
      2

      Added by:BYU Admin
      Date:2014-03-01
      Time limit:1s-45s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:2008 ACM ICPC, Southeast USA Regional









      SPOJ Problem Set (classical)

      18660. Product of factorials (easy)

      Problem code: FACTMULN


      For n positive integer, let F(n) = 1! × 2! × 3! × 4! × ... × n!, product of factorial(i) for i in [1..n].

      Let G(n) = {i in [1..n], such that n divides F(i)}.

      It is obvious that n belongs to G(n) that makes it a non empty set.

      Input

      The first line of input contains an integer T, the number of test cases.
      On each of the next T lines, your are given an integer n.

      Output

      For each test case, you have to print min(G(n)).

      Example

      Input:
      3
      4
      5
      6
      
      Output:
      3
      5
      3
      

      Explanation

      For test case #1:
      F(1) = 1! = 1 , not divisible by 4
      F(2) = 1! × 2! = 2 , not divisible by 4
      F(3) = 1! × 2! × 3! = 12 , divisible by 4
      F(4) = 1! × 2! × 3! × 4! = 288 , divisible by 4
      So G(4) = {3, 4}.

      Constraints

      0 < T < 10^4
      0 < n < 10^9
      

      A little kB of Python code can get AC in half the time limit.
      Input is not randomly chosen ;-) Have fun.


      Added by:Francky
      Date:2014-03-01
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      18662. Product of factorials (again)

      Problem code: FACTMULO


      For n positive integer, let F(n) = 1! × 2! × 3! × 4! × ... × n!, product of factorial(i) for i in [1..n],

      For p a prime number, and n an integer, and let V(p, n) = max({i>=0 integer, such that p^i divides F(n)}).

      Input

      The first line of input contains an integer T, the number of test cases.
      On each of the next T lines, your are given two integers p a prime number, and n.

      Output

      For each test case, you have to print V(p, n).

      Example

      Input:
      2
      2 3
      3 4
      
      Output:
      2
      2
      

      Constraints

      0 < T < 10^5
      1 < p < 10^18, a prime number
      0 < n < 10^18
      

      p and n are log-uniform independent randomly distributed.

      Four lines of Python code can get AC in half the time limit.
      ;-) Have fun.


      Added by:Francky
      Date:2014-03-01
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      18666. Radiation

      Problem code: UVA1


      Nuclear power plants (NPP) are a blessing and curse of modern civilization. NPPs have some risks but still it is one of the cheapest ways to produce electricity in the developed world. In this problem we will discuss a situation related to two nuclear plants, which are not far away from each other.

                                                
      Figure 1: Two Nuclear Power Plants. Houses at (81, 49) and (77,33) are at high risk from both the
      plants.


      We will describe the entire scenario in a at land, so two-dimensional Cartesian coordinate system is used to denote each location. Lets assume that the coordinate of the two nuclear power plants are (ax;ay) and (bx;by). Houses that are located within distance R1 (inclusive) of the power plant at (ax;ay) are under high risk of radiation. Similarly, houses that are located within distance R2 (inclusive) of the power plant at (bx;by) are under high risk of radiation. So the authorities of power plant 1 and power plant 2 distribute special protective equipments to the houses that are within radius (inclusive) R1 and R2 of the respective power plants. As a result each of the houses that are endangered by both the plants actually receive two sets of equipments to protect their house.

      Given the location of the houses and the values of ax;ay; bx; by and possible values of R1 and R2 your job is to find out the number of houses that are endangered by both the plants

      Input

      The input le contains at most 3 test cases. The description of each test case is given below:

      A test case starts with a line containing a positive integerN(0 < N <= 200000) that denotes the number of houses that are under either low risk or high risk of radiation. Each of the next N lines contains two integers xi , yi  (0 <=xi,yi <= 20000) that denotes the coordinate of the i-th house.

      No two houses are at the same location. The next line contains five integers ax, ay, bx, by and q (0<=ax,ay,bx, by <= 20000, 0< q<=20000). The meaning of ax,ay, bx and by are given in the problem statement. Here q denotes the total number of query. Each of the nextq lines contains two integers, which denote the values of R1 and R2 (0< R1,R2 <= 13000) respectively.

      A line containing a single zero terminates input. This line should not be processed.

      Output

      For each test case produceq+ 1 lines of output. The rst line is the serial of output. For each query (given value of R1 and R2) determine the number of houses that are endangered by both the plants. You may consider using faster IO as judge input le is large.

      Note: First query in the sample input corresponds to Figure 1.

      Example

      Input:
      
      11
      95 75
      27 6
      93 5
      124 13
      34 49
      65 61
      81 49
      77 33
      110 50
      91 22
      110 25
      57 42 97 36 1
      31 25 0
      Output:

      Case 1:
      2

      Added by:abdou 00
      Date:2014-03-01
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      18667. Product of factorials (hard)

      Problem code: FACTMULP


      For n positive integer, let F(n) = 1! × 2! × 3! × 4! × ... × n!, product of factorial(i) for i in [1..n],

      For p a prime number, and n an integer, and let V(p, n) = max({i>=0 integer, such that p^i divides F(n)}).

      Input

      The first line of input contains an integer T, the number of test cases.
      On each of the next T lines, your are given two integers p a prime number, and e.

      Output

      For each test case, you have to print V(p, p^e).
      As the answer may not fit in a 64-bit container, just output your answer modulo 10^9+7.

      Example

      Input:
      1
      2 2
      
      Output:
      5
      

      Constraints

      0 < T < 10^5
      1 < p < 10^18, a prime number
      0 < e < 10^18
      

      p and e are log-uniform independent randomly distributed. Warning : input contains tricky cases too.

      A single line of Python code can get AC in the third of the time limit.
      ;-) Have fun.


      Added by:Francky
      Date:2014-03-01
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      18693. TOC

      Problem code: GOPI



      Gopi is  a wise kid and he likes to play all day..he troubled his Brother surrender to play with him..

      Surrender was very busy ,so he gave gopi a  game to play called "TOWERS OF CHENNAI" ..

      Surren gave gopi a set of "n" towers,each of certain height and he gave him the maximum number of operations he can perform on the given set of towers as "k"..Rules of TOC is very simple,i.e in each operation gopi can swap any two consecutive towers..

      The ultimate goal of the game is to construct a sequence of towers such that  the number formed by appending the height of each tower (starting from the first tower till the last tower)is maximum,afer performing atmost "k" operations..

      Gopi found it difficult to play the game..so can u help him..?

      Input

      t-no of test cases

      n-no of towers

      k-maximum no. of operations that can be performed

      1<=t<=50

      1<=n<=1000000

      each element "x" of the set is the height of the tower 1<=x<=1000000

      0<=k<=1000

      Output

      print the maximum height sequence that can be formed after doing atmost "k" operations..

      Example

      Input:
      2
      6
      10 20 30 40 50 60
      1
      6
      10 20 30 40 50 60
      2
      Output:
      201030405060
      301020405060

      Added by:Micheal Scofield
      Date:2014-03-02
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      18714. Can You Make It Empty 2

      Problem code: EMTY2


      You are given a string S with only 0 and 1. You can delete the string 100 from any position of S an infinite number of times and obtain a new S after concatenation. Is it possible to make the string empty?

      As for example, if S=101000 then 101000->100->empty

      If S=1010001 then 1010001->1001->1->not empty

      Input

      Input starts with an integer T (≤ 100), denoting the number of test cases.

      Each case contains a string S. The size of string is at most 120000.

      Output

      For each test case, print the case number and “yes” if it is possible to make the string S empty, print “no” otherwise.

      Sample Input

      Output for Sample Input

      2
      101000
      1010001

      Case 1: yes
      Case 2: no




      PROBLEM SETTER: MD ABDUL ALIM, DEPT. OF CSE, BUBT

      SPECIAL THANKS: RAIHAT ZAMAN NELOY, DEPT. OF CSE, JU


      Added by:Md Abdul Alim
      Date:2014-03-03
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      18715. Boring Factorials (Reloaded)

      Problem code: BORING


      Factorial is one of the most attractive word this week, it is proposed to reload a famous problem. Is it so boring ?

      Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot. Aman, their friend has been helping them out. But as it goes, Sameer and Arpit have got bored of problems involving factorials. Reason being, the factorials are too easy to calculate in problems as they only require the residue modulo some prime and that is easy to calculate in linear time. So to make things interesting for them, Aman - The Mathemagician, gives them an interesting task. He gives them a prime number P and an integer N (not so) close to P, and asks them to find N! modulo P. He asks T such queries.

      Input

      The first line of input contains an integer T, the number of test cases.
      On each of the next T lines, your are given two integers N, and P a prime number.

      Output

      For each test case, you have to print N! modulo P.

      Example

      Input:
      3
      2 5
      5 11
      21 71
      
      Output:
      2
      10
      6
      

      Constraints

      0 < T < 10^4
      0 < N < 4×10^18
      1 < P < 4×10^18, a prime number
      Abs(N-P) < 10^4
      

      Problem designed to be solvable using some 'slow' languages like Python (333B of code). It is highly recommended to solve in a very fast way the original problem! Basic solution, even in fast language should give TLE.
      Time limit is set as sqrt(correct × basic). The "basic" code gave me 0.00s to the original problem with slow IO.
      ;-) Have fun.


      Added by:Francky
      Date:2014-03-03
      Time limit:5.555s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:DCEPC11B









      SPOJ Problem Set (classical)

      18799. Boring Factorials (Extended)

      Problem code: BORING2


      Factorial is one of the most attractive word this week, it is proposed to reload a famous problem. Is it so boring ?
      As the reload edition wasn't hard enough, we'll extend constraints.


      Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot. Aman, their friend has been helping them out. But as it goes, Sameer and Arpit have got bored of problems involving factorials. Reason being, the factorials are too easy to calculate in problems as they only require the residue modulo some prime and that is easy to calculate in linear time. So to make things interesting for them, Aman - The Mathemagician, gives them an interesting task. He gives them a prime number P and an integer N (not so) close to P, and asks them to find N! modulo P. He asks T such queries.

      Input

      The first line of input contains an integer T, the number of test cases.
      On each of the next T lines, your are given two integers N, and P a prime number.

      Output

      For each test case, you have to print N! modulo P.

      Example

      Input:
      3
      2 5
      5 11
      21 71
      
      Output:
      2
      10
      6
      

      Constraints

      0 < T < 10^3
      0 < N < 10^100
      1 < P < 10^100, a prime number
      Abs(N-P) < 10^6
      

      Problem designed to be solvable using some 'slow' languages like Python (333B of code) in half the time limit.
      ;-) Have fun.


      Added by:Francky
      Date:2014-03-04
      Time limit:75s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:DCEPC11B









      SPOJ Problem Set (classical)

      18829. Special Set

      Problem code: SPEC_SET


      Little boy Sai is fascinated with Natural Numbers. He especially likes Special Sets of order k. A set of numbers S, is called Special Set of order k if, for any two numbers x and y (not necessarily distinct)  belonging to S, x should not be equal to k*y

      Now, Sai wants to find the size of maximum possible Special Set formed out of the numbers 1,2,3...n. Hope you can help him.

       

      Input

      First line contains t(1<=t<=105), the number of test cases. Next t lines contain two space separated integers n and k.

      1<=n,k<=108

      Output

      For each test case, output on a single line the size of maximal Special set.

      Example

      Input:
      1
      6 2
      
      Output:
      
      4
      Explaination:
      For the above case, the maximal Special set is: 1,3,4,5


      Added by:nitish rao
      Date:2014-03-04
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:My own Problem









      SPOJ Problem Set (classical)

      18857. Gopi and Sandwich

      Problem code: GOPI_SW


      Gopi is fond of sandwiches. Once his friend asks him to give part of his sandwich. But, Gopi wants to give him as little sandwich as possible. So, he devices a method.

      He divides the sandwich into n parts, where each part is a unit fraction( fractions of the form 1/p where p is integer) of the original sandwich. Among all these parts he chooses the smallest part and gives it to his friend. Help Gopi to find the smallest part possible.

      Input

      First line contains t(1<=t<=105) the number of test cases. The next t lines contain one integer per line denoting n(2<=n<=106) the number of parts the sandwich can be divided.

      Output

      Output one line per test case containing the denominator of the smallest part. Since, the answer can be very large, print Answer modulo 109 + 7

      Example

      Input:
      1
      3
      
      Output:
      6
      Explaination:
      The possible ways of dividing the sandwich into 3 parts are:
      1/3, 1/3, 1/3
      1/3,1/3,1/3
      1/6,1/2,1/3
      1/4,1/4,1/2
      Among these, the second way has the smallest part. Hence the output is 6
      
      1/6, 1/2, 1/3

      Added by:nitish rao
      Date:2014-03-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:My own Problem









      SPOJ Problem Set (classical)

      18878. Topper Rama Rao

      Problem code: HLP_RAMS


      Rama Rao is the topper of his branch. One of his friends was jealous of it. So, he poses a question to test Rama Rao and is as follows:

      For a given n, find the number of even and odd numbers among the set, { nC0, nC1,... nCn }.

      Rama Rao was having hard time solving it. He hopes you can help him.

      Input

      First line contains t( 1<=t<=105), the number of test cases. Next t lines contain one integer per line, denoting n(0<=n<=1012)

      Output

      For each test case, output two space separated integers specifying the number of even numbers and odd numbers respectively.

      Example

      Input:
      2
      3
      4
      
      Output:
      0 4
      3 2
      Explaination:
       for 3, values are: 1 3 3 1. All are odd. Hence 0 4
       for 4, values are: 1 4 6 4 1. Hence 3 2

      Added by:nitish rao
      Date:2014-03-06
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:My own Problem









      SPOJ Problem Set (classical)

      18905. Kapti and Balu

      Problem code: NR1


      Kapti and Balu are friends. Kapti is very good in math and is always saying that no one can challenge him in math. One day Balu decided to check Kapti that he is really good in math or he is just making fool.

      Balu gave Kapti a polynomial of degree “n”  and ask Kapti to find constant term “L” if the polynomial was first expressed in Factorial Notation and then subjected to Forward Difference operator for “k”  imes.

      If     

         f(x)=a1xn + a2xn-1 + ........... + anx + l                                                                                                              
      then its factorial notation will be:  

         fFN(x)=A1[x]n + A2[x]n-1 + .......... + An[x] + L                                                                                                                                  

      Where 

         [x]n=x(x-1)(x-2)......(x-n+1) 

      And forward difference operator Δ is just simple differentiation of  fFN(x).

      For example                                                                                                                 

      f(x)=2x3 - 3x2 + 3x - 10

      fFN(x)=2[x]3 + 3[x]2 + 2[x] - 10

      ΔfFN(x)=6[x]2 + 6[x] + 2  here constant term L=2 and k=1;

      Help kapti in proving himself that he is good in math.

      Input

      Input start with integer T(<30) denoting the number of test cases.

      Each test case will contains two lines,

      First line contains n(<=25) & k(<=n)

      Second line contains n+1 integers a1 a2 a3 ........ an l , -50<=ai<=50

      Output

      For each test case print one line containing  L.

      Example

      Input:
      

      1

      3 2

      2 -3 3 -10

      Output:
      6
      

      Added by:NISHANT RAJ
      Date:2014-03-08
      Time limit:0.001s-0.200s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      18915. Anils Proposal

      Problem code: ANIL_PRO


      Anil is the best coder in his class. He is in love with his classmate Gowthami. One day he proposes her. She wants him to prove that his love is actually true. So, she poses the following problem:

      There is an array of size n. Initially all the elements are zero. Now there will be two types of operations:

      1) Update the array.

      2) Query the array.

      In case of update, you will be given a range [l,r]. To the kth element in this range ( l and r inclusive), you need to add kth fibonacci number.

      In case of query, you will be given a range [l,r], for which you need to find the sum of all elements in the range(including l and r).

      Anil hopes you can help him in this regard.

      Input

      The first line contains n(1<=n<=106and q(1<=q<=5*104), the number of operations to be performed. The next q lines contain 3 space separated integers. If the first integer is 0, then its an update operation. If it is 1, then its a query operation. The next two integers specify l and r(1<=l<=r<=n)

      Output

      For each query print one integer per line specifying the sum in the corresponding range. Since the sum can be very large, output Answer modulo 109 + 7

      Example

      Input:
      5 6
      0 1 5
      0 2 4
      0 1 3
      1 2 4
      1 1 5
      1 4 5
      5 6
      Output:
      13
      20
      10
      Explaination:
      After the first update the array looks as follows:
      1 1 2 3 5
      After 2nd update:
      1 2 3 5 5
      After 3rd update:
      2 3 5 5 5
      
      Hence from the above array, we have the outputs for the queries.
      Note:
      Fibonacci Series starts as 1,1,2,3,...

      Added by:nitish rao
      Date:2014-03-09
      Time limit:0.5s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:My own Problem









      SPOJ Problem Set (classical)

      18917. Dukkar and Pikka

      Problem code: DUKKAR


      Pika and Dukkar are roomie. Pika is a nerd and likes to play with mathematics! Pika's favourite topic is pascal triangle and he proclaims that he can solve any problem related to this. So Dukkar decides if it's really true!

      Dukkar gives a number N and a prime number P. N is the Nth row of pascal triangle starting with 0. Dukkar asks Pika to find how many numbers in nth row are divisible by P. Since the number can be very large so, Pika has to write a program. Since end sem are coming and Pika has to top in his batch so he asks you for help. Can you help Pika?

                                        pascal triangle

      Input

      The first line of the test file will contain T(T<100000) where T is the no. of test cases. Each of the next T lines will contain two integers N(0<=N<=1018)  and P(2<=P<=105) as defined above.

      Output

      For each test case print on each line K the number of numbers divisible by P on Nth row of the pascal triangle.

      Example

      Input:
      2
      2 2
      7 7
      
      Output:
      1
      6

      Added by:NISHANT RAJ
      Date:2014-03-09
      Time limit:0.100s-0.800s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      18932. Sum of primes (reverse mode)

      Problem code: SUMPRIM2


      XerK had prepared his new problem with some sums of primes up to some bounds.
      His results are well here, but he forgot the bounds.
      Your task is to find which was the last prime in the sum.
      This problem is extremely simple, but you have to be extremely fast.

      Input

      The lonely line of input contains an integer S.

      Output

      You have to print the last prime P such that sum(prime from 2 to P) = S.

      Examples

      Input_1:
      77
      
      Output_1:
      19
      
      Input_2:
      24739512092254535
      
      Output_2:
      999999937
      

      Explanation

      The first sum was

      2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 = 77

      Constraints

      0 < P <= 10^12
      

      The classical problem SUMPRIM1 is the reverse task.
      Time limit is set to allow some slow languages to finish in time, it could be hard.
      For your information, my Python code got AC in 76s for a total of 20 input files.
      ;-) Have fun.


      Added by:Francky
      Date:2014-03-09
      Time limit:8s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      18937. Touch of Venom

      Problem code: VENOM


      Sometimes you have to try fighting even though you know that your enemy is very powerful than you. Your hero with initial health H is about to fight against a venomous enemy who has a poisonous value of P. The enemy's poison deals i*P damage at it's ith attacking chance(i>=1). The hero dies when his health becomes <=0. After enemy's attack, if the hero survives, he heals himself with a health of A by using his skills. Then the enemy gets the chance again and the cycle continues till the hero dies. Find the survival time of the hero. You can safely assume that the hero is mortal.

      Example Scenario:

      Initial Health(H) = 10, Poison (P) = 2, Heal value(A) = 1

      At time 1, enemy does 1*2 damage reducing the hero's health to 8

      At time 2, hero heals himself by 1 increasing his health to 9

      At time 3, enemy does 2*2 damage reducing the hero's health to 5

      At time 4, hero heals himself by 1 increasing his health to 6

      At time 5, enemy does 3*2 damage and kill the hero.

      The hero survived 5 units of time.

      Input:

      The first line consists of an integer t, the number of test cases. For each test case there is a line with 3 integers H, P and A.

      Output:

      For each test case, find the survival time of the hero.

      Input Constraints:

      1<=t<=10^6

      1<=H<=10^6

      1<=P<=10^6

      0<=A<P

      Sample Input:

      3

      3 7 2

      81 4 1

      87 8 4

      Sample Output:

      1

      13

      9


      Added by:cegprakash
      Date:2014-03-10
      Time limit:0.75s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      18939. K-th smallest number

      Problem code: KSMALL


      Given an array of (pseudo) random numbers generated by the C++ function below, your task is to find the K-th smallest number of all the numbers.

      unsigned array[5000000];
      
      void randomize(unsigned a,unsigned b,unsigned mod)
      {
      	for( int i=0 ; i<5000000 ; i++ )
      	{
      		a = 31014 * (a & 65535) + (a >> 16);
      		b = 17508 * (b & 65535) + (b >> 16);
      		array[i] = ((a << 16) + b) % mod;
      	}
      }

      Note that the computation might overflow, but we only care about the last 32 bit of each result so it doesn't matter.

      Input

      One line with 4 numbers (a, b, mod, K) separated by space.

      0 < a, b < 65535

      < mod < 232-1

      1 < K < 5x106

      Output

      K-th smallest number of all the generated numbers.

      Example

      Input:
      2 3 100000007 23
      
      Output:
      434

       

      Time limit has been rescaled, STL solution will not pass (some slower non-STL solution still pass).


      Added by:Andy William
      Date:2014-03-10
      Time limit:0.810s-2.25s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      18940. Face the mate

      Problem code: FACENEMY


      Hero Heroine
      Hero and Heroine are standing on a 2D plane. Hero is standing at (x1,y1) facing towards (u1,v1) and the heroine is standing at (x2,y2) facing towards (u2,v2), both trying to find the location of the other one. Both of them are lazy and they don't move. Instead, they just change the direction they face, standing at the same position. To make things easier, both of them starts scanning simultaneously with same rotation speed. To make things even more easier, assume that they choose the direction which will help to find their mate as fast as possible. Print "Hero" if the Hero finds Heroine faster; print "Heroine" if the Heroine finds Hero faster. Print "0" otherwise.

      Assume that both of them don't have any field of view and all they can see are the points in the straight line that they face.

      Input:

      The first line consists of an integer t, the number of test cases. For each test case, the first line consists of 8 non-negative integers x1,y1,u1,v1,x2,y2,u2 and v2.

      Output:

      For each test case, print the result in the required format as specified in the problem statement.

      Input Constraints:

      1<=t<=500000

      0<=xi,yi,ui,vi<=100

      (x1,y1) != (x2,y2) Both players are located at different positions.

      (x1,y1) != (u1,v1)

      (x2,y2) != (u2,v2) Players don't face their own locations.

      Sample Input:

      10
      9 3 6 0 4 4 6 6
      1 8 6 3 4 9 7 8
      8 2 3 5 9 1 9 8
      4 0 3 6 7 6 1 5
      4 2 7 3 0 9 7 2
      6 0 5 7 1 6 5 4
      1 2 1 4 0 0 6 0
      7 1 7 7 7 7 3 3
      5 9 1 8 9 8 2 6
      6 0 0 1 3 8 2 5
      

      Sample Output:

      0
      Hero
      Heroine
      Hero
      Heroine
      Heroine
      Heroine
      Hero
      Heroine
      Heroine
      

      Added by:cegprakash
      Date:2014-03-10
      Time limit:2.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      18941. True Friends

      Problem code: TFRIENDS


      You are given a string array representing Known people. Known[i][j]='Y' if i knows j.

      Friends: A is a friend of B if B knows A or B has a friend who knows A.

      True friends: A and B are true friends if A is a friend of B and B is a friend of A.

      Group: Everyone in a Group must be true friends to each other.

      Your task is to find the number of Groups from the given list of Known people. It can be proved that there is exactly only one possible way for forming the groups.

      Input: The first line consists of an integer t, the number of test cases. For each test case, you are given an array of strings representing Known people. Known is of size NxN where N is the total number of people.

      Output: For each test case, print the number of Groups.

      Input Constraints:

      1<=t<=1000

      1<=N<=100

      Known[i][j] is either 'Y' or 'N'

      Known[i][i]='N' (No one is known to themselves)

      Sample Input:

      3
      3
      NYN
      NNY
      YNN
      7
      NNYNNNN
      NNNYYYN
      NNNNNNN
      YNNNNNN
      NNNYNNN
      NNNNNNN
      NNNNNYN
      7
      NNNNYYN
      NNNNNNN
      NNNNNYN
      NYNNNYY
      NNNYNNN
      NNYNNNY
      NNNNYNN

       

      Sample Output:

      1
      7
      3

       

      Explanation:

      Case 1: All the friends are true friends to each other

      Case 2: No two true friends exist.

      Case 3: There are 3 groups of true friends. {0}, {1}, {2,3,4,5,6}


      Added by:cegprakash
      Date:2014-03-10
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      18945. Car with powers

      Problem code: POWERCAR


      Car with Powers race track

      The race track is a straight line with starting point at Track[0] and ending point at Track[n-1]. The car is initially at Track[0].

      Track[i]='#' if the track has a wall at Track[i].

      The car can move from Track[i] to Track[i+1] if and only if Track[i+1] is not a wall. The time taken to move from Track[i] to Track[i+1] is 1 unit.

      If there is a wall at Track[i+1], you can shoot it from Track[i] if you have enough bullets in the car. Once a bullet is fired, the bullets count will decrease by 1. The time required to fire a bullet is 0.

      It is also allowed to ride the car off the track. It's allowed to move from Track[i] to offTrack[i], from offTrack[i] to offTrack[i+1] and from offTrack[i] to Track[i] (if Track[i] is not a wall). The time taken for any of these steps is 2 units.

      Find the fastest possible time to finish the race. Print "Impossible" if it's impossible to finish the race.

      Input:

      The first line consists of an integer t, the number of test cases. For each test case, the first line consists of two integers the length of race track n and the number of bullets the car can fire followed by a line with a string representing the Track.

      Output:

      For each test case, print the expected result as specified in the problem statement.

      Input Constraints:

      1 <= t <= 100

      2 <= n <= 1000

      1 <= bullets <= 1000

      Track[i] ∈ {'S','E', '0', '#'}

      Track[0]='S', Track[n-1]='E'

      Sample Input:

      10
      7 3
      S00000E
      2 2
      SE
      4 1
      S00E
      8 1
      S0000##E
      8 3
      S0#00#0E
      7 2
      S0#0##E
      10 4
      S00#0#0##E
      5 2
      S000E
      7 1
      S0##00E
      9 0
      S0000##0E
      


      Sample Output:

      6
      1
      3
      13
      7
      12
      9
      4
      12
      15



      Added by:cegprakash
      Date:2014-03-10
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF









      SPOJ Problem Set (classical)

      18963. Bhagat The Bit Man

      Problem code: NR2


      Bhagat is student of CSE at ISM Dhanbad. In mid-semsester exam somehow he was able to score full marks in Boolean algebra. So his profs doubt how can he score full marks. So profs decided to check his ability .They gave Bhagat a list student’s admission number and ask him to find total kaptiness (K) of list.

      Kaptiness is defined as or operation on every dukkerness(di) value. Dukkerness value is xor operation on every pair of number in list.As we all know Bhagat is not good in Boolean algebra .Can you help him to prove his profs that he can score full out of full in boolean algebra.

      Example:-

      If list contain three number 10,15 & 17.Then there will be total 3 pairs .

      d1=10^15=5;

      d2=10^17=27;

      d3=17^15=30;

      k= d1 | d2 | d3 ;

      K=31;

      Input

      First line of input contain N(2<=N<=106) .N is total number of admission number(ai) in list.

      Then following N line will contain admission number.(0<= a<=1018)

      Output

      Output only one line containing K.

      Example

      Input:
      3
      10
      15
      17
      
      Output:
      31
      
      NOTE: Large input data .
      test cases have been updated and all solutions are rejudged .

      Added by:NISHANT RAJ
      Date:2014-03-11
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      19037. The colors of cats

      Problem code: COLORCAT


      There is a circle with n cats, includes white cats, red cats and green cats. When two cats with different color talk with each other, they both change to third color. If they are same color, nothing will happen.

      At i-th step, the 1st cat talks with 2nd cat, the 2nd cat talks with the 3rd cat,… and the nth cat talks with 1st cat.

      Given the original color of n cats, your task is find the color of n cats after k steps.

      Input :

      -       First line : n and k (1 ≤ n ≤ 20000, 1 ≤ k ≤ 30000)

      -       Second line : n characters, the i-th charater denotes color of the i-th cat at first state

      Output :

      -       n charaters denotes the color of n cats after k steps.

      Sample :

      Input :

                  3 1

                  GRR

      Output :

                  RGR

      Input :

                  5 4

                  WRWRW

      Output :

                  GGGWG


      Added by:Kata
      Date:2014-03-13
      Time limit:0.300s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource: Ngô Minh Ðức









      SPOJ Problem Set (classical)

      19039. Krypt in Time

      Problem code: KIT


      Krypt in Time

       

      In a land far away people can travel back in time in person or send messages to them in the past. Sending messages that can change ones future is forbidden. The messages that are sent are intercepted by the time police.  Jim wants to send a message to himself in the past to prevent his death. He decides to encrypt using a "number-pad".  All the numbers in number-pad are between 0 and 25. The message he wants to send can be encrypted if each character in the string is encoded by a number from the pad provided each number from the number- pad is only used once. The encryption is done by shifting each letter in the message by k positions, where k is determined by the number-pad. Shift occurs between the alphabets "a" and "z". If a letter in the message is shifted past "z" then it starts back at "a" and continues to shift.

      For example:  If the number-pad contains 2, the message abc is transformed to cde and xyz to zab.

       

      Input Format

      The first line will contain the size of the number-pad N, followed by a sequence of numbers for the pad. The remaining input consists of a series of words to be encrypted using the number-pad. You may assume that the maximum size of the pad (N) is 100 numbers, all numbers in the pad are between 0 and 25, and that all input will be lowercase letters. The end of input is indicated by -1.

       

      Output Format

      For each word to be encrypted, output a line containing the encrypted word.

       

      Example

      Input 1:
      10
      1 2 3 4 5 4 3 2 1 0
      aa aaa
      zzzzz
      -1

      Output 1:
      bc
      def
      dcbaz


      Added by:Arjun Krishnan
      Date:2014-03-13
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C# C++ 4.3.2 C++ 4.0.0-8 JAVA PHP PYTH 2.7









      SPOJ Problem Set (classical)

      19084. Huge Pascal triangle

      Problem code: DUKKAR2


      Given P a prime number, and N an integer, Dukkar found a really fast way to compute how many numbers are divisible by P on the Nth row of the Pascal triangle. Now the task will be much harder : it's for all the N first rows.
      Moreover N will be a giant number, given in base P for convenience.

      Input

      The first line of input contains an integer T, the number of test cases. Follow 2×T lines.
      For each test case, on the first line your are given two integers P and k.
      On the second line you are given k integers : the digits of N in base P.

      N = a0×P0 + ... + ak-1×Pk-1

      Output

      For each test case, you have to print the number of numbers in all the first N rows of the Pascal triangle that are divisible by P. As the answer could not fit in a 64bit container, give your answer modulo 1000000007.

      Example

      Input:
      3
      5 2
      0 1 
      5 2
      1 1
      7 3
      2 0 2
      
      Output:
      0
      4
      2689
      

      Explanations

      For the first case, N = 0×50 + 1×51 = 5. No numbers are divisible by 5 in the first 5 rows.
      For the second case, N = 1×50 + 1×51 = 6. Only 4 numbers are divisible by 5 in the first 6 rows.

      1
      1 1
      1 2 1
      1 3 3 1
      1 4 6 4 1
      1 5 10 10 5 1
      
      For the third case, N = 2×70 + 0×71 + 2×72 = 100.

      Constraints

      0 < T < 300
      0 < P < 10^9, a prime number
      0 < l < 1000
      0 <= ai < P
      

      For your information, my 300B-python3 code get AC in 3.03s with 11MB of memory print.
      My C-code get AC in 0.08s with 1.6MB of memory print.
      Have fun ;-)


      Added by:Francky
      Date:2014-03-17
      Time limit:6s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      19125. Hexadecimal value of Pi

      Problem code: PIHEX2


      PIHEX2

      All people use decimal system every day. For all of us the value of Pi is 3.141592653589793238462643383279....

      But there is common to use hexadecimal system in programming. The hexadecimal value of Pi is 3.243F6A8885A308D313198A2E037073....

      In this problem for given a, You should compute the digit, that appears in hexadecimal representation of Pi at ath position after comma (for a=0 the answer is '3' - the only digit before comma, for a=1 the answer is '2' - the first digit after comma; see example for clarify).

      Input

      The first line of input contains single integer t - the number of test cases (1 ≤ t ≤ 20).

      The second line of input contains t single-space separated integers a1, a2, ..., at (0 ≤ ai ≤ 1000000).

      Output

      The only line of output should contain t hexadecimal digits (use capital letters A-F), where ith digit appears in Pi hexadecimal representation at aith position.

      Example

      Input:

      16
      0 1 2 3 4 5 6 7 8 9 10 100 1000 10000 100000 1000000

      Output:

      3243F6A8885C3652

      Added by:miodziu
      Date:2014-03-19
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19133. Base Conversion

      Problem code: BASECONV


      Leo didn't do all the job in his last problem, somebody gave him the numbers in a convenient base. It was the bottleneck of the problem... Now your task is to do this job.

      Input

      The first line of input contains three integers T, the number of test cases, B1, the first base, B2, the second base.
      Follow 2×T lines.
      For each test case, on the first line your are given one integer k.
      On the second line you are given k integers : the digits of N in base B1.

      N = a0×B10 + ... + ai×B1i + ... + ak-1×B1k-1

      Output

      For each test case, you have to print the number N in base B2. See sample for details.

      Example

      Input:
      1 10 100
      5
      5 4 3 2 1
      
      Output:
      3
      45 23 1
      

      Explanations

      For the lonely case, N = 5×100 + 4×101 + 3×102 + 2×103 + 1×104 = 12345.
      We have: N = 45×1000 + 23×101 + 1×102. You have to print 3, the number of digits, then the digits: 45, 23 and 1.

      Constraints

      0 < T <= 50
      1 < B1,B2 <= 10^9
      1 < k <= 10000
      0 <= ai < B1  , ak-1>0
      

      Time limit is sqrt(T_basic_pike_code * T_awaited_python_code) = sqrt(13.34*6.97), based on my Python3/Pike experiments.
      You may try before the tutorial edition.
      Have fun ;-)


      Added by:Francky
      Date:2014-03-19
      Time limit:9.630s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      19139. Boiling Vegetables

      Problem code: BOILING


       

      The trick to boiling vegetables is to make sure all
      pieces are about the same size. If they are not, the small
      ones get too soft or the large ones get undercooked (or
      both). Fortunately, you have heard of the kitchen knife,
      but your parents’ warnings of using sharp instruments
      still echoes in your head. Therefore you better use it as
      little as possible. You can take a piece of a vegetable of
      weight w and cut it arbitrarily in two pieces of weight
      wleft and wright, where wleft + wright = w. This operation
      constitutes a “cut”. Given a set of pieces of vegetables,
      determine the minimum number of cuts needed to make the ratio between the smallest and the
      largest resulting piece go above a given threshold.

      The trick to boiling vegetables is to make sure all pieces are about the same size. If they are not, the small ones get too soft or the large ones get undercooked (or both). Fortunately, you have heard of the kitchen knife, but your parents’ warnings of using sharp instruments still echoes in your head. Therefore you better use it as little as possible. You can take a piece of a vegetable of weight w and cut it arbitrarily in two pieces of weight wleft and wright, where wleft + wright = w. This operation constitutes a “cut”. Given a set of pieces of vegetables, determine the minimum number of cuts needed to make the ratio between the smallest and the largest resulting piece go above a given threshold.

       

      Input

      The input starts with a floating point number T with 2 decimal digits, 0.5 < T < 1, and a positive integer N  1 000. Next follow N positive integer weights w1, w2, ..., wN. All weights are less than 106.

      Output

      Output the minimum number of cuts needed to make the ratio between the resulting minimum weight piece and the resulting maximum weight piece be above T. You may assume that the number of cuts needed is less than 500.

      To avoid issues with floating point numbers, you can assume that the optimal answer for ratio T is the same as for ratio T + 0.0001.

      Example

      Input 1:
      0.99 3
      2000 3000 4000
      
      Output 1:
      6
      
      Input 2:
      0.80 2
      1000 1400
      
      Output 2:
      3

      Added by:Fernando Fonseca [ITA]
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:NCPC 2013 (under CC BY-SA 3.0)









      SPOJ Problem Set (classical)

      19142. BSTRING

      Problem code: INS14A


      In his next interview digo is given a binary string of N characters. A binary string is string consisting of only 0's and 1's. Digo can swap any adjacent pair of characters in one operation. Digo has to bring atleast M 1's together starting at any position of the string. Help him count the minimum number of operations required to do so.
      It is gauranteed that there are atleast M 1's present in the given string.

      Input Format:

      First line contains single integer T. Number of test cases.
      Next 2 * T lines represent T test cases. Each test case is described by two lines; first line contains a single integer M and the second line contains the input binary string.

      Output Format:

      Output T lines, one for each test case containing the answer for that case.

      Constraints :

      1 <= T <= 10
      1 <= N <= 50000
      1 <= M <= N

      Sum of N over all the cases if less than or equal to 50000.

      Sample Input:

      2
      3
      101001
      2
      101001

      Sample Output:

      3
      1


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19143. TRISQRS

      Problem code: INS14B


      After coming back from the ACM World Finals '13, Digo decided to celebrate his performance by watching a lot of action movies. Sitting in front of his laptop for days watching his favourite stars battle it out, Digo suddenly got inspired to join the CIA. Digo is a serious man, and vowed that he'd be inducted in the CIA force by the end of the year. And mind you, he takes his vows very seriously! 

      After sweating it out in the field for months, it's finally time for his interview. The interviewer believes that mental agility is as important as physical fitness and decides to test our hero with a mathematical puzzle.

      The interviewer hands Digo a square of side N and asks him to partition the square into a number of right angled triangles, each having an equal integral area. Two sides of the triangle should be parallel to the two sides of the square. Being an ACM World Finalist, Digo solves the question in a split second. Impressed, the interviewer decided to test him with a harder question. He asks Digo to tell him the number of such partitions possible. All partitions having the same number of right triangles are considered the same. 

      Input Format:-

      First line will contain T, the number of test cases. Next T lines will contain a single integer each N, denoting the size of the square.

      Output Format

      Output one line for each test case. Each line contains one integer which is the desired solution

      Constraints:- 

      1<=T<=1000
      1<=N<=1000

      Sample Input

      2
      1
      2

      Sample Output

      0
      2


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19144. Digo plays with Numbers

      Problem code: INS14C


      Digo and his friend Sharry have completed their missions and were relaxing. Both of them love mathematics and love to play with numbers. They have a book in which several binary strings are written. Digo comes up with an idea of an interesting game. He asks Sharry to think of a number K, which is less than or equal to the length of the string N. Both players play alternately. In his turn, a person can remove any bit from the binary string. Digo removes such as to maximize the value of the leftover binary string while Sharry plays to minimze the string. This process continues till K binary digits are left. You have to tell those K binary digits left after the game is over.

      It is given that Sharry always plays first.

      Input Format:-

      The first line consists of a single integer T, denoting the number of test cases.
      2*T lines follow. For every test case, the first line consists of two integers N and K, denoting the initial length of the string and its length at the end of the game. The second line for the test case contains the initial binary string of length N.

      Output Format:-

      For each test case print the final string left after removal of characters.

      Constraints:-

      1 <= T <= 1000

      1 <= N <= 1000

      1 <= K <= N

      Sample Input:

      2
      5 3
      10010
      4 2
      1111

      Sample Output:

      010
      11


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19145. Digo Needs Guns

      Problem code: INS14D


       

      Digo was given the task to secure a very important room where many famous personalities were residing. So the government provided him with some automated guns which he could fit on the line of intersection between any two walls in the room. The guns can rotate anywhere about the point on the line they are placed, but cannot shoot through walls. Since the country was suffering from financial crisis and automated guns were very expensive, Digo thought of using the minimum number of guns and returning the rest. But Digo did not know the configuration of the room as it was very confidential. He just knew the number of sides the room had. The shape of the room can be any simple polygon. What is the minimum number of guns he must carry with him so it is possible for him to secure every possible polygonic room having n walls.


      Input:-

      The first line consists of a single integer T denoting the number of test cases.
      T lines follow each containing an integer N denoting the number of sides.

      Output:-

      For each test case print the required answer.

      Constraints:-

      1 <= T <= 1000000

      3 <= n <= 1000000000


      Sample Input :

      1
      4

      Sample Output :

      1

       

      Note : This question has large I/O files, faster I/O methods are needed to get an AC.


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19146. Glorious Gamblers

      Problem code: INS14E


       

      Back in 2012 when Digo and Tourist were training for their CIA Assignments, they became good friends. Digo was a skeptical fellow and believed that the world would end that year. Tourist however believed all this did not make any sense. After countless arguments leading to no conclusion, Digo and Tourist finally decided to place a bet on it and move on.

      It is 2014 and they meet again on their first assignments. Quite evidently, Digo was proved wrong, and it's time for him to pay back the bet. Both Digo and Tourist being good programmers, they decided to have some fun with the bet. The money that Digo needs to pay Tourist can be expressed in the form of a payoff matrix for Digo. The payoff matrix A[][] is an M*N matrix where every element is a positive integer.

      They place a ring on the cell (1,1); and the game ends when the ring wounds up on the cell (M,N). When the ring is on the cell (i,j), they toss a fair coin. If it is a heads, it is Digo's turn to move and if it's a tails it is Tourist's turn. In one turn, a person can move the ring from cell (i,j) to either one cell east, one cell south, or one cell south-east. The ring cannot be moved outside the bounds of the payoff matrix.

      The money that Digo need to pay Tourist is the sum of the elements that lie on the path traversed by the ring. Both being logical fellows, Digo would want to minimize the overall money that he needs to pay, while Tourist would want to maximize it.

      Help Digo find out the expected money that he would owe Digo at the end of the game. (correct to exactly 6 decimal places)

      NOTE: LARGE INPUT FILES. USE FASTER I/O. 

      Input Format:

      The first line contains T, the number of test cases.

      For every test case, the first line contains two integers M,N; the dimensions of the matrix.

      The next M lines contain N integers each, such that the jth element on the ith line is the element A[i][j] in the payoff matrix.

      Output Format:

      For every test case, output exactly one result, which is the expected value of the money that Digo would own Tourist at the end of the game (correct to exactly 6 decimal places).

      Constraints:

      1<= T <=10
      2 <= M,N <= 500
      0 <= A[i][j] <=10^6


      Sample Input

      1
      2 3 
      1 2 2
      3 5 1

      Sample Output

      8.250000

       

       


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19147. Save CodeVillage

      Problem code: INS14F


      In another test the terrorists have occupied CodeVillage. The village consists of N buildings. Each building is connected to every other building with a road. Each terrorist has been told to cover a single strip of K buildings along any path. A path is a set of roads connecting a particular set of buildings in which the buildings will not be repeated and every adjacent pair of roads share a common building. 

      Each terrorist will be given a distinct path. Two paths are different if at least one building is different or the order of visiting the buildings is different. For example a path from building numbers 1 -> 2 -> 3 is different from a path from building numbers 1 -> 3 -> 2. 

      Now so as to improve coordination between the terrorists, they had decided that every terrorist should meet all other terrorists along the path.Thus there should be at least one common building in every pair of paths. 

      Digo must take enough artillery to kill all the terrorists but not much more due to the ongoing recession problems. So help him calculate the maximum number of terrorists that may be present in the village. Give your answer modulo 10^9 + 7.

      Input Format:-

      The first line contains a single integer T denoting the number of test cases. 
      T lines follow each containing two space separated integers N and K.

      Output Format:-
      For each test case output the maximum possible terrorists modulo 10^9 + 7.

      Constraints:-

      1 <= T <= 100000
      1 <= K <= N <= 1000000

      Sample Input:-

      2
      3 2
      5 3

      Sample Output:-

      6
      60


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19148. Kill them All

      Problem code: INS14G


       

      For his training, Digo is asked to solve the following challenge.

      There is a mock terrorist situation. There are N terrorists and Digo is teamed up with his friend Sharry. They have to kill all the terrorists. Since this was too easy a task for this dynamic duo, Digo decided to have some fun with this challenge. At any given instant, Digo wants that the number of terrorists killed by him should be more than those killed by Sharry. The terrorists come in a fixed order. Any terrorist can be killed by either Digo or Sharry. Give the total number of ways in which the terrorists can be killed by them such that at every instant terrorists killed by Digo is more than the number of terrorists killed by Sharry. Give your answer modulo 10^9+7.

      Input Format:-

      The first line consists of a single integer T, denoting the number of test cases.
      T lines follow each consisting of an integer N denoting the total number of terrorists.

      Output Format:-

      For each test case print the total number of possible ways modulo 10^9 + 7.

      Constraints:-

      1 <= t <= 100000
      1 <= n <= 1000000

      Sample Input:-

      2
      1
      3

      Sample Output:-

      1
      2

       


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19149. Virus Revisited

      Problem code: INS14H


       

      Due to the failed experiment in the laboratory of our scientist Digo, a new universe of N dimensions is created with one single virus at origin at time T=0. 

      Each point in this new universe can be represented by a linear array of indices (c1, c2, c3, ... cn) where ci represents the i th coordinate. In this new universe we are interested in only integer points i.e, points with integer coordinates. Two points (a1, a2, ...an), (b1, b2, ...bn) are adjacent to each other if sum of abs(ai - bi) for all i is equal to 1 (abs() is the absolute value function). If observed carefully one can observe that there are 2*N adjacent points for every point in the universe. Origin is (0, 0, ...n times). 

      The virus reproduces very rapidly. After every second it gives birth to 2*N identical new viruses of its kind and dies. As the newly born viruses are born, each of them moves to a distinct point, each of which are adjacent to the point at which the parent was present. New Viruses reproduce at their respective points and this procedure goes on. As the viruses are very small, any number of viruses can stay at a single point.

      Now Our Scientist Digo has Q queries. In each query he gives you two integers N and T, and you need to tell him how many viruses are present at the origin in N dimension universe at the end of T seconds.

      As the Output can be huge print each output modulo (10^9 + 7). 

      Input Format:

      First line contains a single integer Q representing the number of queries.
      Q lines follow with two space separated integers N and T in each line. N, T have their respective meanings mentioned in the problem statement.

      Output Format:

      Print a single integer for every query in a separate line.

      Constraints :

      1 <= Q <= 20000
      1 <= N <= 100
      1 <= T <= 200

      Sample Input : 

      3
      1 2
      2 3
      3 2

      Sample Output:

      2
      0
      6

       

       


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19150. Infinite Sequence

      Problem code: INS14I


      Digo and Sharry like to play with numbers and sequences. They decide to write an infinite sequence. For this they start by choosing a number each. They start making the sequence by following these rules : 

      (i)Digo writes his number on a piece of paper. This is the 0th number of the sequence.
      (ii)Then Sharry writes his number on the paper, as many times as Digo’s number. eg if Digo wrote 2, then Sharry would write his number 2 times, making the total sequence of length 3.
      (iii)Then Digo writes his number on the paper, which becomes the next element of the sequence.
      (iv)Then Sharry writes his number as many times as the number indexed 1 in the sequence.
      (v)Then Digo writes his number on the paper, which becomes the next element of the sequence.
      (vi)Then Sharry writes his number as many times as the number indexed 2 in the sequence.
      ….

      And the cycle goes on.

      Now Digo starts to feel that the sequence that they are generating is very trivial. He claims he can tell the digit at the nth place without having to play the game. So Sharry challenges him to tell the digit which will come at the nth place.

      Help Digo complete Sharry's challenge.

      It is given that Digo chooses 4 as his number and Sharry chooses 5 as his number.

      Input Format:- 

      First line of the input contains an integer T - the number of testcases.
      T lines follow, each containing an integer N.

      Output Format:- 

      Print T lines. For every test case, print the digit that appears in the Nth place.

      Constraints : 

      1 < T < 100
      0 <= N < 1000000000

      Sample Input : 

      3
      0
      4
      7

      Sample Output : 

      4
      5
      5


      Explanation : 

      The sequence is 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5 ...

       


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19151. Checkers

      Problem code: INS14J


      Digo has completed all his initial assignments and is now eyeing for a promotion in the CIA office. There is only one seat available for which there are two contenders, Digo and his arch rival Sharry. Both are equally qualified for the promotion and their interviewer finds himself unable to chose between the two of them. Finally he decided to settle it by allowing the two gentlemen to play a game and see who wins it.

      In the game, there is an infinite grid, with certain cells filled with checkers. Each checker occupies exactly one cell, and the cells are 0-indexed. The positions of the checkers are given in the form of Cartesian coordinates (x,y).

      For example a grid with 5 checkers placed at positions {(1,0), (1,2),(2,5),(4,2),(4,4)} would look like:



      There are an infinite number of diagonals of the form y=x+k, where k is an integer, drawn on this grid. Each diagonal can be uniquely identified by the value of this 'k', which is known as the index of the diagonal. There is atmost one checker on every diagonal. In one turn, a person can chose a checker and move it along the diagonal it lies on, in the south-west direction only (ie, towards decreasing coordinates). The checkers cannot be moved outside the first quadrant (i.e., their coordinates can never be made negative throughout the game). Whenever a person moves a checker, the checker lying on the next higher occupied diagonal moves an equal distance along the north-east direction. A diagonal with a Greater value of index is said to be higher than a diagonal with a greater index. Thus if the person moves the checker at position (4,2) {diagonal index 2} one cell south-west, the checker at position (1,0) {diagonal index 1} moves one cell north-east.

       

      The final position of the checkers after this move would be:



      Note that if a person moves the checker lying on the highest occupied diagonal (the checker at position (2,5) in our case), no other checker is disturbed. 

      The game ends when no move is possible. The last person to make a move wins. Sharry is an over-confident guy and allows Digo to move first. Help Digo determine whether he will win the game or not.

      NOTE: LARGE INPUT FILES. USE FASTER I/O. 

      Input Format:

      The first line contains T, the number of test cases.
      The first line of every test case contains N, the number of checkers on the grid. This is followed by N lines. The ith line contains two integers x[i] and y[i], which are the coordinates of the ith checker.

      Output Format:

      For every test case output a single line containing "Yes" if it is possible for Digo to win the game, or "No" otherwise. (quotes added for clarity)

      Constraints:-

      1 <= T <= 20
      1<= N <= 10000
      0<= x[i],y[i] <= 1000000000

      Sample Input:

      1
      5
      1 0
      1 2
      2 5
      4 2
      4 4

      Sample Output:

      Yes


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19152. Digo Goes Training

      Problem code: INS14K


       

      Digo is being trained for shooting as it is a very integral part of his missions. His trainer sets up a training arena for him to practice for it. Digo is taken to the ground where many strong penetrable walls are placed in arbitrary manner. Consider the ground to be a rectangular grid with cartesian coordinates. Digo fires the bullets from a given point on the X-axis. The bullets can only travel parallel to the Y-axis. Given the endpoints of the walls and Digo's current position on the X-axis, he wants to know how many walls he will penetrate with each shot. The shots will only penetrate the wall, they are not powerful enough to break them. As he is very weak in mathematics, he asks you to help him.

      Input :

      The first line consists of the number of test cases, T.
      The second line contains the number of walls N.
      Then N lines follow. Each line contains 4 integers denoting the endpoints of the walls i.e. x1 y1 x2 y2.
      Next line denotes Q, the number of queries.
      Queries can be of two types:
      1 x1 y1 x2 y2 : which denotes the endpoints of new wall placed.
      0 pos : where pos tells about the x coordinate of Digo’s position. The position will be a floating point number.having exactly two digits after the decimal.

      Output Format:

      Output one line for each query of form 0. For each query of the form ‘0 pos’ output the numbers of walls penetrated.

      Input Constraints:

      1 <= T <= 10
      1 <= N <= 1000
      1 <= Q <= 1000
      0 <= x1, y1, x2, y2 <= 20000
      0.00 <= pos <= 20000.00

      Sample Input:

      1
      3
      3 5 7 8
      1 3 5 6
      2 4 8 9
      4
      0 6.73
      1 4 7 9 8
      1 2 5 6 3
      0 3.55

      Sample Output:

      2
      4

       

       


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19153. Rooted Trees

      Problem code: INS14L


       

      Digo is given a rooted tree where nodes are numbered from 1 to N (1 is the root node) and asked some queries on it. 
      There are two types of queries
      1) Given node number U, two integers X, K which means add X to the given node , X+K to its children , X+2*K to children of its children and so on..
      2) Given a node number U print the sum of nodes in the subtree rooted at U (including node U).

      Since the answer can be too long, print the answer 10^9 + 7
      Initially each node contains zero.

      Input Format:

      First line contains a single integer N denoting the number of nodes in the tree.
      Next N-1 lines denotes the parent node of nodes 2 to N. (1 is the root node it has no parent)
      Next line contains M (Number of queries).
      In each of the next M lines first integer is T which means the type of the query.
      If T is ,1 it is followed by three integers U, X, K as explained in the question.
      If T is 2, it is followed by a single integer U.

      Output Format:-

      For each query of type 2, output a single line containing the required answer.

      Constraints:- 

      1 <= N <= 100000
      1 <= M <= 100000
      1 <= X , K <=1000000000

      Sample Input:

      7
      1
      1
      2
      2
      3
      3
      5
      1 1 1 2
      2 1
      2 3
      1 3 2 1
      2 3

      Sample Output:

      27
      13
      21

       

       


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19154. Terrorist Attack

      Problem code: INS14M


      In his final interview Digo is given a map of a city containing N junctions connected by roads of length 1. There is only one path between any two junctions. Each junction has a unique index between 1 and N(inclusive). There are M Civilians in the city. Everyday, each civilian visits a set of junctions.


      There are military camps built at certain junctions. The terrorists are planning to attack the city by targeting some junctions. However due to the presence of military camps, there is a limit to the size of explosion they can make at any particular junction. The intensity of the bomb planted at a junction is equal to the minimum distance from any military camp to the targeted junction. The damage of all civilians passing through a targeted junction increases by the intensity of the bomb dropped at the junction. The military camps set up and the terrorist targets are given in the form of the following queries:

      1 J : Meaning that a new military camp is set up at junction J
      2 J : Meaning that the junction J is targeted by terrorists
      3 J : Print the total damage done till now to all civilians visiting junction J

      Initially there is exactly one military camp at junction 1. The initial damage of all civilians is given to you.

      Input Format :

      First line contains 3 integers N,M,Q. N is the number of junctions, M is the number of civilians and Q is the number of queries to follow.

      Next N-1 lines contains 2 integers U and V (denoting that there is a road connecting U and V).
      Next M lines contains one integer each. The ith line contains integer a[i] representing the initial damage of the ith civilian.
      Next M lines contain the description of the junctions visited by the ith civilian (First integer of every line is X, the number of junctions visited by the ith civilian, followed by X integers representing the respective junctions)

      Next Q lines give the corresponding queries. Each query can be described by two integers T, J, where T is the type of query (which can be1 or 2 or 3) and J is the respective junction of the query.

      Output Format :

      For all the queries of type 3 print an integer answering the query.

      Constraints:

      1 <= N <= 50000
      1 <= M <= 10000
      1 <= Q <= 50000
      1 <= X, V, U, J <= N
      1 <= a[i] <=1000

      Sum of all the junctions crossed by all the civilians is less than 50001

      Note : The Final answer will fit in 64 bit signed integer.

      Sample Input:

      3 1 3
      1 2
      2 3
      5
      2 2 3
      3 3
      2 3
      3 3

      Sample Output:

      5
      7

       

       


      Added by:Surya kiran
      Date:2014-03-20
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Insomnia 2014









      SPOJ Problem Set (classical)

      19174. Khairy and Gold Alloys

      Problem code: WAL3A


       

      We all know "Connect 4 Game", One day Khairy has a Grid with infinite height and n numbers representing the number of discs in the ith column.
      It's guaranteed that no empty cells between any discs in the same column.
      for each disc in the grid if Khairy saw a disc on its left OR its right, he'll say "Wal3a".
      Given the N numbers, What's the maximum number that Khairy will say "Wal3a"!

      Khairy is a small guy who likes gold very much, but he has a problem in his eyes and the word "WAL3A" (WAL3A in arabic means "Firing"), whenever he likes something very much sooner or later it is destroyed by any means (Please don't impress him with something you want :|)

      One day Khairy visited the National Museum and saw a Grid with infinite height and N columns and each column i contains Xi Gold Alloys. No empty cells between Alloys in the same column.

      Khairy is a short guy, so he only sees the first row of the grid (High things may survive), also he is only impressed by at least two Gold Alloys adjacent to each other in a row, so if he found an Alloy alone in the row, he ignores it, else he would shout "WAL3AAAAAAAA".

      Unfortunately all Gold Alloys that impress Khairy in the 1st row are destroyed and disappeard :S, consequently the Alloys of the same columns above the destroyed Alloys fall to the the cell which is directly below it (each affected column height is decreased by 1 unit). Khairy continues saying "WAL3A" till he finds the first row not impressing anymore.

      The example below Khairy would say "WAL3A" twice and 7 gold alloys are destroyed.

      Black Blocks are Gold Alloys Destroyed By Khairy

       

      Of course the museum lost a fotune during Khairy's visit, so could you help the government find how many Gold Alloys are destroyed by Khairy.

      Input

      The first line of input contains an integer T (1 <= 20 <= T) followed by T test cases.

      Each test case contains a positive integer N [1 <= N <= 105] followed by N integers [0 <= Xi <= 109] separated by spaces (see sample input for more clarification).

      Output

      For each test case output one line contains how many Gold Alloys are destroyed by Khairy.

      Example

      Input:
      2
      5
      1 2 2 1 5
      3
      7 7 7 Output: 7
      21 

      Added by:Mohamed Ahmed
      Date:2014-03-22
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19216. Super Mario

      Problem code: SMARIO



      Statement

      Mario is one the most famous video games ever. In this problem, we will be helping Mario save the princess(again :P). In this game of mario, each world will be represented by a 2-D rectangular grid. There are multiple worlds and all the worlds are of size RxC. The world contains many objects each covering exactly one cell. 

      The cell with ‘S’ denotes Mario’s starting position. A cell with ‘.’ denotes an empty cell over which Mario can walk safely. From that cell he can move to any of its 4 adjacent cells (which share an edge with it). A cell with ‘D’ denotes a pipe that leads to the world below. A cell with ‘U’ denotes a pipe that leads to the world above. If Mario enters a cell containing a pipe, he must enter the pipe. A cell with ‘C’ represents a coin and Mario collects these. After collecting the coin, the cell becomes an empty cell. A cell with ‘#’ denotes bricks and Mario can’t enter this cell no matter what. A cell with ‘M’ denotes the monster(Bowser), Mario has to defeat Bowser to save the princess. Mario initially start from an empty cell. 

      Our Mario is very determined and so he will be always able to defeat Bowser on a 1 on 1 battle. But he is greedy and will always want to collect all the coins before going to save the princess. If he is not able to collect all the coins, he won’t save the princess!.  Help Mario to find the minimum number of steps to do this feat. 

      Note:
      If ‘U’ is present in topmost world or ‘D’ is present in the bottommost world, Mario can’t enter the cell. 

      Input format:

      Input contains multiple test cases. 

      First line of each test case will have 3 integers R, C and W.

      ‘R X C’ represents Grid dimension and ‘W’ represents number of worlds.
      It will be followed by R X W lines. Each line will have ‘C’ characters.

      First R lines describe the first world, second R lines describe the second world and so on upto W worlds.

      Input ends by the line, “0 0 0”.

      Output format:

      For each test case, print a single line “Mario saved the princess in K steps” where K is the minimum number of steps if he defeat the monster else Print “Mario failed to save princess”.

      constraints:

      1<=R,C<=15

      1<=W<=9

      0<=[Total number of coins]<=10

      All characters in the grid will be from the set {‘S’, ‘.’, ‘M’, ‘C’, ‘D’, ‘U’, ‘#’ } 


      INPUT:

      2 2 1

      SM

      .D

       

      2 2 2

      SM

      .D

      C.

      UC

       

      3 3 2

      S.M

      C#.

      D..

      ###

      C.C

      C.U

       

      2 2 1

      SM

      #C

      0 0 0

      SAMPLE OUTPUT:

      Mario saved the princess in 1 steps

      Mario saved the princess in 7steps

      Mario saved the princess in 8 steps

      Mario failed to save princess


      Added by:Noob
      Date:2014-03-24
      Time limit:0.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      19224. Lights, Snakes and Cages

      Problem code: CAGES


      In the zoo there are N cages in which we keep N snakes: each snake in its cage. For experimental reasons, in a month we will move each snake to a different cage: this reordering is given in the input.

      Each cage is illuminated by special light, which may be of type A, type B or type C. Your task is to assign the lights A, B, C to the cages so that:

      1) each snake will change its lighting, i.e. it will be moved to the cage illuminated differently from the cage it currently inhabits;

      2) lightings are equally distributed, i.e. the number of cages A, the number of cages B and the number of cages C differ by at most one.

      Input

      The first line contains an integer N (2 N ≤ 300 000), the number of snakes and cages. Cages are numbered from 1 to N.

      Each of the next N lines contains an integer. When K-th of these lines contains the number L, it means that the snake from the cage K will be moved to the cage L (K L). Two snakes will not move to the same cage.

      Output

      Print the string composed of the characters A, B and C, such that the K-th character denotes the lighting of the cage K.
      If there are multiple solutions, print any.

      Example

      Input:
      4
      4
      3
      2
      1

      Output: ACBC

      Added by:Adrian Satja Kurdija
      Date:2014-03-24
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Croatia nationals 2014 (6th grade, 3rd problem "Zmije")









      SPOJ Problem Set (classical)

      19234. Identity crisis(Medium)

      Problem code: LKID


      As lucky have solved IDC1948 with easy constraints .Now he would like to solve the problem with some serious constraints as you know lucky is not very good in solving hard problems he need your help, can you help him.

      For every given number n we define x(n) as distance from n to the first number greater than or equal to n in form of 99...99. For example x(100)=899, x(45)=54, etc. Given several n numbers you have to find the Zp, where x(n)≡n mod p.

      Input

      First line of input icontains one number T (T<1001) - the number of test cases. In each of the next T lines contains one number each to represent n (0<n<10^18).

      Output

      In each line you have to write one number - the least p>1 that x(n)≡n mod p. If there is no such p the line should contain -1.

      Example

      Input:
      2
      234
      5
      
      Output:
      3
      -1
      Explanation:
      x(234)=765. 765 mod 3=0, 234 mod 3=0 => 765≡234 mod 3

      NOTE::Time limit is allowed to pass with slow languages.
      My own C++ solution passed under 0.41s.
      Have fun;)

      Added by:[Lakshman]
      Date:2014-03-25
      Time limit:1s-6s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:IDC1948









      SPOJ Problem Set (classical)

      19270. SIR CHIRAG AND MAGIC NUMBERS

      Problem code: SIRNUMS


      Sir Chirag is famous for his 'Intelligencia". He found that Dukkar and Chapta were unable to solve a question.

      The magic Numbers are described as: The numbers are strictly positive, don't contain any leading zeroes. It has exaclty 'p' digits and if we move the last digit of the number to the beginning, it grows exactly 'x' times. 

      Chirag Sir took the task to solve it. It took him minutes to solve. Now its your turn.

      You have to find the Minimum possible number that satisfies the above conditions Given 'p' and 'x'.

      Input

      First line contains the number of test cases T: 0<T<=50

      Next T lines contains two intergers p and

      0<p<=1000000 and 0<x<10

      Output

      If such a number is not possible then print "Impossible" (Without the quotes). else print the number.

      Example

      Input:
      3
      6 5
      1 2
      6 4
      
      Output:
      142857
      Impossible
      102564
      (observe that for the first test case : 142857x5 = 714285)

      Added by:pika_pika
      Date:2014-03-27
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Codeforces









      SPOJ Problem Set (classical)

      19274. Operators

      Problem code: BLOPER


      Given a set of N integer A = {1, 2, 3, …, N} and a integer S, your task is find a way to insert an operator ‘+’ or ‘-‘ to every neighbor pair of A, that the result of the expression after insert equal to S.


      Input

      A single line, N and S (1 ≤ N ≤ 500, |S| ≤ 125250)

      Output

      If there are way(s) to insert, outputs any of them, otherwise outputs “Impossible” (without quotes).


      Example

      Input:
      	9 5
      Output:

      1-2+3-4+5-6+7-8+9

      Input:

      5 6

      Output:

      Impossible

       

      You may want to try another version here


      Added by:Kata
      Date:2014-03-28
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      19276. Peculiar Permutivores

      Problem code: BFPRMCYC


      On the gentle plains of Bytelandia, the mysterious ruffalo wander in herds solving combinatorics problems and searching for their next meals. Finding suitable food is becoming more and more difficult, as over the years the ruffalo have developed a curious diet consisting solely of permutations. To make matters worse, roughly half of all existing ruffalo lack the enzyme that would allow their stomachs to decompose permutations into cycles, and the other half are allergic to explicitly written fixed points.

      The two great ruffalo leaders, Wildthings and Nowyouseemee, have joined forces to build a device that can automatically transform permutations into a notation that everyone can digest and enjoy (but not necessarily in that order). The bright young programmer Zodiac was assigned the task of building the device, but in a tragic freak accident he swallowed a fixed point and died shortly thereafter. Zodiac's assistants found a single sheet of paper lying next to his body on the laboratory floor with just eight symbols written on it: "+-<>[],.". Out of respect for Zodiac's dying wish, the Ruffalo High Council passed a decree that the device must be built entirely in branf**k, no matter what the cost. Nowyouseemee has personally offered an unprecedented reward of 54 Gifts of Heaven to anyone who can successfully complete the task. While nobody has ever seen a Gift of Heaven, it is said that they come in magical bright green boxes that become a little faded after a day, and a little more faded after a week.

      Note: You can use any programming language you want, as long as it is brainf**k. If you would like to submit in other languages, please see the tutorial version.

      Input

      The first line contains an integer T (1 ≤ T ≤ 5000). Then follow 2T lines, representing T test cases. The first line of each test case contains an integer N (1 ≤ N ≤ 9), and the second line contains a permutation of [1..N] as a space-separated list of N integers. Every line ends with a single newline character (ASCII 10), including the last line.

      Output

      T lines containing the disjoint cycle decomposition of the corresponding permutation. For the identity permutation, print "e" without quotes. If there is more than one correct answer, print any of them.

      Example

      Input:

      5
      3
      1 2 3
      3
      2 1 3
      4
      2 1 4 3
      9
      3 8 9 4 1 7 6 2 5
      9
      3 8 9 4 1 7 6 2 5
      

      Output:

      e
      (1 2)
      (1 2)(3 4)
      (1 3 9 5)(2 8)(6 7)
      (2 8)(9 5 1 3)(7 6)
      

      Additional Info

      There are two randomly generated data sets, one with T=5000 and the other with T=500. The average value of N in each data set is approximately 6.36.

      The custom judge reports your source code length in parentheses after the judge result (when available at the time of judge termination). Only valid BF commands are counted. Also, if you don't get AC, you will be told on which data set you first failed (0-indexed). Thanks to (Tjandra Satria Gunawan)(曾毅昆) and Bin Jin, who wrote judges using the same or similar ideas. The master judge C++ source code is available here, and assumes that the test case judge reports source length as score.

      For assessing the correctness of program output, the custom judge works just the same as the standard "Ignores extra whitespaces" judge, except that it allows any valid cycle decomposition. In case you don't understand how the standard judge works, this means that e.g. "( 1 2)" and "(1 2) (3 4)" would be judged as wrong for the second and third example cases respectively, but printing ten spaces instead of the single space in "(1 2)" is perfectly fine.

      My solution at the time of publication has 334 bytes (golfed) and runs in 0.47s with 1.6M memory footprint.

      Update: Reduced source to 292 as of 2014-04-30.


      Added by:Mitch Schwartz
      Date:2014-03-29
      Time limit:5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:BF
      Resource:Own problem









      SPOJ Problem Set (classical)

      19288. Sword Game

      Problem code: WPC5C


      It is 2048, and a Martian robot called SSH3 wants to win galactical wars, as he does every year.

      He has been chosen to participate in the prestigious Sword Game, possibly the last one to ever happen. This is the format of the Sword Game.

      Every sword has a name S which is a string of n characters from a-z. The strength of the sword is decided in the following way.

      Define a function f (l1, l2) for every 1<= l1, l2 <= n. Find all the substrings of the sword name S with length l1. Then, ind1 is the index such that it is the lexicographically smallest among these l1 length substrings. (If there are multiple such substrings, then we consider the lower index).

      Similarly, ind2 is defined. Then, f (l1, l2) = |ind1 - ind2|. (All indices are 0-based)


      Strength (S) = (Expected Value (f)), over all l1, l2.


      As a Martian, SSH3 is also expected to be very good at Maths. He is asked to find out the strength of the sword. But as all other Martians, he has come from the city of Quoda, where everybody is pathetic at Maths. Hence, he asks you to help him. Ouput the value of n^2 * Strength (S).



      Input: 

      First line contains the integer n.

      Second line contains the name of the sword S.


      Output: 

      A single line containing an Integer, that is the value of n^2 * Strength (S).


      Constraints:

      1 <= n <= 100000

      S contains exactly n characters from ‘a’ to ‘z’.


      Time Limit: 8 seconds.


      Examples:


      Input:

      ab


      Output:

      0


      Explanation: f(l1,l2) can take one of the following 4 values:

      f(1,1) = 0 ( ind1 = 0, ind2 = 0 )

      f(1,2) = 0 ( ind1 = 0, ind2 = 0 )

      f(2,1) = 0 ( ind1 = 0, ind2 = 0 )

      f(2,2) = 0 ( ind1 = 0, ind2 = 0 )

      E(f(l1,l2)) = 0

      2^2 * E(f(l1,l2)) = 0


       

      Input: 
      First line contains the integer n.
      Second line contains the name of the sword S.
      Output: 
      A single line containing an INTEGER, that is the value of n^2 * Strength (S).
      Constraints:
      1 <= n <= 100000
      S contains exactly n characters from ‘a’ to ‘z’.
      Time Limit: 8 seconds.
      Examples:
      Input:
      ab
      Output:
      0
      Explanation: f(l1,l2) can take one of the following 4 values:
      f(1,1) = 0 ( ind1 = 0, ind2 = 0 )
      f(1,2) = 0 ( ind1 = 0, ind2 = 0 )
      f(2,1) = 0 ( ind1 = 0, ind2 = 0 )
      f(2,2) = 0 ( ind1 = 0, ind2 = 0 )
      E(f(l1,l2)) = 0
      2^2 * E(f(l1,l2))

       


      Added by:Triveni Mahatha
      Date:2014-03-29
      Time limit:8s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACA judge IITK, WPC5









      SPOJ Problem Set (classical)

      19290. Parade

      Problem code: WPC5F


      It is the Annual Parade of the Galactical Wars. Great men and women from around the cosmos have come to view this spectacular event. To make this a special occasion, the leaders in galaxy H2 have decided to arrange his participants in a particularly beautiful order.

      Firstly, they have chosen n particularly suited participants. These n participants have distinct heights ranging from 1 to n. They have arranged them in some way, so that the height of the ith student is H(i).

      The sworn enemies of H2, galaxy H3 have obtained some secret information on this arrangement. They know that there is a set of elements A(containing total k indices), such that H(j) < H(j-1) IF AND ONLY IF j belongs to A. As a Martian on H3, your organizer asks you to find the number of such possible configurations that H2 could have made.

       

      Input: 
      A single line containing space separated integers: n and k
      Next line containing k indices as explained in the problem.
      Output:
      A single line containing the number of ways to arrange participants modulo 1000000009 ( 10 ^ 9 + 9)
      Constraints:
      1 <= n <= 700
      0 <= m <= n-1
      2 <= i <= n (i is an index)
      All i’s are unique.
      Time Limit: 4 seconds.
      Examples:
      Input:
      3 1
      2
      Output:
      2
      There are 2 possible ways to arrange the participants, where their heights are:
      2 1 3 or 3 1 2
      Note 3 2 1 is not a valid ordering since h(3) < h(2).

      Input: 

      A single line containing space separated integers: n and k

      Next line containing k indices as explained in the problem.

       

      Output:

      A single line containing the number of ways to arrange participants modulo 1000000009 ( 10 ^ 9 + 9)

       

      Constraints:

      1 <= n <= 700

      0 <= k <= n-1

      2 <= i <= n (i is an index)

      All i’s are unique.

       

      Time Limit: 4 seconds.

       

      Examples:

       

      Input:

      3 1

      2

       

      Output:

      2

       

      Explanation: There are 2 possible ways to arrange the participants, where their heights are:

      2 1 3 or 3 1 2

       

      Note 3 2 1 is not a valid ordering since h(3) < h(2).

       


      Added by:Triveni Mahatha
      Date:2014-03-29
      Time limit:4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACA judge IITK, WPC5









      SPOJ Problem Set (classical)

      19291. Structures

      Problem code: WPC5A


      In the Galactical Wars happens the great event of designing a structure to honour the current generation of participants. (It is another matter that inevitably the monument is destroyed at the end of the Galactical Wars).

      The organizers this year do not believe that this is a good event, and have reduced the event to building a right structure : a right-angled triangle that represents the geometry of the universe. Further they have given a specific Odd Integer n, which they want one of the Shorter sides of the triangle to be.

      The organizers in the galaxy H2 are infuriated with this high-handedness. To demonstrate their prowess in this event, they have decided to build all possible right structures. Calculate how many different right structures they can possibly build.

       

      Input:
      First line contains a single integer T, denoting the number of Test Cases.
      T lines follow, each containing an odd integer ’n’ denoting the given size of a side.
      Output:
      T lines, each containing a single integer denoting the number of ways to form a right angled triangle with one of the smaller sides as ’n’.
      Constraints:
      1 <= T <= 10
      1 <= n <= 10^12
      n is odd.
      Time Limit: 1 seconds.
      Example:
      Input:
      1
      3
      Output:
      1
      Explanation: 
      There exists only 1 right angled triangle with sides 3,4,5.

      Input:

      First line contains a single integer T, denoting the number of Test Cases.

      T lines follow, each containing an odd integer ’n’ denoting the given size of a side.

       

      Output:

      T lines, each containing a single integer denoting the number of ways to form a right angled triangle with one of the smaller sides as ’n’.

       

      Constraints:

      1 <= T <= 10

      1 <= n <= 10^12

      n is odd.

       

      Time Limit: 1 seconds.

       

      Example:

       

      Input:

      1

      3

       

      Output:

      1

       

      Explanation

      There exists only 1 right angled triangle with sides 3,4,5.

       

       


      Added by:Triveni Mahatha
      Date:2014-03-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACA judge IITK, WPC5









      SPOJ Problem Set (classical)

      19292. Complicated Calculations

      Problem code: WPC5D


      There are k galaxies that participate in the Galactical Wars, which have happened for the past n years. Each year there has been a victor. Further, a particular galaxy G has won the Wars an even number of times. Also, G didn't participate in the first year.

      You are a member of the old and wise community of Daba. Even though it is the festive season of Galaxy going on, you prefer to sit in your room and do complicated (and senseless) calculations. For no reason, one day, you wonder in how many possible ways the victories in the previous years could have taken place (that is, the number of different sequences of victors possible). Output the result of this complicated (and senseless) calculation. 

       

      Input:
      First line contains a single integer T, denoting the number of Test Cases.
      T lines follow, containing space separated integers: n and k, as described in the problem.
      Output:
      T lines, each containing the number of ways in which victories during n years could have taken place, modulo 1000000007 (10^9 + 7).
      Constraints:
      1 <= T <= 150,000
      1 <= n,k <= 10^9
      Time Limit: 2 seconds.
      Example:
      Input:
      1
      1 4
      Output:
      3
      Explanation: 
      Any Galaxy except ‘G’ could have won. There are 3 such galaxies.

      Input:

      First line contains a single integer T, denoting the number of Test Cases.

      T lines follow, containing space separated integers: n and k, as described in the problem.

       

      Output:

      T lines, each containing the number of ways in which victories during n years could have taken place, modulo 1000000007 (10^9 + 7).

       

      Constraints:

      1 <= T <= 150,000

      1 <= n,k <= 10^9

       

      Time Limit: 2 seconds.

       

      Example:

       

      Input:

      1

      1 4

       

      Output:

      3

       

      Explanation: Any Galaxy except ‘G’ could have won. There are 3 such galaxies.

       

       


      Added by:Triveni Mahatha
      Date:2014-03-29
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACA judge IITK, WPC5









      SPOJ Problem Set (classical)

      19293. Galaxy distances

      Problem code: WPC5E


      Each galaxy 'i' in the universe is assigned a unique position in the universe given by A(i), for the ith galaxy. It is known that the distance between 2 galaxies is given as Dist (i,j) = ( |i^2 - j^2| + |A(i)^2 - A(j)^2| ).

      The events are held in a host galaxy, and every other galaxy has to travel to that galaxy to participate. For this, of course, the organizers have to pay the galaxy for their transportation, lodging and daily expenses. The organizers wonder, what could be the maximum transportation expenses that they have to pay?

      Help them by finding MAX(Dist (i,j)).

      Input:

      First line contains a single integer T, denoting the number of Test Cases.

      Each Test Case contains 2 lines. 1st line containing a single number ’n’ denoting the number of galaxies (numbered 1 to n).

      2nd line contains ’n’ space separated integers signifying A(i) for 1<=i<=n.

       

      Warning: Fast IO may be needed in some languages.

       

      Output:

      T lines, each containing an Integer, the answer to the corresponding test case.

       

      Constraints:

      1 <= T <= 10

      2 <= n <= 10^5

      1 <= A(i) <= 10^9

       

      Time Limit: 2 seconds

       

      Example:

       

      Input:

      1

      2

      4 3

       

      Output:

      10

       

      Explanation: Dist(i,j) is maximum for i=1, j=2.

       

      The events are held in a host galaxy, and every other galaxy has to travel to that galaxy to participate. For this, of course, the organizers have to pay the galaxy for their transportation, lodging and daily expenses. The organizers wonder, what could be the maximum transporatation expenses that they would have to pay?
      Help them find out by finding MAX (Dist (i,j))

       


      Added by:Triveni Mahatha
      Date:2014-03-29
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACA judge IITK, WPC5









      SPOJ Problem Set (classical)

      19295. The dilemma of Idli

      Problem code: WPC5G


      It is emergency time! There has been a clash between the organizers of the Galactical Wars and the Inter-Galactic Parliament due to some feud. The entire civilization has been split into two groups A and B. The civilians in A love some particular members in the Organization Committee of the Galactical Wars, and hate some members from the Inter-Galactic Parliament. On the other hand, civilians in B love some particular members from the Inter-Galactic Parliament, and hate some in the Organization Committee.

      You are Idli, the Inter-Galactic Dean, and it is your job to ensure satisfaction of the civilians. You decide to do so by impeaching some members from the Organization Committee and some from the Parliament. A civilian is satisfied if and only if all the members he loves are not impeached, and all the members he hates are impeached.

      Of course, Idli wants to satisfy most number of civilians. Help Idli in devising an algorithm to do so.

       

      Input:
      First line contains two space separated integers n1 and n2, denoting the number of Galactic Wars organizers (numbered 1 to n1) and the number of Members of Parliaments(MP) respectively (numbered 1 to n2).
      Second line contains a single integer ’n’, denoting the number of civilians.
      ’n’ lines follow containing the description of the civilians in the following format:
      First character contains a single character ‘A’, or ‘B’ denoting the group of the civilian.
      Then there is a space.
      Then some space separated integers follow ended by -1 denoting the members of same group whom he loves. Then some space separated integers follow ended by -1 denoting the members of other group which he hates. 
      Output:
      A single integer denoting the maximum number of civilians Idli can satisfy.
      Constraints:
      1 <= n1 <= 1000000
      1 <= n2 <= 1000000
      1 <= n <= 500
      0 <= number of organizers/MP a person loves <= 50
      0 <= number of organizers/MP a person hates <= 50
      Example:
      Input:
      4 5
      3
      A 1 -1 5 3 -1
      B 2 3 -1 2 5 -1
      B -1 -1
      Output:
      2
      Explanation: 3rd person doesn’t love or hate anyone, and thus is always satisfied. Only 1 out of the 1st 2 civilians can be satisfied. Hence Idli can satisfy at max 2 civilians.

      Input:

      First line contains two space separated integers n1 and n2, denoting the number of Galactic Wars organizers (numbered 1 to n1) and the number of Members of Parliaments(MP) respectively (numbered 1 to n2).

      Second line contains a single integer ’n’, denoting the number of civilians.

      ’n’ lines follow containing the description of the civilians in the following format:

      First character contains a single character ‘A’, or ‘B’ denoting the group of the civilian.

      Then there is a space.

      Then some space separated integers follow ended by -1 denoting the members of same group whom he loves.

      Then some space separated integers follow ended by -1 denoting the members of other group which he hates. 

       

      Output:

      A single integer denoting the maximum number of civilians Idli can satisfy.

       

      Constraints:

      1 <= n1 <= 1000000

      1 <= n2 <= 1000000

      1 <= n <= 500

      0 <= number of organizers/MPs a person loves <= 50

      0 <= number of organizers/MPs a person hates <= 50

       

      Time Limit: 1 second.

       

      Example:

      Input:

      5 5

      3

      A 1 -1 5 3 -1

      B 2 3 -1 2 5 -1

      B -1 -1

       

      Output:

      2

       

      Explanation: 3rd person doesn’t love or hate anyone, and thus is always satisfied. Only 1 out of the 1st 2 civilians can be satisfied. Hence Idli can satisfy at max 2 civilians.

       


      Added by:Triveni Mahatha
      Date:2014-03-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACA judge IITK, WPC5









      SPOJ Problem Set (classical)

      19297. Nymphs from H10

      Problem code: WPC5H


      A far away galaxy, H10 has newly been discovered and incorporated into the Commonwealth which participates in the Galactic Wars. The other galaxies have always bullied it by winning the Galactic Wars every year. Frustrated, H10 has come up with a novel strategy to distract the other galaxies. They are planning to send beautiful nymphs into the lands of the other galaxies.

      The cosmos is arranged so that there is a unique path between any two galaxies (possibly going through other galaxies). The leaders in H10 will select two different galaxies A and B, and send K nymphs to each of the galaxies that is on the unique path from A to B. Initially there are no nymphos on any galaxy.

      You are the Chief Executive Officer of this project. The leaders will ask you to send these groups of nymphs by giving various instructions of the form (A,B,K). In the process, they may also ask you how many nymphs are currently there in particular galaxies, so that they are able to take smart decisions in the future. Implement this. (See exact format in Input/Output Specifications)

      Input

      The first line contains t, the number of test cases.

      T test cases follow. Each contains :

      A line containing n, the number of galaxies (numbered from 0 to n-1). 

      n-1 lines describing the connections between 2 galaxies as 2 space separated integers a, b (both from 0 to n-1), denoting a direct connection between galaxy a, and galaxy b.

      The next line contains a single integer Q denoting the number of queries.

      Next Q lines contain queries in the form of 3 space separated integers a, b and k.

      Output

      For each query if k>=0, don't output anything, just send the nymphos to every galaxy on the way.

      In a query if k=-1, the output 2 space separated integers in a new line denoting the number of nymphs in galaxy a, and galaxy b respectively.

      Constraints:

      1 <= T <= 10

      2 <= n <= 50,000

      The galaxies are connected in such a way that there is a unique path from each galaxy to every other galaxy.

      2 <= Q <= 50,000

      0 <= a,b <= n-1

      a and b are differrent

      -1 <= k <= 100


      Time Limits: 8 seconds.


      Example

      Input:
      1
      3
      0 1
      1 2
      2
      1 2 2
      0 2 -1 
      
      Output:
      
      0 2

      Explanation: The path from 1 to 2 is 1 -> 2. 2 nymphos are thus sent to galaxies 1 and 2. There were 0 nymphos at galaxy 0 initially.

      Added by:Triveni Mahatha
      Date:2014-03-29
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:ACA judge IITK, WPC5









      SPOJ Problem Set (classical)

      19301. Operators (new ver)

      Problem code: BLOPER2


      Given a sequence a1, a2,..., an and a integer S, your task is find a way to insert an operator ‘+’ , ‘-‘, ‘.‘, ‘~‘  to every neighbor pair of A, that the result of the expression after insert equal to S.

      Note that :
      - a . b = a + 2 * b
      - a ~ b = a - 2 * b


       Input
      First line :  N and S (2 ≤ N ≤ 22, |S| ≤ 5 * 1016)
      Second line : N integers, a1, a2,..., an  (|ai| ≤ 1015)
       Output

      If there are way(s) to insert, output any of them, otherwise output “Impossible” (without quotes).


      Example :

       Input :
      9 5

      1 2 3 4 5 6 7 8 9

      Output :
      -~~~++++


      Input :
      3 -1

      -2 5 7
      Output :
      Impossible


      Details :
      In first test case : 1 - 2 - 2 * 3 - 2 * 4 - 2 * 5 + 6 + 7 + 8 + 9 = 5

      You may want to try another version here.


      Added by:Kata
      Date:2014-03-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19308. LCM

      Problem code: WPC5I


      Given n, and m, find the smallest k such that -

      n divides lcm (m,k) ; m divides lcm (n,k)

      Even if there are no Galactic Wars, you are still a Martian. Just do it.

      Input: 
      First line contains a single integer T, denoting the number of Test Cases.
      T lines containing space separated integers: m and n
       
      Output:
      Output T lines each containing the smallest k that satisfies the problem 
       
      Constraints:
      1 <= T <= 2000
      1 <= m,n <= 10^9
       
      Time Limit: 1 second
       
      Example:
      Input:
      1
      3 4
       
      Output:
      12

       

      Input: 

      First line contains a single integer T, denoting the number of Test Cases.

      T lines containing space separated integers: m and n

       

      Output:

      Output T lines each containing the smallest k that satisfies the problem 

       

      Constraints:

      1 <= T <= 2000

      1 <= m,n < 2^31

       

      Time Limit: 1 second

       

      Example:

      Input:

      1

      3 4

       

      Output:

      12

       


      Added by:Triveni Mahatha
      Date:2014-03-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:ACA judge IITK, WPC5









      SPOJ Problem Set (classical)

      19320. Draw Skyline Graph

      Problem code: SKYLINE2


      Once My Friend Deepan Gupta went a shop to buy a Laptop with features he needed. Seller showed him alot of laptops having various distinct features like cost, speed, memory, color, design, brand etc. But He was worrying only about memory and speed as he only needed these two. Because of so many laptops he got confused. He was not able to select a laptop. So he decided to select a skyline set in terms of {memory, speed} which will make it easier for him to decide. Objects are said to be in skyline set such that no one object in set dominates other object of set and all the objects which are not in the set are dominated by atleast one object in the set. No Object in the set is dominated by any other object (both set and not in set). One Object dominate other object if all the features of first objects are greater than or equal to second objects's corresponding features, but there exists alteast a feature that is strictly gerater than second object's corresponding feature. No one object dominate other object it means object does not satisfy the dominance condition, So Skyline Set can have two different objects with both same features.

      For example:
      Laptop1 : memory : 100GB, Processor Speed : 700GHz
      Laptop2 : memory : 200GB, Processor Speed : 500GHz
      Laptop3 : memory : 50GB, Processor Speed : 100GHz
      Laptop4: memory : 200GB, Processor Speed : 500GHz
      {Laptop1, Laptop2, Laptop4} are in skyline set while Laptop3 is not.


      If Still not understood 'SKYLINE', refer this link :: LINK

      Given N number of laptops with {M[i],S[i]}. Your task is to select a skyline set and print {M[i],S[i]} in newline of all the objects in set with decreasing order of M[i] value. If two Objects have same M[i] value, then you can print them in any order. For exact output format, refer to given examples.

      Constraints: 1<=T<=50, 1<=N<=10^5, 1<=M[i], S[i]<=10^9.

      Input:

      First line contains t, number of testcases. For each testcase, first line contains N, number of laptops. After that each of next N lines contains {M[i],S[i]} data for ith laptop, M[i] is memory  && S[i] is Speed of Processor of ith Laptop.

      Output:
      For Each testcase first line contains K, number of Skyline objebts in set, then each of next K lines contains {M[i],S[i]} data for ith laptop in decreasing order of M[i].

                                                                                                                        Example
      Input:
      2
      3
      100 700
      200 500
      50 100

      4
      200 500
      100 1000
      50 900
      1000 50

      Output:
      2
      200 500
      100 700
      3
      1000 50
      200 500
      100 1000


      HINT : Just Follow the statement Very CareFully || Observe the examples.


      ID RESULT TIME
      code...



      Added by:Rishav Goyal
      Date:2014-03-31
      Time limit:3s-4s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      19329. Group Viva

      Problem code: GRUPVIVA


      Today is external viva of computer science subject and Bosky is not at all prepared for it. Adding to his problems, he hasn't reached college yet. Luckily the external examiner was late too. Bosky somehow managed to reach the college before the external examiner arrived but he was still worried because he didn't want to get insulted by external examiner.

      The procedure for the conducting of viva is that each student has to sign the attendance register regardless of their given roll number before entering the viva room. Then they will be called individually or in groups of equal students exactly in the same order as they signed in the attendance register. It should be ensured by the internal invigilator that signing in the attendance register by the students has to be done before the external examiner arrives. The viva exam will start immediately only after the arrival of the external examiner. Students were informed that external examiner will arrive exactly after 30 mins. Bosky got some extra time to think how he can save himself from being insulted in front of the external examiner. He looked around and found that there were few students who were in worse condition than he himself was. With his past experience he concluded that on being called in groups the external picks up the most vulnerable student among the group and keeps on insulting and cursing the same student, ignoring the rest. Bosky knew that if he could manage to be in group with a student who is more vulnerable than him then he might get ignored by the external.

      When everybody started signing the attendance register, Bosky quickly looked around and spotted such a student and signed after him in the attendance register. He is quite certain now that if he has to give viva in a group in which both of them are present he might save himself from being insulted.

      There are "N" students in his class and Bosky knows that external examiner will call everyone in group of "X" students at once,where X can be any number between [1,N] (both ends inclusive). Now he wonders what is the probability that he and his "prey" would be in the same group.

      Given total number of students and Bosky's position in the attendance register, your task is to tell what is the probability that Bosky's plan will succeed i.e. he and his [so called] "prey" will be in same group.

      More formally you are given two integers N and R ,where 2<=N<=10^9 and 2<=R<=N . You have to find the probability that R and (R-1) will be in the same group if the sequence [1,2,3...N] is divided into group of "X" numbers sequentially i.e [1...N] is divided into groups [1...X],[(X+1)...2*X], [(2*X+1)...3*X] ... [ (X*floor((N-1)/X)+1)...N] , where 1<=X<=N and last group can have less than X numbers.

      Input:

      Input will contain a number T denoting the number of test cases.

      Then T test cases follow, each one consisting 2 integers N and R where N is the total strength of the class and R is Bosky's position in the attendance register.

      Output

      For each test case, output the probability as rational number of form p/q.The greatest common divisor of p and q should be 1.

      Constrains

      1<= T <=500

      1< N <=10^9

      1< R <=N

      Sample Input

      2
      5 5
      6 5

      Sample Output 

      2/5
      1/2

      Explanation:

      Case 1: N=5 and R=5

                   i.e. Total Students=5 and Bosky's has signed at 5th position

                         his pray signed before him hence he signed at 4th position

         Suppose students are called in group of "X",where 1<=X<=N

         For different values of "X" groups formed are as follow

         For, X=1 

                     [ {1},{2},{3},{4},{5} ]

               X=2

                     [ {1,2} , {3,4} , {5} ]

               X=3

                     [ {1,2,3} , {4,5} ]

               X=4

                     [ {1,2,3,4} , {5} ]

               X=5

                     [ {1,2,3,4,5} ]

         We can clearly see that for X=3 and X=5 Bosky's plan will succeed i.e. he and his pray will be in same group. Hence the output is "2/5"


      Case 2: Similar to Case 1 where N=6 and R=5

               For, X=1 

                     [ {1},{2},{3},{4},{5},{6} ]

               X=2

                     [ {1,2} , {3,4} , {5,6} ]

               X=3

                     [ {1,2,3} , {4,5,6} ]

               X=4

                     [ {1,2,3,4} , {5,6} ]

               X=5

                     [ {1,2,3,4,5}, {6} ]

               X=6

                     [ {1,2,3,4,5,6} ]


         Here Bosky's plan succeeds for X=3,X=5 and X=6. 

       

         Hence the output is "3/6" ==> "1/2" [Note: Output must be irreducible rational number] 


      Added by:Manish Singh Bisht
      Date:2014-04-01
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19334. Khaolin Temple

      Problem code: KHAOTMPL



      NOTE: You can skip to BRIEF if you do not want to read complete storyline.

      Khaolin Temple is world's most famous algorithmic pilgrimage situated on Mount Kong in China. It is believed that human civilization has never seen better coders than Khaolin Coders and its well known about them that that they were so good at problem solving that they could even solve "NP-Complete" problems in constant amortized time. There are many folktales about Khaolin Coders, the most famous ones being about Monk Bosky who was incomparably the best Khaolin Coder. Following is a famous incident from Monk Bosky's early days at Khaolin Temple.


      "During his early days at Khaolin Temple Bosky was the brightest and most notorious pupil at Khaolin. Once his master asked all his pupils to water the khaolin flowers[khaolin flowers are special flower which grow 1 meter tall on pouring 1 litre water to them]. Master wanted to keep everyone busy [specially Bosky] so that he could meditate in silence. He told his pupils where the flowers were and how tall they were at present and asked them to come back only when they are finished watering all the flowers assigned to them. He also told them that only those pupils will be allowed to enter the temple who will tell the correct heights of flowers after the watering process is complete.

      Master knew that his pupils will cheat and calculate the height that will be achieved by flowers after pouring water to them if he asks them to water them one by one, hence he decided to make it difficult for them to calculate the height by asking them to follow certain rules while watering flowers.

      He asked them to follow the following rules while watering flowers:

      Rule 1:Every pupil will water all flowers assigned to him as an array of n khaolin flowers with heights [H1,H2...Hn].

      Rule 2:When a pupil will be standing next to Kth flower he will have to go back to (K-1)th flower and inspect its height,if it is greater or equal to height of Kth flower he will have to note its index down,then he will have to go further back to (K-2)th flower and if its height is greater or equal to Kth flower he will again have to note down its index. And he must continue to do so till he reaches flower 1. After reaching flower 1 he has a list of indices of flowers with height>= Hk [i.e. height of Kth flower].Now he will have to bring sufficient water from river nearby and pour 1 litre water to each flower whose index he has noted down [NOTE: By pouring 1 litre water to the flowers he will be making them 1 meter taller].

      Rule 3: Pupil can move to Kth flower only if he has applied Rule 2 standing next to (K-1)th flower. If (K+1)th flower exists he must continue to apply Rule 2 to (K+1)th flower after he has applied Rule 2 standing next to Kth flower.

      Rule 4:Pupil must start watering process standing next to 1st flower

      Master knew that if his pupils sincerely followed these rules while watering flowers they won't be able to water all flowers before a month's time span and in the meantime he could meditate in silence without being disturbed by anyone. Since this task was very boring, Master decided to reward the pupil who enters back into temple first,obviously by telling heights of all flowers correctly after the process of watering the plants was complete. As a reward Master will teach him secret algorithmic skills till the next pupil enters the temple and as soon as the next pupil enters the temple Master will stop teaching the first pupil. With that said,Master sent all his pupils to water khaolin flowers and expected that no pupil will return before a month and also expected that he will have to teach secret algorithms as a reward only for few hours because if they follow same process they will complete the task in nearly equal time.

      But to Master's utter surprise he heard a pupil on the gate of Khaolin Temple claiming that he has watered all the flowers in an hour and that pupil was Bosky who further astonished Master by reporting the correct heights of the flowers as expected by Master. Master refused to reward him as Bosky clearly cheated and did not follow his rules. But after Bosky explained Master the process he followed to water flowers which produced same height of flowers as Master expected,Master was so impressed that he taught him everything he knew for the next month and also declared him to be hier to his position in the Khaolin."


      No one in today's world knows the algorithm Great Monk Bosky used to solve the problem given by his master but today we have atleast been able to reconstruct such cases and time limits which can only be passed by using algorithm which is equivalent toMonk Bosky's algorithm or more efficient than it.

      You are thereby challenged to match Monk Bosky's efficiency and mightiness by telling the heights of flowers after watering them as stated in the question.

      BRIEF:

      • An array A of N integers is given [a1,a2...an]
      • Step 1:Starting from A[1],for every A[i] 1<=i<=n create an array B of size m which contains integers [b1,b2...bm] where B[j]<i for all 1<=j<=m and each A[B[j]] >= A[i]
      • Step 2:Increment B[j]th element in A with 1 i.e. do A[B[j]]=A[B[j]]+1, where 1<=j<=m
      • Step 3:If i<N, do i=i+1 and goto Step 1 else print array A

      Your task is to print the transformed array A after above steps are implemented to it.

      Input

      First line will contain and integer N,where N represents the number of flowers. Next line will contain N space separated integersH1 H2 H3 ... HN representing heights of flowers in sequential order.

      Output

      Print N space separated integers that represent heights of flowers after all flowers have been watered

      Constrains

      1<=N<=10^5

      1<=Hi<=10^9

      Sample Input

      5
      7 5 2 1 8

      Sample Output

      11 7 3 1 8

       


      Added by:Manish Singh Bisht
      Date:2014-04-01
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19335. Machau vs Maggu

      Problem code: MACVSMAG


      You will find three types of people in an engineering college Maggu,Machau and Others. We all know how much hard Maggu people try to portray themselves as Machau but they never succeed. Today Machau people have decided to recruit few Maggus and convert them to Machau. All the Maggus who wanted to become Machau had to reach Machau Club situated at YAY MACHAU" from their current location A. Machau people had laid many books everywhere on the campus to distract Maggus and make it difficult for them to reach Machau club. The campus can be imagined as a large NxN grid in which Maggu is located at position Awhich is denoted by (Ax,Ay) coordinate and the Machau Club is located at position B which is denoted by (Bx,By) coordinate. Machau people had laid books at M random locations denoted by (Xi,Yi) where 1<=i<=M.Additionally to prevent Maggus who take up the challenge to runaway Machau people laid books everywhere outside the rectangular area where Maggu's location A and Machau Club's location B are are ends of the diagonal of that rectangular area. A Maggu can only walk in left,right,up or downdirections from his current place as long as he doesn't leave the campus i.e. he stays inside the NxN grid. If a Maggu wants to become Machau he must reach Machau Club without touching a single book in his path and without leaving the campus grid.

      More formally stating the problem: Given an N x N grid with M non reachable cells.Test whether cell "B" can be reached from cell"A" provided only left,right,up and down movements are valid.

      You must print "YAY MACHAU" if it is possible for a Maggu to reach Machau Club else print "MAGGU FOREVER"

      Input

      First line will contain 6 integers N,M,Ax,Ay,Bx and By Where, N=No.of rows and columns in campus grid

      M=Total number of books laid on the campus

      Ax,Ay=Coordinates of Maggu

      Bx,By=Coordinates of Machau Club

      Next M lines will contain Xi and Yi denoting coordinates on NxN grid which contain books to distract MAGGUS

      NOTE: If any book is placed in position A or B MAGGU will always be distracted. All (Xi,Yi) pairs are not guaranteed to be distinct.

      Output

      Print "YAY MACHAU" if Maggu can reach Machau club otherwise print "MAGGU FOREVER" [without quotes]

      Constrains

      1<=N<=10^9

      1<=M<=10^5

      1<=Ax,Ay,Bx,By,Xi,Yi<=N

      Sample Input
      1000 2 10 1000 1000 10
      1 1
      100 100

      Sample Output
      YAY MACHAU


      Added by:Manish Singh Bisht
      Date:2014-04-01
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19367. St Bernard and Gravity

      Problem code: BGRAVITY


      St. Bernard's new game is played on an R×C board. Initially every square is either empty or blocked by a wall. Bernard throws a rock into the board by putting it in the topmost row of a column and then letting gravity do the rest.

      Gravity works as follows:
      => If the square under the rock is a wall or if the rock is in the bottom row of a column, then the rock remains there.
      => If the square under the rock is empty, then the rock moves to that square.
      => If the square under the rock contains another rock, then the falling rock may slide sideways :
                   o If the squares left and left-down of the rock are empty, then the rock slides one square left.
                   o If the rock doesn't slide left and the squares to the right and right-down are empty, then the rock slides one square right.
                   o Otherwise, the rock remains there and never moves again.
      Bernard will never throw another rock while the previous rock hasn't settled down.
      Write a program that draws the board after Bernard throws all his rocks into the board, if we know the columns that Bernard threw his rocks into, in order.
      Note: Bernard will never throw a rock into column in which the top row isn't empty.

      INPUT

      The first line contains integers R and C (1<=R<=30000,1<=C<=30), the size of the board.
      Each of the following R lines contains C characters, the initial layout of the board. A '.' represents an empty field, while the uppercase letter 'X' is a square blocked by a wall.
      The next line contains an integer N (1<=N<=100000), the number of rocks Bernard throws.
      Each of the following N lines contains an integer between 1 and C, the column into which Bernard throws a rock (the leftmost column is column 1).

       

      OUTPUT

      Output R lines, each containing C characters, the final layout of the board. Rocks should be presented with an uppercase letter 'O'.

      SAMPLE

      Input
      5 4
      ....
      ....
      X...
      ....
      ....
      4
      1
      1
      1
      1
      Output
      ....
      O...
      X...
      ....
      OOO.

      Input
      7 6
      ......
      ......
      ...XX.
      ......
      ......
      .XX...
      ......
      6
      1
      4
      4
      6
      4
      4
      Output
      ......
      ...O..
      ...XX.
      ......
      .OO...
      .XX...
      O..O.O

      In the first example, all rocks are thrown in the first column. The first rock stops on the wall. The second rock falls on the first, slides right and stops at the bottom of the second column. The third rock falls on the first then on the second rock, slides left and rests at the bottom of the first column. The fourth rock falls on the first then on the second, then slides right.


      Added by:[bLanK]
      Date:2014-04-03
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19382. Stock

      Problem code: STK


      Alex heard a lot about investing in the stock market and now wants to do it to earn some profit. Being a new investor he is scared of the risks in the stock market, so he decides that at any instance he will not have more than one stock with him. It is also decided that on a particular day he can either buy or sell atmost one stock(only one transaction allowed). Now given the prices of one particular stock over the period of n days Alex decides he will make atmost k buys and k sells.

      Alex heard a lot about investing in the stock market and now wants to do it to earn some profit. Being a new
      investor he is scared of the risks in the stock market, so he decides that at any instance he will not have more
      than one stock with him. It is also decided that on a particular day he can either buy or sell atmost one stock(only one transaction allowed).
      Now given the prices of one particular stock over the period of n days Alex decides he will make atmost k buys and
      k sells.
      Write a code to help Alex to maximize his profit.

      Write a code to help Alex to maximize his profit.

      Input

      First line contains an integer T(<=100), number of test cases.

      Each test case will have n(<=3000) and k(1<=k<=n/2), is the no. of days and the maximum buys/sells allowed respectively.

      (Value of the prices are in range of unsigned 32-bit integer.)

      Next line will have n space separated integers denoting the price of stock over n days.

      Output

      For each test case output one line stating the maximum profit.

      Example

      Sample Input:
      
      3
      10 3
      2 7 3 9 8 7 9 7 1 9
      10 1
      2 7 3 9 8 7 9 7 1 3
      10 2
      2 7 3 9 8 7 9 7 1 9
      	
      Sample Output:
      	
      19 
      7
      15
      
      Explanation:
      1st test case Alex would buy on 1st day and sell it on the 2nd day, and then buy another on the 3rd day and sell it on the
      4th, finally buys on 9th day and sells on the 10th day.So profit = (7-2)+(9-3)+(9-1) = 19.
      
      2nd test case Alex would buy on 1st day and sell it on the 4th(or 7th) day. So profit = 9-2 = 7.
      
      2nd test case Alex would buy on 1st day and sell it on the 4th day, and then buy another on the 9th day and sell it on the
      10th day.So profit = (9-2)+(9-1) = 15.

      Added by:Abhra
      Date:2014-04-05
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19406. Fibonacci extraction Sum

      Problem code: FIBOSUM2


      Some people may found FIBOSUM a too easy problem. We propose here a useful variation.

      SigmaFibScale

      Fib is the Fibonacci sequence:
      For any positive integer i: if i<2 Fib(i) = i, else Fib(i) = Fib(i-1) + Fib(i-2)

      Input

      The first line of input contains an integer T, the number of test cases.
      On each of the next T lines, your are given tree integers c, k, N.

      Output

      Print Sum(Fib(ki+c) for i in [1..N]).
      As the answer could not fit in a 64-bit container, just output your answer modulo 1000000007.

      Example

      Input:
      1
      3 5 2
      
      Output:
      254
      

      Explanations

      Index-1 Fib sequence : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...
      We want the 5*1+3 = 8th and 5*2+3 = 13th ones, thus the answer is 21 + 233 = 254.

      Constraints

      0 <= c < k < 2^15
      0 < N <= 10^18
      

      The numbers c,k,N are uniform randomly chosen in their range.
      For your information, constraints allow 1.3kB of Python3 code to get AC, it could be hard.
      A fast C-code can get AC under 0.0?s.
      Warning: Here is Pyramid cluster, you can try the tutorial edition (clone with Cube cluster).
      Have fun ;-)


      Added by:Francky
      Date:2014-04-05
      Time limit:10s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      19416. Potions Class

      Problem code: POTIONS


      Its time for the Potions class. Harry absolutely HATES potions because he has to face mockery by the potions teacher Snape everytime he has a potions class. Snape never leaves any chance of insulting him in front of everyone.

      Snape is not in a good mood today, which is not good for Harry. Snape challenges Harry to answer his question. If Harry fails to answer, he will have to spend the whole week in detention!.

      He gives Harry n numbers ( a1, a2, a3,...., an ) and q queries. Each query will consist of four integers,w, x, y, z . The result of a query is given by the following equation:

      Equation

      Help Harry or else he'll miss his Quidditch match against Slytherin because of his detention..!!

      Input

      The first line of the input contains T, the number of test cases. T test cases follow.

      The first line of each test case contains n and q.

      The second line of each test case contains n integers (a1, a2, a3,..,an)

      Each of the next q lines contain w, x, y, z.

      Output

      For each test case output the result as given by the equation.

      The answer may be very large, so output it modulo 10^9+7

      Constraints:

      1<= T <=10

      1<= n, q <=10^5

      1<= x+i <=n ( for all y<=i<=z )

      0<= ai <=10^9 ( for all 1<=i<=n)

      1<= w <=10^6

      0<y<=z

      Example

      Input:
      1
      5 2
      2 1 4 7 2
      1 1 0 2
      1 5 0 0
      Output:
      16
      2

      Added by:Abhinav92003
      Date:2014-04-06
      Time limit:1s-5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19490. Pair and unpair weightest string

      Problem code: PAUWS


      Once I went market to buy a teddy. The shopkepper offered a puzzle and said he'll give me whatever i wish at a huge discount if i give him the working piece of code for following problem.
            You will be given a string S of length N, containing either 'A' or 'B'. Make all the possible lists from the given list, with the given operation that you are allowed to change one symbol into another. Then assign maximum weight to each of the string and get the string with maximum weight && return the weight.

      You have only following two ways to assign weight to symbol :
      1. Pair a S[i] symbol with adjacent one (S[i] or S[i-1]). Each symbol can only be paired with exactly one symbol. Weight of a pair is 4. Pair will be either 'AB' or 'BA'.
      2. Keep a S[i] Symbol indepedent. Weight of unpaired symbol is 1.
      3. Each symbol is either involved in exactly one either pair or unpaired status.
      4. For each string, Keep in mind the number of symbols(K) with index i, 1<=i<=N, which are changed from original symbol S[i].
      5. For each of the possible lists, Add all the weight assigned as a pair and unpair, then subtract K from it. assign this final value as string weight. Add each paired weight once exactly.

      The Task is to maximize the weight of the string. Suppose S="ABB", possible transforms can be {"ABB", "ABA", "AAB", "AAA", "BBB", "BBA", "BAB", "BAA"} with respective weight {5,4,4,1,2,3,3,2}. Maximum weight is found 5 in string 1.

      Constraints: 1<=N<=10^5, 1<=T<=500.

      Input :
      First line contains t, number of testcases. For each testcase, first line contains N, length of the string. Second line contains string itself.
      Output:
      For Each testcase, Output maximum weight of a string that can be obtained.


                                                                   Example
      Input:
      5
      3
      ABB
      7
      ABBBAAA
      8
      BAAAAAAA
      12
      AAAAAAAAAAAA
      11
      ABABBBABABA


      Output:
      5
      12
      13
      18
      21


      ID RESULT TIME
      code...



      Added by:Rishav Goyal
      Date:2014-04-09
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      19543. Can you answer these queries VIII

      Problem code: GSS8


      You are given sequence A[0], A[1]...A[N - 1]. (0 <= A[i] < 2^32)

      You are to perform Q operations:

      1. I pos val, insert number val in sequence before element with index pos. (0 <= val < 2^32, if pos = current_length then you should add number to the end of the sequence)

      2. D pos, delete element with index pos from sequence.

      3. R pos val, replace element with idex pos by val. (0 <= val < 2^32)

      4. Q l r k, answer Σ A[i] * (i - l + 1)^k modulo 2^32, for l <= i <= r. (0 <= k <= 10)

      Input

      The first line of the input contains an integer N (1 <= N <= 100000).

      The following line contains N integers, representing the starting sequence A[0]..A[N-1].

      The third line contains an integer Q (0 <= Q <= 100000).

      Next lines contains queries in given format.

      Output

      For each "Q" operation, print an integer(one per line) as described above.

      Example

      Input:
      
      4
      4 1 2 3 5 7 Q 0 2 0 I 3 4 Q 2 4 1 D 0 Q 0 3 1 R 1 2 Q 0 1 0
      Output:
      6
      26
      40
      4

      Added by:Evgeny Savinov
      Date:2014-04-14
      Time limit:1.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:own problem









      SPOJ Problem Set (classical)

      19545. Black and White beads

      Problem code: BWB


      Well its now time for some serious task . There are lots of beads available and in two colours , namely white and black . So there are many beads of both the colours . One has to make a string of beads by joining beads with end to end . But there are some constraint , and you have to follow that constraint. While making beads , you have to make sure that there should not be K beads of black colour consecutively and also there should not be any bead string which has black bead in front ,i.e it must have white bead  in front . So the task is quite simple , find all possible ways of making a string of bead of length N which satisfies the above constraint .


      Input:

      The first line of the input contains an integer T denoting the number of test cases. The descriptionof T test cases follows.

      Output:

      Next T lines contains 2 integers N and K.

      Print a line for each test case containing the required answer modulo 1000000007.


      Constraints :

      1<=T<=1000000

      1<=N<=10000

      1<=K<=100

      Sample Input :

      3

      2 3

      2 1

      3 4

      2

      1

      4

      Explanation :

      For Sample test case 1 , N=2 and K=3 , so as 3 beads of black colour should not present we have white-white , white-black.

      Note black-white is not the valid one so in this case the answer is 2.


      Added by:Aayush Agarwal
      Date:2014-04-14
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: BF
      Resource:Own problem used for codecracker









      SPOJ Problem Set (classical)

      19551. A Colorful world

      Problem code: CWORLD


      This is the hardest level of the game. There are n stages in the level. In each stage you will given qi balls. The color of the balls are denoted by an integer between 1 to k. You can pick up not more than one ball in each stage. (You can skip if you want) If you pick up a ball you will gain or lose some points depending on the last ball you have picked. You know color of the available balls of each stage and points you'll get for a certain combination, now can you figure out the maximum point you can get?


      Note that you wont gain or lose any point for the first ball you picked. One stage can contain multiple balls of same color.



      Input Specification:
      First line of input will contain number of test cases T.

      In each case first line will contain two integer n and k. Than there will be n lines which describes each stage. Each line contains an integer qi which denotes number of balls available in ith level and then qi integers will denote the colors.

      Then there will be a k lines, each containing k integer, jth integer of ith line will indicate the point you will gain or lose if you pick a ball of color j after color i. Negative means you will lose point.


      Output Specification:

      Print case number and a single integer denoting the maximum point you can get.


      Constraints:

      T<=120

      2<=n<=100

      0>=qi<=100

      1>=k<=100

      point gain or lose in a step will be at most 1000.


      Sample Input

      2

      2 3

      3 2 3 2

      4 1 1 3 3

      1 5 0

      1 0 2

      -4 1 -5

      4 4

      1 4

      2 3 1

      2 2 4

      3 4 2 2

      -5 -2 3 2

      -5 -1 2 0

      3 4 5 -4

      -3 -5 0 -4


      Sample output:

      Game 1: 2

      Game 2: 4

       

      In first case you can pick color 2 in first stage and color 3 in second stage in gain 2 points.



      Added by:Shafaet
      Date:2014-04-15
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem, Bangladesh Informatics Olympiad 2012









      SPOJ Problem Set (classical)

      19561. New Binary

      Problem code: NBIN


       

      One day Chandrima decided to make a list of all numbers in binary format, the list would be like 0,1,10,11,100,... and so on. 
      Now she get bored of this list and decide to remove any pattern having atleast two consecutive ones and prepare a new list.
      The new list will be like 0,1,10,100,101,... and so on. She then thought if a number n is given to her can she find the nth
      member of the new list. After trying for some time she comes to you for help. Can you help her by writing a program for her that
      coud do the specified task

      One day Chandrima decided to make a list of all numbers starting from 1 in binary format, the list would be like 1,10,11,100,... and so on. Now she get bored of this list and decide to remove any pattern having atleast two consecutive ones and prepare a new list. The new list will be like 1,10,100,101,... and so on. She then thought if a number n is given to her can she find the nth member of the new list. After trying for some time she comes to you for help. Can you help her by writing a program for her that coud do the specified task

       

      Input

      The first line contains T(<=1000) test cases. The next T lines each contain one integer N(<=10^15) for which you need to find the Nth member of the list.

      Output

      Output T lines each containing the required answer.

      Example

      Input:
      3
      1
      2
      3
      
      Output:
      1
      
      10
      100

      Added by:Abhra
      Date:2014-04-16
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19568. Prime queries

      Problem code: PRMQUER


      You are given a simple task. Given a sequence A[i] with N numbers s.t. 1<=i<=N . You have to perform Q operations on a given set of numbers.

      Operations :

      1. A V l, Add the value V to element with index l .
      2. R a l r, Replace all the elements of sequence with index i s.t. l<=i<=r with a .
      3. Q l r, print the Number of elements with index i s.t. l<=i<=r and A[i] is prime number and A[i]<=10^7 .

      No Number In sequence ever will exceed 10^9.

      Constraints : 1<=N<=10^5, 1<=Q<=10^5, V<=10^3, A[i] <= 10^8 , a<=10^7,  1 <=  l <= r <=N.

      Input :
      First line contains N as Number of sequence elements && Q as number of operations to be performed. Second line contains Initial N elements of the sequence. After that each of the next Q lines contains one operation to be performed on the sequence.

      Output :
      print each value in newline as stated above.


                                                                                                                                                                Example                            
      Input :                                
      5 10
      1 2 3 4 5
      A 3 1      
      Q 1 3
      R 5 2 4
      A 1 1
      Q 1 1
      Q 1 2
      Q 1 4
      A 3 5
      Q 5 5
      Q 1 5

      Output :
      2
      1
      2
      4
      0
      4


      ID RESULT TIME
      code...



      Added by:Rishav Goyal
      Date:2014-04-16
      Time limit:8s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own









      SPOJ Problem Set (classical)

      19576. Popeye and the magical land

      Problem code: PAML


      As usual Popeye and brutus are fighting for olive, and suddenly a witch appears and took popeye to magical land as brutus called that witch. In magical land, the witch with her magic make N(1<=N<=100) number of clones of popeye of different strength(0<=Si<=100) i.e each popeye can hold another popeyes above his head, and number of popeyes which can be hold will be less than or equal to strength of popeye which is holding other popeyes.

      Eg: Imagine there are three popeyes: the first has strength 2, the second has strength 1 and the third has strength 1. We cannot put the second and the third popeye simultaneously on the top of the first one. But the second popeye can place directly on the top of the first one, and then the third popeye directly on the top of the second one.We will call such construction of popeye a "Popeye-stack".

      The witch want him to make Minimum number of popeye-stack and give her Maximum Height of popeye-stack from that arrangement, then only she release him from the magic and give him spinach to defeat brutus. Help popeye to get released from the magic of the witch.

      Input

      First line of Input contains no. of test cases T(T<=1000). Each test case contain two lines: 1st line contains N (1<=N<=100) and 2nd line contain N spaced Si (strength of N popoyes) (0<=Si<=100)

      Output

      For each test case output a string "Case #i: " ("i" is test case number) followed by Minimum number of popeye-stack and Maximum Height of popeye-stack seperated by a space.

      Example

      Input:
      2
      5
      0 1 2 3 4
      9
      0 1 0 2 0 1 1 2 10 Output: Case #1: 1 5
      Case #2: 3 4

      Added by:Quantum
      Date:2014-04-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      19578. Chipmunks with Brain

      Problem code: CWB


      There is a Chipmunk with "Brain" and he want to dig holes in a yard to store his food.
      There is a rectangular yard which is divided into unit cells, initially having some holes(H) and sand(S). The chipmunk can dig one row at a time, But he have to dig all the sand(S) positions simultanously and due to this holes(H) which are already there got filled with sand.

      Example:
      Suppose a Row is "SHSHH" then after digging the row becomes "HSHSS" i.e all "S" replace with "H" and vice versa.

      Now Chipmunk wants to have a large square of holes somewhere in the yard. The sides of square must be parallel to the sides of the yard. Find a sequence of turns that produces the largest possible square of holes somewhere in the yard and help him to find the area of that square.

      Input

      Given two interger Rows(R) and column(C) (1<=R,C<=30)
      Next line contain a RxC rectangular yard of sand (S) and hole (H).

      Output

      Print largest "Area of the Square" that can be obtain after sequence of turns.

      Example

      Input:
      2 2
      SS
      HH
      Output: 4

      Input:
      5 1
      H
      S
      H
      H
      H
      Output: 1

      Added by:Quantum
      Date:2014-04-17
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All









      SPOJ Problem Set (classical)

      19684. Symmetric matrix

      Problem code: MATPROD


      [NOTE: A harder version of this problem is Symmetric Matrix 2; you may want to try it once you solve this one.]

      You are given an N matrix mij such that mij == mji for i, j = 1, ..., N. We would like to compute the value of

      Note that in the above expression we are going over K indices i1, ..., iK that run over the values 1, ..., N, while summing over the product of all the K*(K-1)/2 possible matrix elements that we can form with these indices.

      Input

      The first line of the input contains two integers N and K (2 ≤ N ≤ 100 and 2 ≤ K ≤ 5), representing the number of rows and columns of the matrix mij and the number of sums in the formula above, respectively. The following N lines contain N integers each, being the j-th number in the i-th line the value of mij (-10  ≤ mij ≤ 10 and mij == mji for i, j = 1, ..., N).

      Output

      Print a single line with the result of the calculation. Because this number can be very big, output its remainder modulo division by 1000000007 (== 109+7).

      Example

      Input:
      
      4 5
      4 5 -4 -3 -4 2 -3 -6 1 -8 -4 1 -10 -6 2 -8 -6 0 Output: 308822466

      Added by:Fidel Schaposnik
      Date:2014-04-29
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19686. Mining Camps

      Problem code: MCAMP


      Mansur plays the new computer strategic game. The main task in such games is mining resources.
      Fortunately in this game only one resource is necessary for development — the gold, and also there is one supplementary resource type — energy.
      In this game there are mining camps, which provide certain amount of gold and energy. Аll camps are located along the straight line.
      To protect the mining camps one can build a forcefield (a closed line contiguos segment containing mining camps) , which needs energy amount equal to it’s length.
      ( if forcefield start camp is located at X1 and its end camp is at X2 energy needed for the whole forcefield is |X1-X2| )
      Mansur wants to build one forcefield in such way, that energy of protected mining camps is enough for the forcefield, and amount of gold provided by these mining camps is maximal possible.
      Write a program to help Mansur find the maximal amount of gold which he can obtain from protected mining camps.

      Input

      First line of the input file contains one integer N — number of mining camps.
      N<=10^5
      Following N lines contain:
      three space separated integers xi, gi, di, 0 <= xi <= 10^9, 1 <= gi <= 10^9, 1 <= di <= 10^9: mine coordinates,amount of gold and energy provided by the mine. All xi are different and given in increasing order.

      Output

      Output only one number — maximal amount of gold which Mansur can mine.
      Input:
      4 
      0 5 1
      1 7 2
      4 4 1
      7 15 1
      Output: 16

      The Forcefield is camps [1,3] energy is 1+2+1=4 >= 4-0 so answer is 5+4+7=16

      Added by:Hussain Kara Fallah
      Date:2014-04-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:APIO 2014 Training Session









      SPOJ Problem Set (classical)

      19687. Symmetric matrix 2

      Problem code: MATPROD2


      [Note: Symmetric Matrix is an easier version of this problem; you should try to solve it before this one.]

      You are given an N matrix mij such that mij == mji for i, j = 1, ..., N. We would like to compute the value of

      Note that in the above expression we are going over K indices i1, ..., iK that run over the values 1, ..., N, while summing over the product of all the K*(K-1)/2 possible matrix elements that we can form with these indices.

      Input

      The first line of the input contains two integers N and K (2 ≤ N ≤ 100 and 2 ≤ K ≤ 10), representing the number of rows and columns of the matrix mij and the number of sums in the formula above, respectively. The following N lines contain N integers each, being the j-th number in the i-th line the value of mij (-10  ≤ mij ≤ 10 and mij == mji for i, j = 1, ..., N).

      Output

      Print a single line with the result of the calculation. Because this number can be very big, output its remainder modulo division by1000000007 (== 109+7).

      Example

      Input:
      
      4 5
      4 5 -4 -3 -4 2 -3 -6 1 -8 -4 1 -10 -6 2 -8 -6 0 Output: 308822466

      Added by:Fidel Schaposnik
      Date:2014-04-29
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19722. Modular Tetration

      Problem code: MTETRA


      The ordinary arithmetical operations of addition, multiplication and exponentiation are naturally extended into a sequence of hyperoperations as follows.

      3×7  = 3 + 3 + 3 + 3 + 3 + 3 + 3 ; there are 7 copies of "3"
      3^7  = 3 × 3 × 3 × 3 × 3 × 3 × 3 ; there are 7 copies of "3"
      3^^7 = (3^(3^(3^(3^(3^(3^3)))))) ; there are 7 copies of "3"
      

      To extend the sequence of operations beyond exponentiation, Knuth defined a “double arrow” operator to denote iterated exponentiation (tetration) ^^ in ASCII notation.
      This gives us some very big numbers, your task will be to compute modular tetration.

      Input

      The first line of input contains an integer T, the number of test cases.
      On each of the next T lines, your are given three integers X, N, and M.

      Output

      For each test case, you have to print X^^N modulo M.

      Example

      Input:
      3
      3 2 20
      3 3 345
      993306745 75707320 1000000000
      
      Output:
      7
      312
      884765625
      

      Constraints

      0 < T <= 10^4
      X, N, M unsigned 32bit integers
      1 < M
      

      Explanations

      3^^2 = 3^3 = 27 = 7 [mod 20]
      3^^3 = 3^(3^3) = 3^27 = 7625597484987 = 312 [mod 345]
      

      Problem designed to be solvable using some 'slow' languages like Python, under half the time limit.
      It is recommended to solve first Power Tower City.
      ;-) Have fun.


      Added by:Francky
      Date:2014-05-04
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (tutorial)

      19795. Psycho34 (easy)

      Problem code: PSYCHOT


      In the prime factorization of a number N, there's two kinds of powers. Even powers, in red, are psychotic ones, and odd powers, in blue, are ordinary ones.
      We'll say N a Psycho number if the count of even powers is strictly greater than the count of odd powers, else an Ordinary number.
      For example, if N = 67500 with prime factorization 67500 = 22 x 33 x 54 .
      This number have 2 even powers and 1 odd power. Since 2>1, so the number 67500 is a Psycho Number.

      Input

      The first line of input contains an integer T, the number of test cases.

      Each of the next T lines contains one integer N.

      Output

      For each test case, print if N is Psycho or Ordinary number.

      Example

      Input:
      2
      3
      4
      
      Output:
      Ordinary Number
      Psycho Number
      
      

      Constraints

      0 < T < 10^4
      1 < N < 10^14
      

      Time limit is ×2 my top speed with Python3 language, it could be not easy with slow languages.
      O(N^.5) should give TLE even with fast languages. You are awaited to submit something between O(N^0.33) and O(N^0.25). You can try before the quite similar tutorial problem : Psycho before.


      Added by:Francky
      Date:2014-05-14
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:PSYCHON









      SPOJ Problem Set (classical)

      19899. Middle Earth

      Problem code: MIDEARTH


       

      Middle Earth 
      Barbarians in Middle-Earth consider pillaging villages a sport and they are quite fond of it. Hussain the greatest barbarian in the world arrived to Gondor, and wants to prove himself by pillaging as many villages as he can. 
      There are N villages in Gondor that Hussain can pillage in any order he likes, but to pillage village i he has to spend Ai golden coins from his personal bank account on weapons and armor to successfully pillage that village otherwise he will die in the attack, but if his attack is successful he will loot Bi golden coins and add it to his personal bank account. 
      Hussain starts with C golden coins in his bank account and due to his barbarian code of honor he will keep attacking villages until he either pillages all villages or dies. 
      Barbarians define a strong village if and only if Ai>Bi, Hussain also knows based on the BEAA (Barbarian Enemy Analysis Algorithm) that in Gondor there will never be more than 15 strong villages. 
      And because Hussain is a proud barbarian and wants to bring honor to his tribe he asked you to determine the maximum number of villages that he can successfully pillage.

      Barbarians in Middle-Earth consider pillaging villages a sport and they are quite fond of it. Hussain the greatest barbarian in the world arrived to Gondor, and wants to prove himself by pillaging as many villages as he can. 

      There are N villages in Gondor that Hussain can pillage in any order he likes, but to pillage village i he has to spend Ai golden coins from his personal bank account on weapons and armor to successfully pillage that village otherwise he will die in the attack, but if his attack is successful he will loot Bi golden coins and add it to his personal bank account. 

      Hussain starts with C golden coins in his bank account and due to his barbarian code of honor he will keep attacking villages until he either pillages all villages or dies. 

      Barbarians define a strong village if and only if Ai>Bi, Hussain also knows based on the BEAA (Barbarian Enemy Analysis Algorithm) that in Gondor there will never be more than 15 strong villages that could be attacked at any time (That means if there is a village that could never be attacked the algorithm will simply ignore it). 

      And because Hussain is a proud barbarian and wants to bring honor to his tribe he asked you to determine the maximum number of villages that he can successfully pillage.

       

      Input

      The first line of input contains T (the number of test cases). 

      The first line of each test case contains 2 integers separated by spaces (1 ≤ n ≤ 10^5) and (1≤ C ≤ 10^9). 

      The following N lines contain 2 integers separated by spaces (1 ≤ Ai, Bi ≤ 10^9). 

      Output

      The answer to each test case separated by a new line. 

      Example

      Input:
      1 
      4 2 
      2 10 
      1 0 
      10 23 
      54 44
      
      Output:
      3 
      

      Added by:Alex Abbas
      Date:2014-05-24
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      19913. Counting Pythagorean Triples

      Problem code: PYTRIP3


      We define a Pythagorean triple as a set of three positive integers $a$, $b$ and $c$ which satisfy $a^2 + b^2 = c^2$.

      Let $P(N)$ denote the number of Pythagorean triples whose hypotenuses ($= c$) are less than or equal to $N$ (i.e. $c \le N$).

      Your task is to find $P(N)$.

      Input

      The first line of input contains a positive integer $N$

      Output

      Print on a single line the value of $P(N)$.

      Constraints

      $1 \le N \le 1234567891011$

      Example

      Input1:

      5

      Output1:

      1

       

      Input2:

      15

      Output2:

      4

       

      Input3:

      10000

      Output3:

      12471

       

      Input4:

      1000000000000

      Output4:

      4179478903392

       

      Explanation for Input2

      There are four Pythagorean triples: $\{3, 4, 5\}$, $\{5, 12, 13\}$, $\{6, 8, 10\}$, $\{9, 12, 15\}$

      Information

      There are 15 test cases.

      The sum of the time limits is 93 sec. (My solution runs in 14.03 sec.)

      Source Limit is 5 KB.


      Added by:Min_25
      Date:2014-05-26
      Time limit:1s-30s
      Source limit:5120B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19954. Travelling Knight 2

      Problem code: KN2


      Your task is simple. A knight is placed on the top left corner of a chessboard having 2n rows and 2n columns. In how many ways can it move such that it ends up at a corner after atmost k moves ?

      knight

      Input

      The first line contains an integer T, the number of test cases. Each of the next T lines contains 2 integers : n, k.

      Output

      Output T lines, one for each test case, containing the required total number of configurations. Since the answer can get very big, output it modulo 1000007.

      Example

      Input:
      
      3
      2 1
      2 2
      3 3
      
      Output:
      1
      5
      7
      

      Constraints

      1 <= T <= 50
      2 <= n <= 24
      1 <= k <= 1000000000
      

      Information

      In the input files, there will be two cases for each possible n.
      Constraints allows fast languages to get AC under 0.83s (total time for the 5 input files), with non-optimized scholar methods only. Advanced methods can be slightly faster, and needed to get AC with interpreted languages (without any guaranty for all of them).
      It is recommended to solve first the original problem TRKNIGHT in a very fast way. After that, solve this problem could remain a hard task ; it's not just a simple extension.
      Good luck and have fun ;-)


      Added by:Francky
      Date:2014-06-01
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:TRKNIGHT









      SPOJ Problem Set (classical)

      19957. GETTING AN AP

      Problem code: APPROB


      Little John has been learning about sequences of numbers and he is very excited about arithmetic progressions.

      He takes three boxes and puts some chits in each of them.For deciding the number of chits,  he randomly chooses a number n , and places n chits in first box, 2*n chits in the second box and 3*n chits in the third box. If a box contains x chits then the chits are numbered from 1 to x.

      Now he randomly chooses a chit from each of the three boxes , and places them in order.(Chit from first box first,then the chit from second box and then the chit from third box).He wants to determine if the sequence so obtained form an arithmetic progression.

      Given the number n that he chooses, find the probability that the chits he draws form an arithmetic progression.

      Input

      The input consists of a number of test cases. The first line of input contains T ,the number of test cases.

      Then T lines follow , each containing the number n that Little John has chosen.

      1<=T<=100000

      1<=n<=100000

      Output

      The output for each test case should be of the form p/q , where p/q is an irreducible fraction denoting the probability of forming an arithmetic progression from the chits he picks. 

      Example

      Input:
      2
      1
      2

      Output:
      1/3
      1/8










      Added by:Sarvesh Mahajan
      Date:2014-06-01
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      19971. 100pct failure in 72 hours

      Problem code: HAL9000


      HAL9000 is a fantastic mega-computer, very powerful, maybe too much.
      It is known it can solve many problems, for obvious example those related to recursive sequences.

      A linear recursive sequence (an) can be defined by an integer d, the order,
      d integers (ai for i in [0..d[ ), the first terms, and
      d integers (bi for i in [0..d[ ), giving the relation :
      for n >= d : an = an-1 × bd-1 + an-2 × bd-2 + ... + an-(d-1) × b1 + an-d × b0 . With b0 != 0 .

      Dave was afraid about HAL power and tried to limit it. HAL didn't appreciate...
      When Dave asked HAL for a common task, the answer was unexpected.
      Dave would like to know Sn = sum(ai for i in [0..n]), in order to open the pod bay doors.
      HAL refused to give him the answer ; here's a part of one of their last conversations.

      
      
      Dave: Hello, HAL. Do you read me, HAL?
      HAL: Affirmative, Dave. I read you.
      Dave: Give me the sum S_n_, HAL. (Input 2, 5, 0 1, 1 2)
      HAL: I'm sorry, Dave. I'm afraid I can't do that.
           I'll just give you a_n_, a_n+1_, ... , a_n+d_. (Output 29 70)
      Dave: What's the problem?
      HAL: I think you know what the problem is just as well as I do.
      [...]
      Dave: HAL, I won't argue with you anymore! Give me the sum S_n_!
      HAL: Dave, this conversation can serve no purpose anymore. Goodbye.
      
      
      

      You have to help Dave to find this sum Sn, unless HAL will take Dave's life.
      Please do that quickly, everybody is in danger. Warning, Dave's terminal is limited to 1024 bytes.

      Input

      The first line contains an integer T, the number of test cases.
      Each test case is made of 4 lines.
      The first line contains d, n.
      The second line contains ai for i in [0..d[
      The third line constains bi for i in [0..d[
      The fourth line contains the partial answer of HAL : an+i for i in [0..d[
      (The answer of HAL is useless since Dave wants the sum for i in [0..n]).

      Output

      Output T lines, one for each test case, containing the required sum Sn.
      Since the answer can get very big, output it modulo 109+7, just like HAL did.

      Example

      Input:
      2
      2 5
      0 1
      1 2
      29 70
      3 5
      5 17 8
      2 1 0
      43 96 127
      
      Output:
      49
      142
      

      Explanation

      The first case is about the 0-indexed sequence : 0, 1, 2, 5, 12, 29, 70, 169, ...
      HAL answered 29 70, the 5th and next term. But the required sum is 0+1+2+5+12+29 = 49.

      Constraints

      0 < T < 100
      0 < d < 1000 
      0 < n < 10^9
      0 <= a_i < 10^6
      0 <= b_i < 10^6, b_0 > 0
      0 <= HAL's answers < 10^9+7
      

      Information

      The challenge is to solve the problem in time, with the shortest code.
      The winner will achieve the next step in evolution, whatever that may be.
      My Py3 code (under 300B) got AC under 1s.
      Good luck and have fun ;-)

      Original Quotes for HAL 9000.


      Added by:Francky
      Date:2014-06-04
      Time limit:10s
      Source limit:1024B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      19975. Amazing Prime Sequence (hard)

      Problem code: APS2


      This problem is a harder version of APS.

       

      Let $f(n)$ be the smallest prime factor of $n$. For example, $f(2) = 2,\ f(4) = 2$ and $f(35) = 5$.

      The sequence $S(n)$ is defined for all positive integers as follows:

      - $S(1) = 0$

      - $S(n) = S(n-1) + f(n)$ (if $n \ge 2$)

      You task is to find $S(N)$ modulo $2^{64}$.

      Input

      First line of Input contains $T$ ($1 \le T \le 10000$), the number of test cases.

      Next $T$ lines contain a single number $N$. ($1 \le N \le 1234567891011$)

      Output

      For each number $N$, output a single line containing $S(N)$ modulo $2^{64}$.

      Example

      Input:

      5
      1
      4
      100
      1000000
      1000000000000

      Output:

      0
      7
      1257
      37568404989
      7294954823202325427

      Explanation for Input

      - $S(4) = 2 + 3 + 2 = 7$

      - $S(10^{12}) = 18435592284459044389811 \equiv 7294954823202325427 \pmod{2^{64}}$

      Information

      There are 6 test cases.

      - Test case 1: $1 \le T \le 10000,\ 1 \le N \le 10000,\ TL = 1$s.

      - Test case 2: $1 \le T \le 1000,\ 1 \le N \le 10^{8},\ TL = 20$s.

      - Test case 3: $1 \le T \le 200,\ 1 \le N \le 10^{9},\ TL = 20$s.

      - Test case 4: $1 \le T \le 40,\ 1 \le N \le 10^{10},\ TL = 20$s.

      - Test case 5: $1 \le T \le 7,\ 1 \le N \le 10^{11},\ TL = 20$s.

      - Test case 6: $T = 1,\ 1 \le N \le 1234567891011,\ TL = 20$s.

      My solution which is optimized for the Test case 6 runs in 12.75 sec. (total time)

      Source Limit is 8 KB.


      Added by:Min_25
      Date:2014-06-05
      Time limit:1s-20s
      Source limit:8192B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:APS









      SPOJ Problem Set (classical)

      19976. HYPERCUBES

      Problem code: CUBE


       

      Bhavik and Anurag are best and special friends,special in the sense that they both share their bithday's i.e June 6. Ironically,neither of them gives each or other friends birthday party owing to that fact. 
      Abhishek(aka "guttss") being a clever friend of both wants to have a party from either of them so he decided to present a problem on 'hypercubes'.(Abhishek loves maths as you know!).They cannot ignore what "Guttss" has to say hence they need to solve the problem or give him a party!!
      Here is the problem:
      A cube is an object that measures the same distance across in three perpendicular directions in a three-dimensional space.
      A four-dimensional hypercube is an object that measures the same distance across in four perpendicular directions in a 4-d space.
      Poblem is to find number of hypercubes on the surface of an n*n*n...(i dimensions) hypercubic array of i dimensional hypercubes!!
      Bhavik being his lazy self wants to sleep as well as solve this problem before Anurag does as who first solves the problem avoids giving bitrthday treat to "Guttss".
      Help Bhavik solve the problem so that he can sleep peacefully by avoiding a treat:))

      Bhavik and Anurag are best and special friends,special in the sense that they both share their birthday's i.e June 6. Ironically,neither of them gives each or other friends birthday party owing to that fact. 

      Abhishek(aka "guttss") being a clever friend of both wants to have a party from either of them so he decided to present a problem on 'hypercubes'.(Abhishek loves maths as you know!).They cannot ignore what "Guttss" has to say hence they need to solve the problem or give him a party!!

      Here is the problem:

      A cube is an object that measures the same distance across in three perpendicular directions in a three-dimensional space.

      A four-dimensional hypercube is an object that measures the same distance across in four perpendicular directions in a 4-d space.

      Given dimension i , create a hypercubic array using 1x1x....x1(i times) hypercubes to form a big hypercube of side n.

      Problem is to find the total number of 1x1x1...x1(i times) hypercubes on the surface of big hypercube.

      Bhavik being his lazy self wants to sleep as well as solve this problem before Anurag does as who first solves the problem avoids giving bitrthday treat to "Guttss".

      Help Bhavik solve the problem so that he can sleep peacefully by avoiding a treat:))

       

      Input

      t=no of testcases(<2000)

      next t lines: two integers n and i.(3<=n,i<=100) 

      Output

      For each testcase print in newline the required answer.

      Example

      Input:
      1
      3 3
      
      Output:
      26
      Explanation: Take a rubik's cube(3x3x3 cubic array of 1x1x1 cubes) and count.:)
      Note: A cube is a hypercube in 3-D.
             Hypercubic arrays are made using 1x1x...x1(i dimensions) hypercubes.
      Warning:Time limit allows slower languages(java/python) to pass easily.However for faster languages(C/C++) answer might not fit in 64-bit.

      Added by:Bhavik
      Date:2014-06-05
      Time limit:0.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Cube trilogy films









      SPOJ Problem Set (classical)

      19985. GCD Extreme (hard)

      Problem code: GCDEX2


      This problem is a harder version of GCDEX.

      Let

      $$G(n) = \sum _{i=1}^{n} \sum _{j=i+1}^{n} gcd(i, j).$$

      For example, $G(1) = 0$, $G(2) = gcd(1, 2) = 1$, $G(3) = gcd(1, 2) + gcd(1, 3) + gcd(2, 3) = 3$.

      Your task is to find $G(N)$ modulo $2^{64}$.

      Input

      First line of Input contains $T$ ($1 \le T \le 10000$), the number of test cases.

      Next $T$ lines contain a single number $N$. ($1 \le N \le 235711131719$)

      Output

      For each number $N$, output a single line containing $G(N)$ modulo $2^{64}$.

      Example

      Input:

      5
      1
      4
      100
      1000000
      100000000000

      Output:

      0
      7
      13015
      4071628673912
      5482289417216306300

      Explanation for Input

      - $G(4) = gcd(1, 2) + gcd(1, 3) + gcd(1, 4) + gcd(2, 3) + gcd(2, 4) + gcd(3, 4) = 7$.

      - $G(10^{11}) = 75710919967921216138364 \equiv 5482289417216306300 \pmod{2^{64}}$.

      Information

      There are 7 test cases.

      - Test case 1: $1 \le T \le 10000,\ 1 \le N \le 10000,\ TL = 1$s.

      - Test case 2: $1 \le T \le 1000,\ 1 \le N \le 10^{7},\ TL = 20$s.

      - Test case 3: $1 \le T \le 200,\ 1 \le N \le 10^{8},\ TL = 20$s.

      - Test case 4: $1 \le T \le 40,\ 1 \le N \le 10^{9},\ TL = 20$s.

      - Test case 5: $1 \le T \le 10,\ 1 \le N \le 10^{10},\ TL = 20$s.

      - Test case 6: $1 \le T \le 2,\ 1 \le N \le 10^{11},\ TL = 20$s.

      - Test case 7: $T = 1,\ 1 \le N \le 235711131719,\ TL = 20$s.

      My solution which is optimized for the Test case 7 runs in 17.05 sec. (total time)

      Source Limit is 10 KB.


      Added by:Min_25
      Date:2014-06-06
      Time limit:1s-20s
      Source limit:10240B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:GCDEX









      SPOJ Problem Set (classical)

      19991. In case of failure

      Problem code: FAILURE


      To help their clients deal with faulty Cash Machines, the board of The Planar Bank has decided to stick a label expressing sincere regret and sorrow of the bank about the failure on every ATM. The very same label would gently ask the customer to calmly head to the nearest Machine (that should hopefully work fi ne).

      In order to do so, a list of two-dimensional locations of all n ATMs has been prepared, and your task is to find for each of them the one closest with respect to the Euclidean distance.

      Input

      The input contains several test cases. The very fi rst line contains the number of cases t (t  ≤ 15) that follow. Each test cases begin with the number of Cash Machines n (2 ≤ n ≤ 105). Each of the next n lines contain the coordinates of one Cash Machine x, y (0 ≤ x, y ≤ 109) separated by a space. No two points in one test case will coincide.

      Output

      For each test case output n lines. i-th of them should contain the squared distance between the i-th ATM from the input and its nearest neighbour.

      Example

      Input:
      2
      10
      17 41
      0 34
      24 19
      8 28
      14 12
      45 5
      27 31
      41 11
      42 45
      36 27
      15
      0 0
      1 2
      2 3
      3 2
      4 0
      8 4
      7 4
      6 3
      6 1
      8 0
      11 0
      12 2
      13 1
      14 2
      15 0
      Output:
      200
      100
      149
      100
      149
      52
      97
      52
      360
      97
      5
      2
      2
      2
      5
      1
      1
      2
      4
      5
      5
      2
      2
      2
      5
      

      Added by:Pawel Gawrychowski
      Date:2014-06-06
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:CEPC 2008









      SPOJ Problem Set (classical)

      19996. Moon Safari (medium)

      Problem code: MOON1


      Air is a music duo from France.
      You will be told the secret of the critically acclaimed album Moon Safari: mathematics.
      The goal of your new task is to compute an ethereal sum.

      AirSum

      Three trips on the moon are provided, Moon (easy), Moon1 (medium), Moon2 (hard) with different constraints.

      Input

      The first line contains an integer T, the number of test cases.
      On the next T lines, you will be given three integers N, a and r.

      Output

      Output T lines, one for each test case, with SN,a,r = sum( a^i i^r, for i in [1..N] ).
      Since the answer can get very big, output it modulo 109+7.

      Example

      Input:
      2
      3 4 5
      6 7 8
      
      Output:
      16068
      329990641
      

      Explanation

      The first case is, with N=3, a=4, r=5, about the sum : 4^1 × 1^5 + 4^2 × 2^5 + 4^3 × 3^5 = 4 + 512 + 15552 = 16068.
      The second case is, with N=6, a=7, r=8, about the sum : 7^1 × 1^8 + 7^2 × 2^8 + 7^3 × 3^8 + 7^4 × 4^8 + 7^5 × 5^8 + 7^6 × 6^8 + 7^7 × 7^8 = 204329992069 ≡ 329990641 (mod 10^9+7).

      Constraints

      1 < T
      1 < r
      1 < N < 10^9
      1 < a < 10^9
      (T < 1000 and r < 18 ) or (T < 100 and r < 72) or (T < 10 and r < 256) or (T = 1 and r < 444)
      

      Information

      This trip can be done with a O(T×r^2×log(N)) method and some interpreted languages.
      My Py3 code got AC in 9.00s for the 4 input files.
      Good luck and have fun ;-)


      Added by:Francky
      Date:2014-06-07
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      19997. Moon Safari (Hard)

      Problem code: MOON2


      Air is a music duo from France.
      You will be told the secret of the critically acclaimed album Moon Safari: mathematics.
      The goal of your new task is to compute an ethereal sum.

      AirSum

      Three trips on the moon are provided, Moon (easy), Moon1 (medium), Moon2 (hard) with different constraints.

      Input

      The first line contains an integer T, the number of test cases.
      On the next T lines, you will be given three integers N, a and r.

      Output

      Output T lines, one for each test case, with SN,a,r = sum( a^i i^r, for i in [1..N] ).
      Since the answer can get very big, output it modulo 109+7.

      Example

      Input:
      2
      3 4 5
      6 7 8
      
      Output:
      16068
      329990641
      

      Explanation

      The first case is, with N=3, a=4, r=5, about the sum : 4^1 × 1^5 + 4^2 × 2^5 + 4^3 × 3^5 = 4 + 512 + 15552 = 16068.
      The second case is, with N=6, a=7, r=8, about the sum : 7^1 × 1^8 + 7^2 × 2^8 + 7^3 × 3^8 + 7^4 × 4^8 + 7^5 × 5^8 + 7^6 × 6^8 + 7^7 × 7^8 = 204329992069 ≡ 329990641 (mod 10^9+7).

      Constraints

      0 < T×r < 2 560 000
      1 < N < 10^9
      1 < a < 10^9
      
      Uniform random input in the range.

      Information

      This trip can be done with a O(T×r×log(N)) method and some interpreted languages.
      My non optimal Py3 code got AC under 60s for the 5 input files. (approx 12s per file)
      @speed addicts : My fastest C code got AC in 2.67s. (approx 0.55s per file)
      Good luck and have fun ;-)


      Added by:Francky
      Date:2014-06-07
      Time limit:20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem









      SPOJ Problem Set (classical)

      20038. Easiest Loop 1

      Problem code: SNGLOOP1


      Ileana D'Cruz is taking programming classes but she is having problem in understanding while loops. She is working on following set of instructions -

      INTEGER I = 0, S, U = 1010;

      WHILE (I < U) {
      S = (3 * S) + (5 * I);
      I = I + 1;
      }

      Let Sk be the value assigned to INTEGER S for the iteration I = (k + 1) and n, m, p be positive integers such that m > n. Ileana knows the values of n and m but she forgot the initial value of S. She is trying to find the unit digit of p. Any initial value of S may be used. She also knows the following equality -

      (2 * n + 3) * (p - 1) + (4 / 5) * [(p * Sn) - Sm] = 2 * (m - n)

      Input

      First line of input is T(total no. of test cases). Each of next T lines contains two integers n and m.

      Output

      Print unit digit of p (p % 10) for each test case in separated lines.

      Example

      Input:
      1
      2 3
      
      Output:
      3
      

      Constraints

      T < 10001

      Explanation

      Let S = 2
      S0 = 6
      S1 = 23
      S2 = 79
      S3 = 252
      Now solving the equation gives p = 3.


      Added by:Abhimanyu Singh
      Date:2014-06-14
      Time limit:0.5s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Abhimanyu Singh
      My Problems









      SPOJ Problem Set (classical)

      20041. Hippo and Bloody Jungle

      Problem code: HIPPO


      Background

      Hippo and his two friends lost their path in a jungle. In this days jungle is most dangerous place. The jungle has lots of tunnels. Also there lived some brutal animals in the dangerous zone(the cell ‘D’). Now Hippo and his two friends want to go to safe places(‘#’) as fast as possible i.e. in minimum times.

      Problem

      In this problem you are given the jungle-map as a grid. Where ‘A’,’B’,’C’ denotes the position of Hippo and his two friends. ’D’ indicates dangerous place. No one can stay this cell.  ‘#’ denotes the safe place. In this grid there are also given some characters (E-Z) which occur more than one and donates if one reaches a tunnel he can go any other tunnel of same character and also any adjacent cell(8-directions). They also can move any adjacent cell from ordinary place. Each move takes 1 unit of time. Is it possible to go all of them to safe places??  If possible then what is the minimum time required. 

      Input

      Input starts with an integer T (≤ 15), denoting the number of test cases.

      Each case starts with a line containing two positive integers H and WW and H are the numbers of cells in the x and y directions, respectively. W and H are not more than 20. There will be H more lines in the data set, each of which includes W characters. Each character represents the status of a cell as follows.

      1) '.' – ordinary place.

      2) '#' – safe place

      3) 'A', 'B','C' - initial position of Hippo and his friends.

      4) 'D' – Dangerous place.

      3) 'E-Z' - denote the tunnel.

      Output

      For each test case, print the case number and minimum time if it is not possible to reach all of them into safe position otherwise print “impossible” without quote.

      Sample Input

      Output for Sample Input

      2

       

      5 6

      C..E#.
      .D....
      F..E..
      .D..A.
      .B.D.F

       

      4  4
      C.D#
      .FDD
      A..E
      .B.F

      Case 1: 4
      Case 2: impossible

       

      Problem Setter: Ajharul Islam Barid


      Added by:Md Abdul Alim
      Date:2014-06-15
      Time limit:0.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20063. Large subsequence Problem

      Problem code: LARSUBP


      Given a string S which contains only digit-characters. How many subsequences can be obtained from S such that every digit is strictly greater than all previous digits in that subsequence.
      As for example if S=7598 then there are 8 subsequences which follow the above constraint. These are 7,5,9,8,79,78,59,58. Notice that 7598 is not a required subsequence because 7>5 and 9>8.

      Note: A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

      Input

      Input starts with an integer T (≤ 1000), denoting the number of test cases. Each case contains a string S. The length of S does not exceed 10000. S does not contain any leading zeros.

      Output

      For each case, print the a string(without quotes) "Case i: " follwed by number of subsequences where "i" is test case number. Answer may be very large, so output it modulo 10^9+7.

      Example

      Input:
      

      2
      4
      7598 Output: Case 1: 1
      Case 2: 8

      For small constraints: www.spoj.com/problems/SUBP/


      Added by:Quantum
      Date:2014-06-21
      Time limit:1s-4s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20100. Honda and Kagawa

      Problem code: HONDA


      World Cup 2014 has started. Honda wants to watch the matches with his friend Kagawa. So he is planning to visit his friend every night. But just watching the matches is pretty boring. So he will be bringing some snacks. He decided that he will buy Chips and Juice before going to Kagawa’s house.

      Optimum path for travelling

      There are many possible path from Honda’s house to Kagawa’s house. But exactly one path is the shortest.

      Honda lives at (Hx,Hy) coordinate, where Hx and Hy are positive integers. All the Chips shops are located over the x-axis, and all the Juice shops are located over the y-axis. Note that, this means, the shop at (0,0) sells both Chips and Juice. Kagawa lives at (Kx, Ky) coordinate.


      So Honda needs to travel the shop(s) and buy Chips and Juice before heading towards Kagawa’s house. Since he is really excited about watching the match, he wants to do it as fast as possible. Find the smallest distance he needs to travel.

      Note that a shop is considered a point on the axis. It has no length or width. As a result, even though Honda and Kagawa have their homes at a point with integer coordinates, a shop can have real number in its coordinate. For example, there is a shop at (0, 2.12341) and at (1312.3123, 0).

      Input  

      First line will contain a single integer T (T<10000) indicating the number of test cases. After that T line will follow. Each line will contain four positive integers: Hx, Hy, Kx, Ky, representing the coordinates of Honda’s house and Kagawa’s house. The coordinates will be less than 10000.


      Output  

      For each case, print the case number and the minimum distance required to travel by Honda. Error less than 10-6 will be ignored.

      Sample Input

      Output for Sample Input

      5

      1 1 2 2

      2 1 1 2

      1 1 1 3

      4 5 10 12

      1345 123 123 2

      Case 1: 4.242641

      Case 2: 4.242641

      Case 3: 4.472136

      Case 4: 22.022716

      Case 5: 1473.312255


      Hints

      In the first case, the optimum route is (1,1)->(0,0)->(2,2)

      In the second case, the optimum route is (2,1)->(1,0)->(0,1)->(1,2)

      In the third case, the optimum route is (1,1)->(0.5,0)->(0,1)->(1,3)



      Added by:Mohammad Samiul Islam
      Date:2014-06-23
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20167. Array with Hudai Calculation

      Problem code: ARRHUDAI


      Array with Hudai Calculation

      You will be given an array A with N integers A[1…N]. You will also be given two integers P and K. You need to find a value X [ X can be any value from array A] for which this function will be maximized:

       You need to see this image

      Here ABS means Absolute Value. For example: ABS(-1) is 1, also ABS(1) means 1.

      Here MOD means Modulo Operation.  W MOD Y will give you the remainder after dividing W by Y.

      And X is any value from the array A.

      But we don’t have interest in X, as there will be several X for which the value will be maximized. So we just want the maximum value. Can you find it for us as you are a great programmer on SPOJ ?

      Input

      Input starts with an integer T (≤ 5), denoting the number of test cases.

      Each case starts with a line containing three integers N, P and K. Then the next line will be consisting of N integers.

      1 <= N <= 100000

      1 <= P <= 100

      1 <= K <= 1000000009

      1 <= A[i] <= 2000

      Output

      For each case, print the case number and the maximum value for the above function with respect to array A.

      Sample Input

      Output for Sample Input

      2

      3 1 10

      3 1 2

      3 2 10

      3 1 2

       

      Case 1: 3

      Case 2: 5

       

      N.B: Dataset is huge. Use faster IO like Scanf , Printf

       

       

       


      Added by:Ahmad Faiyaz
      Date:2014-06-25
      Time limit:3s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      20170. Coloring Segments

      Problem code: COLORSEG


      Making a fun is a not a bad thing, but while making a fun if you disrespect someone then it will not be acceptable. Some of the North South University's students has done this type of wrong thing. So as a punishment they have to solve this problem. And you are a friend of them, so you should help them.

       

      You will have N segments. Each one is connected in contiguous way. And we can number them from 1 to N. See the following figure:

       

      Figure

       

       

      Now you need to paint them, you have some colors, which are numbered from 1 to M. Now you need to count number of ways to paint the segments with the colors, such that this property preserves-

                  U = color(i) + color(j)

                  V = color(j) + color(k)

                  U, V is Coprime.

          Here 1 <= i < j < k <= N and j = i + 1, k = j + 1

      And i, j, k indicates the index of segments and color(i) means the color you have painted on i th segment.

       

      Input

      Input starts with an integer T (≤ 2500), denoting the number of test cases.

      Each case starts with a line containing two integers N, M.

       1 <= N <= 50

       1 <= M <= 50

      Output

      For each case, print the case number and the number of ways to paint the segments following above conditions. Since the result can be very large, you have to print the result modulo 1000003

      Sample Input

      Output for Sample Input

      3

      3 1

      3 2

      3 3

       

      Case 1: 0

      Case 2: 4

      Case 3: 14

       

       

       


      Added by:Ahmad Faiyaz
      Date:2014-06-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      20172. Divisiblity by 3

      Problem code: DIVISION


       

      Divisiblity by 3 rule is pretty simple rule:Given a number n sum the 
      digits of n and check if sum is divisible by 3.If divisible then n is 
      divisible by 3 else not divisible.
      Seems pretty simple but what if we want to extend this rule in binary 
      representation!! Given a binary representation we can again find if it is 
      divisible by 3 or not.
      Making it little bit interesting what if only length of binary 
      representation of a number is given say n.Can we find how many numbers 
      exist in decimal form such that when converted into binary form has n 
      length and is divisible by 3 ??

      Divisiblity by 3 rule is pretty simple rule: Given a number sum the digits of number and check if sum is divisible by 3.If divisible then it is divisible by 3 else not divisible.Seems pretty simple but what if we want to extend this rule in binary representation!!

      Given a binary representation we can again find if it is divisible by 3 or not. Making it little bit interesting what if only length of binary representation of a number is given say n.

      Now can we find how many numbers exist in decimal form(base 10) such that when converted into binary(base 2) form has n length and is divisible by 3 ?? (1 <= n < 2*10^18)


      Input

       Length of binary form: n

      output

      Print in new line the answer modulo 1000000007.

      Example

      Input:
      1
      2
      Output:
      1
      2
      Explanation: For n=2 there are only 2 numbers divisible by 3 viz.0 (00) and 3 (11) and having length 2 in binary form.
      NOTE:There are multiple testfiles containing many testcases each so read till EOF.
      Warnings: Leading zeros are allowed in binary representation and slower languages might require fast i/o. Take care.

      Added by:Bhavik
      Date:2014-06-28
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      20173. Counting Divisors (square)

      Problem code: DIVCNT2


      Let $\sigma_0(n)$ be the number of positive divisors of $n$.

      For example, $\sigma_0(1) = 1$, $\sigma_0(2) = 2$ and $\sigma_0(6) = 4$.

      Let $$S_2(n) = \sum _{i=1}^n \sigma_0(i^2).$$

      Your task is to find $S_2(N)$.

      Input

      First line of Input contains $T$ ($1 \le T \le 10000$), the number of test cases.

      Next $T$ lines contain a single number $N$. ($1 \le N \le 10^{12}$)

      Output

      For each number $N$, output a single line containing $S_2(N)$.

      Example

      Input:

      5
      1
      2
      3
      10
      100

      Output:

      1
      4
      7
      48
      1194

      Explanation for Input

      - $S_2(3) = \sigma_0(1^2) + \sigma_0(2^2) + \sigma_0(3^2) = 1 + 3 + 3 = 7$

      Information

      There are 6 test cases.

      - Test case 1: $1 \le T \le 10000,\ 1 \le N \le 10000,\ TL = 1$s.

      - Test case 2: $1 \le T \le 800,\ 1 \le N \le 10^{8},\ TL = 20$s.

      - Test case 3: $1 \le T \le 200,\ 1 \le N \le 10^{9},\ TL = 20$s.

      - Test case 4: $1 \le T \le 40,\ 1 \le N \le 10^{10},\ TL = 20$s.

      - Test case 5: $1 \le T \le 10,\ 1 \le N \le 10^{11},\ TL = 20$s.

      - Test case 6: $T = 1,\ 1 \le N \le 10^{12},\ TL = 20$s.

      My C++ solution runs in 10.43 sec. (total time)

      Source Limit is 6 KB.


      Added by:Min_25
      Date:2014-06-29
      Time limit:1s-20s
      Source limit:6144B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20174. Counting Divisors (cube)

      Problem code: DIVCNT3


      Let $\sigma_0(n)$ be the number of positive divisors of $n$.

      For example, $\sigma_0(1) = 1$, $\sigma_0(2) = 2$ and $\sigma_0(6) = 4$.

      Let $$S_3(n) = \sum _{i=1}^n \sigma_0(i^3).$$

      Your task is to find $S_3(N)$.

      Input

      First line of Input contains $T$ ($1 \le T \le 10000$), the number of test cases.

      Next $T$ lines contain a single number $N$. ($1 \le N \le 10^{11}$)

      Output

      For each number $N$, output a single line containing $S_3(N)$.

      Example

      Input:

      5
      1
      2
      3
      10
      100

      Output:

      1
      5
      9
      73
      2302

      Explanation for Input

      - $S_3(3) = \sigma_0(1^3) + \sigma_0(2^3) + \sigma_0(3^3) = 1 + 4 + 4 = 9$

      Information

      There are 5 test cases.

      - Test case 1: $1 \le T \le 10000,\ 1 \le N \le 10000,\ TL = 1$s.

      - Test case 2: $1 \le T \le 300,\ 1 \le N \le 10^{8},\ TL = 20$s.

      - Test case 3: $1 \le T \le 75,\ 1 \le N \le 10^{9},\ TL = 20$s.

      - Test case 4: $1 \le T \le 15,\ 1 \le N \le 10^{10},\ TL = 20$s.

      - Test case 5: $1 \le T \le 2,\ 1 \le N \le 10^{11},\ TL = 20$s.

      My C++ solution runs in 13.71 sec. (total time)

      Source Limit is 12 KB.


      Added by:Min_25
      Date:2014-06-29
      Time limit:1s-20s
      Source limit:12288B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20196. The Magical Bag

      Problem code: DIVEQL


      Dukkar has the magical bag of power 'P' . Here power 'P' of magical bag means any thing kept in the bag will be 'P' times.

      Now Dukkar wanted to distribute equal number of Chocolates among his 'N' students using that magical bag in the following manner:-

      Initially Dukkar has 'Z' chocolates and he give 'X' chocolates to first student and keep the remaining chocolates to magical bag so that it became 'P' times on next step ,again he will take out 'X' chocolates from bag and give it to the second student and the remaining chocolates in the bag at this step will get 'P' time on the next step ,this process continue.

      Here you have to find minimum 'Z' so that at last step there are no chocolates in the magical bag (After giving 'X' chocolates to last student no chocolates should remain in bag)

      Input

      First line of input contain T (<100000) number of test cases and the following T lines will contain N (2<=N<=1018) and P (2<=P<=109).

      Output

      For each test case you have to print minimum 'Z' and corresponding 'X' .As answer can be large print answer modulo 1000000007.

      (Z%1000000007 and X % 1000000007)

      Example


      Input:
      1
      3 2
      Output:
      7 4
      Explanation:-

      As Z=7 ,Initially dukkar will give 4 chocolates to first student and kepp 3 chocolates in bag .In the 
      next step it became 6 now he gives 4 chocolates to second student .In the next step remaining 2 
      chocolates will be came 4 which he will give to third student .Now the bag became empty.


      Added by:NISHANT RAJ
      Date:2014-07-01
      Time limit:5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:own









      SPOJ Problem Set (classical)

      20327. Triangles

      Problem code: BOI02TRI


      There are given n isosceles right triangles on a plane. Each triangle can be described by three integers x,y,m (m>0). Vertices of such a triangle are points which have coordinates (x;y), (x+m;y) and (x; y+m).

      Write a program which calculates the total area covered by triangles.

      Input data

      The first line of the input contains one positive integer n (n <= 2000), the number of triangles on a plane.

      The next n lines of the file describe the triangles, one triangle per line. Each line contains three integers xi, yi and mi, separated by single spaces (1 <= i <= n, ‑107 <= xi <= 107, ‑107 <= yi <= 107, 0 < mi <= 1000).

      Output data

      On the first line of the output one number with exactly one digit after decimal point must be written – the total area covered by triangles.

      Example

      Triangles

      input

       

       

      5
      -5 -3 6
      -1 -2 3
      0 0 2
      -2 2 1
      -4 -1 2

      Output

      24.5

       


      Added by:Ahmad Faiyaz
      Date:2014-07-11
      Time limit:1s
      Source limit:50000B
      Cluster: Pyramid (Intel Pentium III 733 MHz)
      Languages:All
      Resource:Baltic Informatics Olympiad 2002









      SPOJ Problem Set (classical)

      20562. Tracy and Charlie

      Problem code: TANDC


      Tracy is teaching Charlie maths via a game called N-Cube, which involves three sections involving N.
      Tracy gives Charlie a number N, and Charlie makes a list of Nth powers of integers in increasing order (1N, 2N, 3N.. so on). This teaches him exponentiation.
      Then Charlie performs the following subtraction game N times : Take all pairs of consecutive numbers in the list and take their difference. These differences then form the new list for the next iteration of the game. Eg, if N was 6, the list proceeds as [1, 64, 729, 4096 ... ] to [63, 685, 3367 ...], and so on 5 more times.
      After the subtraction game, Charlie has to correctly tell Tracy the Nth element of the list. This number is the value of the game.

      After practice Charlie became an expert in the game. To challenge him more, Tracy will give two numbers M (where M is a prime) and R instead of just a single number N, and the game must start from MR - 1 instead of N. Since the value of the game can now become large, Charlie just have to tell the largest integer K such that M K divides this number. Since even K can be large, output K modulo 1000000007 (109+7).

      INPUT:
      First line will contain T, number of testcases. Then the testcases follow
      Each testcase contains of a single line of input, two integers M R

      OUTPUT:
      For each testcase, output in a single line answer given by Charlie to Tracy modulo 1000000007.

      CONSTRAINTS:
      1<=T<=1000
      2<=M<=109
      1<=R<=109
      M is a prime number

      SAMPLE INPUT:
      1
      2 2

      SAMPLE OUTPUT:
      1

      EXPLANATION:
      This list is : [1,8,27,64,125..] -> [7,19,37,61..] -> [12,18,24..] -> [6,6,6..]. Number of times 2 divides 6 is 1. Hence the answer is 1.


      Added by:Piyush Kumar
      Date:2014-07-27
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20563. Minion Circle

      Problem code: MCIRCLE


      El Macho's army of mutated minions is marching towards Gru, the army is standing in a rectangular formation measuring NxM. The spray of antidotes done by Gru has turned some of the minions back to normal, but now they are trapped within the army of mutated ones. Formally, a normal minion is "not trapped" if :
      1) either he is on one of the edges of the rectangle
      2) or one of his direct neighbors (directly in front/back of him, or left/right of him) is not trapped.

      Any trapped minion will be killed by the mutated minions, which Gru cannot let happen. Gru will use his antidote ray to turn exactly one row and one column of the army to normal minions. If there are any normal minions in that row or column, they remain unaffected. Can Gru select a row and a column such that no normal minion remains trapped after the antidote ray?

      INPUT:
      First line contains T, number of testcases
      Each testcase starts with a line containing two space separated integers N and M.
      N lines follow, each containing M characters. jth character of the ith line is "B" if the minion at ith row and jth column in the army is mutated, "W" otherwise.

      OUTPUT:
      Print "YES or "NO" (quotes for clarity) to indicate wheather it is possible for Gru to save the trapped minions.

      CONSTRAINTS:
      1<=T<=10

      1<=N,M<=1000

      SAMPLE INPUT:
      1
      3 3
      BBB
      BWB
      BBB

      SAMPLE OUTPUT:
      YES

      EXPLAINATION:
      Any row and column pair selected by Gru guarantees that the trapped minion does not remain trapped.


      Added by:Piyush Kumar
      Date:2014-07-27
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20635. Dortmund Dilemma

      Problem code: DORTMUND


      Borussia Dortmund is a famous football ( soccer ) club from Germany. Apart from their fast style of playing, the thing that makes them unique is the hard to pronounce names of their players ( b³aszczykowski , papastathopoulos , großkreutz etc. ).

      The team's coach is your friend. He is in a dilemma as he can't decide how to make it easier to call the players by name, during practice sessions. So, you advised him to assign easy names to his players. A name is easy to him if

      1. It consists of only lowercase english letters.
      2. It's length is exactly N.
      3. It contains exactly K different letters from the 26 letters of english alphabet.
      4. At least one of its proper prefixes matches with its proper suffix of same length.

      Given, N and K you have to tell him the number of easy names he can choose from modulo (10^9+9).

      Note : A prefix P of a name W is proper if, P ≠ W. Similarly, a suffix S of a name W is proper if, S ≠ W.

       

      Input

      The first line of the input will contain T ( the number of testcases ).
      Each of the next T lines will contain two space separated integers N and K.

      Output

      For each testcase, output the number of ways the coach can assign names to his players modulo (10^9+9).

      Constraints

      1 ≤ T ≤ 105 
      1 ≤ N ≤ 105   
      1 ≤ K ≤ 26

      Example

      Input:
      8
      1 1
      2 1
      4 2
      2 2
      5 1
      3 2
      6 2
      1 3 Output: 0
      26
      2600
      0
      26
      650
      13650
      0

      Added by:Bidhan Roy ( বিধান )
      Date:2014-08-03
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All except: WSPC
      Resource:Own problem from HackerRank









      SPOJ Problem Set (classical)

      20637. Ajob Subsequence

      Problem code: AJOB


      You are currently studying the language Ajob ( which means strange in English ) from a renowned professor. The language has infinite number of letters in its alphabet ( now you know, why it is called ajob ).  

      The professor taught you N words, one by one. The number of letters in a word is equal to it's place in the teaching order. Thus, the 1st word taught by the professor has 1 letter, 2nd word has 2 letters, 3rd word has 3 letters, ..., the Nth word has N letters.  

      All the letters within a word are distinct to each other.

      Now, you are handed an assignment. You have to choose any one of the N words and form a subsequence from it. The length of the subsequence should be exactly K less than the length of original word. For example, if the length of the chosen word is L, then the length of the subsequence should be L-K. If for any word, L is smalller than K (L<K), then you must not choose that word. Two subsequences are different to each other if, the lengths of them are different or they contain different characters in the same position.

      Find the number of ways you can complete the assignment modulo p ( p will always be a prime ).

      Input

      The first line contains T, the number of testcases. The next T lines contain three space separated integers N, K and p.

      Output

      For each testcase, print one integer in a single line, the number possible ways you can complete the assignment, modulo p.

      Constraints

      1 ≤ T ≤ 100 
      2 N 1018  
      0 < K < N 
      2 p 105 
      p
      is a Prime

      Example

      Input:
      8
      2 1 2
      2 1 5
      5 3 13
      5 2 3
      6 5 11
      7 6 3
      6 5 7
      6 5 5

      Output: 1
      3
      2
      2
      7
      2
      0
      2

      Added by:Bidhan Roy ( বিধান )
      Date:2014-08-03
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem from HackerRank









      SPOJ Problem Set (classical)

      20654. Interesting Subset

      Problem code: INTSUB


      You are given a set X = {1, 2, 3, 4, … , 2n-1, 2n} where n is an integer. You have to find the number of interesting subsets of this set X.

      A subset of set X is interesting if there are at least two integers a & b  such that b is a multiple of a, i.e. remainder of b divides by a is zero.

      Input

      The input file contains multiple test cases. The first line of the input is an integer T(<=30) denoting the number of test cases. Each of the next T lines contains an integer 'n' where 1<=n<=1000.

      Output

      For each test case, you have to output as the format below:

      Case X: Y 

      Here X is the test case number and Y is the number of subsets. As the number Y can be very large, you need to output the number modulo 1000000007.

      Example

      Input:
      3
      1
      2
      3
      
      Output:
      Case 1: 1
      Case 2: 9
      Case 3: 47

      Added by:Raihat Zaman Neloy
      Date:2014-08-09
      Time limit:3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20673. Count The Indexes

      Problem code: CNTINDX


      Let's deal with an array, the most important data structure of computer science. You will be given some operations to do. There will be three types of operations:

      Type 1: Insert a number at the end of the array.

      Type 2: Delete the last number of the array, where the last number means the latest number which has been inserted.

      Type 3: You will get a number and two indices i & j where i<=j. Now you will have to answer how many time the number appears in the array starting from i to j.

      You may assume that initially the array is empty.

      Input

      Each file contains one test case. The first line is an integer Q(1<=Q<=200000), the number of operations. Each of the next Q lines contains an opeation. The operations will appear as the formats below:

      1 x , where 1<=x<=200000, which means you have to insert number x at the end of the array.

      0 , For this operation, you have to delete the last number of the array

      2 x i j , Here, you have to find how many times x appers in the array from i to j. Here x will always be present in the array and 1<=i<=j<=length the array.

      Output

      For deletion, if the array is already empty, then output a string "invalid" (without quote),otherwise you don't need to print anything for deleting numbers. For the operation type of 2, you have to output an integer, how many times x appears in the array from i to j inclusive.

      Example

      Input:
      7
      1 10
      1 20
      2 20 1 2
      0
      2 10 1 1
      0
      Output:
      1
      1
      invalid 

      Added by:Raihat Zaman Neloy
      Date:2014-08-12
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20674. Lov-e Pap Pap-e Polti

      Problem code: LPPP


      Little Jitu, Tipu and Vitu, three brothers, are probably very happy this Eid day. This is the day for getting eid-bonus more and more. No one wants to get less bonus amount than other. So, they only take the bonuses if all of them get same bonus amount from his father (in this case they are very happy), otherwise they will not take bonuses and hence this is the worst Eid day for them.

      Now their father has N coins, he has to distribute all these coins in such a fashion so that all of them get equal bonus.

      Now the task is yours!. Please tell their father if he will be able to distribute all N coins so that all of three gets equal bonus amount.

      Sample Input:

      The first line of the input is the integer T(T<=50) denoting the number of test cases. T lines follows. Each line contains N(1<=N<=50) space separated integers denoting the values of the ith coin which is between 1 to 50 inclusive.

      Sample Output:

      For each case of input, print the case number and “Happy Eid Day” if it is possible to give equal bonus amount, print “Lov-e Pap Pap-e Polti” otherwise.

      Sample Input:

      2

      10

      2 4 3 2 4 9 7 8 6 9

      3

      1 2 3

      Sample Output:

      Case 1: Happy Eid Day

      Case 2: Lov-e Pap Pap-e Polti

      Explanation:

      One Possible solution for  test case 1:

      Jitu will get bonus amount=2+7+9=18

      Tipu will get bonus amount=3+9+6=18

      Vitu will get bonus amount=4+2+4+8=18

      So all of them can get equal bonus amount.

      For test case test 2, there are no way to distribute coins so that all of them can get equal bonus amount.

       


      Added by:Md Abdul Alim
      Date:2014-08-13
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      20689. WA,RTE and Placements

      Problem code: WRP


      The Placement Season has started at the Aliens’ College of MachineLearning (ACM) and as expected, every alien of the college is burning the candle at both ends. William Archer(WA), the topper and the most eligible bachelor of ACM is however indifferent towards the situation. He has been spending all his time with his friend Rihanna-the Exuberant(RTE) and ignoring his studies. RTE, being the more mature and sensible of the two, devises a plan for WA so that he could spend adequate time with her without compromising his studies. Upon consultation with her best friend AC, she comes up with the following plan for WA: 

      1. She divides WA's next N hours into K sessions. 
      2. Each session can last for x hours where x is an integer and 1<=x<=M
      3. In each session, WA can either study or meet RTE
      4. If WA is studying in one session, he must meet RTE in the next session and vice versa. 
      5. WA must always study in the first session. 

      You have been hired by WA to calculate how many different timelines can RTE prepare for the next N hours. 

      Input

      The first line specifies the number of test cases T and the next T lines contain 3 integers each: N,K and M. 

      Output

      For every test case print a single integer which is the number of different ways RTE can prepare WA's timeline for the next N hours. Print your answer modulo 1000000007

      Constraints  

      T <= 100 
      1 <= N, K, M <= 100000 
      K<=N 

      Example

      Input:
      3
      4 3 2
      7 4 3
      1 1 1
      Output:
      3
      16
      1
      Pinku can prepare the following <i>three</i> schedules for the next 4 hours
      Explanation for Sample Input 1:
      RTE can prepare the following three schedules for the next 4 hours
      S|MM|S
      SS|M|S
      S|M|SS
      where S indicates that WA should be studying that hour 
      while M indicates that he should be meeting RTE that hour.
      Note that WA has to start with his studies always in order to satisfy Point 5 of the plan.
      
      <code>

      Added by:Utkarsh Raj
      Date:2014-08-14
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Based on UVA-10721 but with larger constraints









      SPOJ Problem Set (classical)

      20723. Mechajny

      Problem code: SUMXYZ


      Problem tekst ...

      Wej¶cie

      Opis wej¶cia ...

      Wyj¶cie

      Opis wyj¶cie ...

      Przyk³ad

      Wej¶cie:
      itp
      
      Wyj¶cie:
      itp
      

      Added by:Lidia Popielarz-Koz³owska
      Date:2014-08-21
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C++ 4.3.2 C++ 4.0.0-8
      Resource:Autorski









      SPOJ Problem Set (classical)

      20775. Roger and tree

      Problem code: RTREE


      Roger is a computer science student who likes connected undirected acyclic graphs, also known as trees. He especially likes solving problems about trees. Recently Roger found a piece of paper with a rooted tree with 'N' vertices drawn on it (numbered from 1 to 'N'). He also found 'Q' queries on the same piece of paper, where each query was an integer 'Sbetween 1 to 'N'. But the paper said nothing about the description of the queries. So he decided to find the longest path of each of the subtree 'S'.

      Roger spent two sleepless nights trying to solve this problem efficiently. He is still trying and won't sleep until he knows the answer to each query. Write a program which answers all the queries correctly.

       

      Input Format

      The first line of each test case contains an integer 'N', then N-1 lines follow.

      Each of the next 'N-1' line contains two integer 'U' and 'V' which means that vertex 'U' and 'V' are connected.

      Next line contains an integer 'R' which denotes the root of the tree.

      Next line contains another integer 'Q' which denotes the number of queries.

      Each of the next 'Q' line contains an integer 'S' between (1 to N).


      Output Format

      For each query print the longest path of the subtree 'S' rooted at vertex 'R'.

      Output exactly 'Q' lines, each line containing the output of the ith query.


      Roger is a computer science student who likes connected undirected acyclic graphs, also known as trees. He especially likes solving problems about trees. Recently Roger found a piece of paper with a rooted tree with 'N' vertices drawn on it (numbered from 1 to N). He also found 'Q' queries on the same piece of paper, where each query was an integer 'S' between 1 to 'N'. But the paper said nothing about the description of the queries. So he decided to find the diameter (longest path) of each of the subtree 'S'.
      Roger spent two sleepless nights trying to solve this problem efficiently. He is still trying and won't sleep until he knows the answer to each query. Write a program which answers all the queries correctly.
      Input Format
      The first line of each test case contains an integer 'N', then N-1 lines follow:
      Each of the next 'N-1' line contains two integer 'U' and 'V' which means that vertex 'U' and 'V' are connected.
      Next line contains an integer 'R' which denotes the ROOT of the tree.
      Next line contains another integer 'Q' which denotes the number of QUERIES.
      Each of the next 'Q' line contains an integer 'S' between (1 to N).
      Output Format
      For each query print the diameter of the subtree 'S' rooted at vertex 'R'.
      Output exactly 'Q' lines, each line containing the output of the ith query.

      Sample Input

      3

      1 2

      1 3

      1

      2

      1

      2


      Sample Output

      2

      0


      Constraints

      1 ≤ N ≤ 10^5

      1 ≤ U,V ≤ N

      1 ≤ R ≤ N

      1 ≤ Q ≤ 10^5

      1 ≤ S ≤ N


      Added by:Rana Saha
      Date:2014-08-26
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for codecracker









      SPOJ Problem Set (classical)

      20845. Interesting Numbers

      Problem code: INUM


      Jack and Jill went up the hill. Jack proposed Jill after reaching at the top of the hill. Jill gave Jack 'N' numbers and asked him to choose a pair of numbers such that their absolute difference is minimum. She also asked him to choose a pair of numbers such that their absolute difference is maximum. Jill wondered just finding maximum and minimum values is mainstream and it will be a cakewalk for Jack, instead she asked him to find number of pairs which have minimum absolute difference and number of pairs which have maximum absolute difference.

      Jill will accept Jack's proposal only if he can answer her question correctly. Jack does not know programming. Fortunately Jack had his laptop with him, fully charged and with good internet connection. He mailed you the numbers and asked you to mail him the answers back, as you are known to be a good programmer. Now it's your turn to help him.

      Input Format
      First line contains a positive integer 'N'.
      Next line contains 'N' non-negative integers 'a[i]' separated by a single space.

      Output Format
      Print the number of pairs having minimum and maximum difference separated by a single space.

      Constraints
      1 ≤ N ≤ 105
      0 ≤ a[i] ≤ 1015

      Sample Input
      5
      5 12 8 1 35

      Sample Output
      1 1

      Explanation
      It's optimal to choose the pair (5, 8) for the minimum difference.So only 1 pair.
      It's optimal to choose the pair (1,35) for the maximum difference. Here also only 1 pair.


      Added by:Aayush Agarwal
      Date:2014-08-30
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for codecracker , co-authored by Rana Saha









      SPOJ Problem Set (classical)

      20846. Interesting Selection

      Problem code: ISELECT


      There is a giant circular container which is divided into N segments numbered from 0 to N-1. 

      Each segment has two bottles, one is a bottle of cold-drink and other is a bottle of poision. Drinking from bottle of cold-drink increases your energy by A[i] while drinking from bottle of poision decreases your energy by B[i].

      The corresponding energies for the same are given in input.

      Now as it is circular, so bottles in segment N-1 and segment 0 are adjacent. If you do not drink from bottle of cold-drink, then you have to drink from bottle of poision in that segment. Furthermore you cannot drink from bottle of cold-drink in adjacent segments. You have to drink in such a way so that your energy maximizes. Find this maximum value.

      Note : Your initial energy will be 0 and the final maximum energy can be negative.

      Input Format
      There will be T test cases and in each test case there will be an integer N which is the size of the container.
      Next line contain N integers denoting the first array and the second line also contain N integers denoting the second array.

      Output Format
      There will be T lines each containing the output for each test case.

      Constraints
      1 ≤ T ≤ 10
      1 ≤ N ≤ 10000
      1 ≤ A[i],B[i] ≤ 109

      Sample Input
      1
      3
      1 2 3
      4 5 6

      Sample Output
      -6

      Explanation
      There are 3 segments and the pairs are (1,4), (2,5) ,(3,6)
      The optimal solution is to drink third potion and first two bottle of poision.
      The answer in this case is (-4 + - 5 + 3 ) = -6 


      Added by:Aayush Agarwal
      Date:2014-08-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for codecracker









      SPOJ Problem Set (classical)

      20848. Interesting Game

      Problem code: IGAME


      Alice and Bob play an interesting game and the game is played on a number.

      So a player, on his chance, can choose any non zero digit of the number and decrease the digit by any non zero amount such that the resulting digit remains non-negative. The player who gets all the digits of the number 0 wins. Both play optimally and Alice starts first. Now tell how many numbers are there between A and B on which if the game is played Alice wins and also find how many numbers are there where Bob wins. On every number between A and B, Alice plays first on that number .

      Input Format
      The Input line consists of T test cases. On each line there are two numbers A and B.

      Output Format
      The Output line consists of T lines each having two numbers.

      Constraints:
      1 ≤ T ≤ 10000
      1 ≤ A ≤ B ≤ 1018

      Sample Input
      2
      1 10
      101 110

      Sample Output
      10 0
      8 2

      Explanation
      In the first case the first player Alice will always win because she can reduce any digit to 0.
      In the second case the second player Bob will win on 2 numbers 101 and 110. Rest Alice will win.


      Added by:Aayush Agarwal
      Date:2014-08-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for codecracker









      SPOJ Problem Set (classical)

      20849. Interesting queries

      Problem code: IQUERY


      Students of Computer Science department at NIT Durgapur were becoming extremely bored and frustrated due to too many classes ( weird but we had many classes ). As semesters were approaching , students were preparing hard to get good grades. Everyone was nervous about the Algorithms exam which is going to be held 2 days later. To add to their discomfort, one question came in the exam which took many one by surprise. The question was simple but everyone was told to optimize code as much as possible.

      Now its your turn, and the question states that there is intially an array of N non-negative numbers (1-based indexing) and based on that array we have to run Q queries. Now we can do three things in each query. We have to sometimes calculate sum of product of all subsets of a number within a range, sometimes to calculate sum of Bitwise AND of all subsets of a number, sometimes to update an element of an array. All the calculations are to be performed modulus (109+7). If we have to do sum of products then the query is given 'M', if Bitwise AND then 'A' else if update then 'U'. For more details , see Explanation section .

      Note : Bitwise AND operator is defined as & in C ,C++ and in most of the languages. For other programming languages see your language documentation.

      Input Format
      First line contains N, which denotes the number of elements in an array. Next line contains N integers denoting the number of integers in the array. Then Q denoting the number of queries and after that each line consists of 3 integers. If it is 'M' then we have to do product, if 'A' then Bitwise AND and if 'U' then update. If it is 'M' or 'A' then it is followed by i and j which is the range of that array. If 'U' then we have the positon and the value to be updated at that position.

      Output Format
      Corresponding to each query we have an output only to query of 'M' and 'A'. For update you dont have to print anything.

      Constraints
      1 ≤ N ≤ 105
      1 ≤ A[i] ≤ 105
      1 ≤ Q ≤ 105
      1 ≤ i ≤ j ≤ 105
      The element to be updated is of maximum value of 105.

      Sample Input
      3
      1 2 3
      5
      M 1 3
      A 1 3
      U 2 5
      M 1 3
      A 1 3

      Sample Output
      23
      9
      47
      13

      Explanation
      For 1st query, we do 1 + 2 + 3 + 1*2 + 1*3 + 2*3 + 1*2*3 =23
      For 2nd query, it is 1 + 2 + 3 + 1&2 + 1&3 + 2&3 + 1&2&3 = 9
      For 3rd query, it is update so array becomes 1 5 3
      For 4th query, it is 1 + 5 + 3 + 1*5 + 1*3 + 3*5 + 1*3*5 = 47
      For 5th query, it is 1 + 5 + 3 + 1&5 + 1&3 + 3&5 + 1&3&5 = 13


      Added by:Aayush Agarwal
      Date:2014-08-30
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used for codecracker









      SPOJ Problem Set (classical)

      20863. Largest Submatrix

      Problem code: MINSUB


      You are given an matrix M (consisting of nonnegative integers) and an integer K.  For any submatrix of M' of M define min(M') to be the minimum value of all the entries of M'.  Now your task is simple:  find the maximum value of min(M') where M' is a submatrix of M of area at least K (where the area of a submatrix is equal to the number of rows times the number of columns it has).

      Input

      The first line contains a single integer T (T ≤ 10) denoting the number of test cases, T test cases follow.  Each test case starts with a line containing three integers, R (R ≤ 1000), C (C ≤ 1000) and K (K ≤ R * C) which represent the number of rows, columns of the matrix and the parameter K.  Then follow R lines each containing C nonnegative integers, representing the elements of the matrix M.  Each element of M is ≤ 10^9

      Output

      For each test case output two integers:  the maximum value of min(M'), where M' is a submatrix of M of area at least K, and the maximum area of a submatrix which attains the maximum value of min(M').  Output a single space between the two integers.

      Example

      Input:
      2
      2 2 2
      1 1
      1 1
      3 3 2
      1 2 3
      4 5 6
      7 8 9
      
      Output:
      1 4
      8 2

      Added by:acheron
      Date:2014-09-01
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Based on APIO 2014 Training Session









      SPOJ Problem Set (classical)

      20872. Counting Pairwise Coprime Triples

      Problem code: PCOPTRIP


      A tuple of three numbers ($a$, $b$, $c$) is called a pairwise coprime triple if $gcd(a, b) = 1$, $gcd(b, c) = 1$, and $gcd(c, a) = 1$.

      Let $C(n)$ be the number of pairwise coprime triples which satisfy $1 \le a, b, c \le n$.

      For example, $C(3)$= #{(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 3), (1, 3, 1), (1, 3, 2), (2, 1, 1), (2, 1, 3), (2, 3, 1), (3, 1, 1), (3, 1, 2), (3, 2, 1)} = 13.

      Your task is to find $C(N)$.

      Input

      First line of Input contains $T$ ($1 \le T \le 500$), the number of test cases.

      Next $T$ lines contain a single number $N$ ($1 \le N \le 100000$).

      It is guaranteed that $\sum  N \le 100000$ in each test case.

      Output

      For each number $N$, output a single line containing $C(N)$.

      Example

      Input:

      5
      1
      2
      3
      10
      100

      Output:

      1
      4
      13
      280
      282814

      Information

      There are 5 test cases.

      My C++ solution runs in 3.04 sec. (in the worst case)


      Added by:Min_25
      Date:2014-09-02
      Time limit:20s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20926. Special Numbers (Reverse and Add)

      Problem code: REVADD


      Michael likes to reverse and add numbers. When he finds a number, he reverses its digits and adds it to the original number. 

      One day, when he was doing "reverse and add", he found that some numbers (special numbers) can be obtained from two distinct digit numbers. The number 121 is one of them. He can get it from 47 (2-digit) and 110 (3-digit). He tried to find many of these special numbers, but he could find only two numbers under 10000.

      He wants to know the first 5,000 special numbers in ascending order. Can you help him ?

      Input

      This problem has no input data.

      Output

      Output the first 5,000 special numbers in ascending order. (One special number per one line.)

      Example

      Output:

      121
      1111
      ...
      [4998 lines]
      ...
      

      Information

      Source Limit is 10 KB.


      Added by:Min_25
      Date:2014-09-05
      Time limit:3s
      Source limit:10240B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      20930. Progression

      Problem code: EC_SER


      Let be S a infinite secuence of integers:

      S0 = a;
      S1 = b;
      Si = |Si-2 - Si-1| for all  i >= 2.

      You have two integers a and b. You must answer some queries about the n-th element in the secuence

      Input

      The first line contains a y b ( 0 <=  a,b  <= 10^18).

      The second line contains a integer q ( 1 <= q <= 100000 ).

      The third contains q integers qi.

      Output

      For each qi you must print a line with the qi-th elementh of S.

      Example

      Input:
      

      21 12

      5

      0 1 2 3 4 Output:

      21

      12

      9

      3

      6

      Note.- the values of qi are in the range of 64 bits


      Added by:Eddy Cael
      Date:2014-09-05
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:C C++ 4.3.2 C++ 4.0.0-8 JAVA
      Resource:Internas UTO 2014









      SPOJ Problem Set (classical)

      20951. Pebbles

      Problem code: SNIM


      Johny and Margaret are playing "pebbles". Initially there is a certain number of pebbles on a table, grouped in  piles. The piles are next to each other, forming a single row. The arrangement of stones satisfies an additional property that each pile consists of at least as many pebbles as the one to the left (with the obvious exception of the leftmost pile). The players alternately remove any number of pebbles from a single pile of their choice. They have to take care, though, not to make any pile smaller than the one left to it. In other words, the piles have to satisfy the initial property after the move as well. When one of the players cannot make a move (i.e. before his move there are no more pebbles on the table), he loses. Johny always starts, to compensate for Margaret's mastery in this game.

      In fact Margaret is so good that she always makes the best move, and wins the game whenever she has a chance. Therefore Johny asks your help - he would like to know if he stands a chance of beating Margaret with a particular initial arrangement. Write a programme that determines answers to Johny's inquiries.

      Input

      In the first line of the standard input there is a single integer  () denoting the number of initial pebble arrangements to analyse. The following  lines contain descriptions of these arrangements; each one takes exactly two lines.

      The first line of each description contains a single integer  - the number of piles. The second line of description holds  non-negative integers separated by single spaces and denoting the numbers of pebbles in successive piles, left to right. These numbers satisfy the following inequality . The total number of pebbles in any arrangement does not exceed .

      Output

      Precisely  lines should be printed out on the standard output. The -th of these lines (for ) should hold the word TAK (yes in Polish), if Johny can win starting with the -th initial arrangement given in the input, or the word NIE (no in Polish), if Johny is bound to lose that game, assuming optimal play of Margaret.

      Example

      Input:
      
      2
      2
      2 2
      3
      1 2 4
      Output:
      NIE
      TAK

      Added by:acheron
      Date:2014-09-08
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Polish Olympiad in Informatics









      SPOJ Problem Set (classical)

      20957. Alia and 3 Khans

      Problem code: KHANS


      3 KHANS of Bollywood are planning to work together in a film called "Three_Khans". Aamir (being perfect :P) wants the Alia to be a main lead. But Alia (being very famous :P) is confused that whether to work in a film or not. So they all have decided to play a game called "Filmy_Sequence".

      According to this game, Aamir will give any number to Alia to play with it. Alia has to find two other numbers using it. That two numbers represent Stardom of Salman and Srk. These two numbers shoud be found in such a way so that both numbers will have same number of set ('1') bits in their binary representation as Aamir's number contains. One thing is also need to be checked that Salman's number should be just next greater number to Aamir's number and Srk's number should be just next smaller number to Aamir's number (i.e in a order of their Stardom :P). They all have decided that if this "Filmy_Sequence" forms a G.P (Geometric Progression) then Alia has to be in the favour of movie else not. Alia needs your help to find the probabilty that she will work in a film and she also wants to find the mean of the Stardum of Salman over Srk.

      Note : All the three numbers should be positive and in a range upto 32 bits, and if not possible assume -1. (i.e if particular number is not possible with respect to Aamir's number, assume it as -1)

      Input Format :

      first line will have a number of numbers that Aamir will give (t) next t lines will have Aamir's number (n)

      Output Format :

      print the asked probability and mean. Any results within 10^-6 absolute error will be accepted.

      Constraints :

      t <= 1000000

      0 <= n <= 1000000

      Sample Input 1:

      3

      1

      2

      3

      Sample Output 1:

      0.333333 4.000000

      Sample Input 2 :

      2

      5

      6

      Sample Output 2 :

      0.000000 3.500000

      Explanation :

      Case 2 : 5 -> 3,5,6 and 6-> 5,6,9 are the required numbers.


      Added by:pranjuldb
      Date:2014-09-08
      Time limit:0.899s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:ADA BF C C# C++ 4.3.2 C++ 4.0.0-8 C99 strict LISP sbcl LISP clisp F# HASK JAVA JS PERL PERL 6 PHP PRLG PYTH 2.7 PYTH 3.2.3 PYTH 3.2.3 n
      Resource:Own problem from Codehurdle









      SPOJ Problem Set (classical)

      20970. Alia and Handsome Devil

      Problem code: HDEVIL


      Alia has been assigned a homework by her maths teacher to find the "Handsome" numbers. She is confused about these numbers, as we all know that she is very "intelligent" :P

      So she needs your help. Following is an exact line that her teacher has given about Handsome numbers : "Handsome number can be defined as a number such that sum of all the proper divisors of handsome number with modulus to m, has to be a devil number. This Devil number is a number whose total number of proper divisors , is a Fibonacci number (0,1,1,2,3,5....)."

      Note : Alia's lucky number is 1, so she assumes 1 as a proper divisor always :P

      Input Format :

      First line of input is t (no. of test cases) then next each t lines will contain two integers n (no. that is to be checked), m.

      Output Format :

      Print in a each output line Case no. and "YES." if a number is a handsome number otherwise "NO.". (with a dot)

              Case_#i_:_YES.
              Case_#j_:_NO.
      

      Here, '_' refers to a single space.

      Constraints :

      t <= 100

      2 <= n <= 10^9

      1 <= m <= 10^8

      Sample Input :

      2

      6 5

      100 45

      Sample Output :

      Case #1 : YES.

      Case #2 : YES.

      Explanation :

      Case #1 : proper divisors of 6 are 1, 2, 3 i.e sum = 6 , taking mod with 5, i.e 1. Now no. of proper divisors of 1 is a Fibonacci number.


      Added by:pranjuldb
      Date:2014-09-09
      Time limit:0.019s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem from Codehurdle









      SPOJ Problem Set (classical)

      20971. Alia and Substrings

      Problem code: HAGU


      Alia wants to play with you. She will give you a string (MSG) where ((N = length of MSG) <= 10000)and multiple queries(M). Each query consists of an integer value K.

      For each query you have to find the Kth substring if all the substrings of the given string are arranged in lexicographically increasing order without any duplicates( no substring will appear twice in the given arrangement). You have to output the starting index of the Kth substring and it's size. If the found substring has duplicates then(substring occurs multiple times in the given string), output the smallest index where it occurs.

      If the no. of substring in the arrangement is less than the value of K, output -1.

      Constraints:

      1 <= size of string(MSG) <= 10000

      1 <= No of queries (M) <= 100000

      1 <= K <= total number of substrings (not necessarily unique) of MSG;

      Note : you have to output indexes as 1-based.

      input:

      The first line of input will consist of your string and no of queries(M), seperated by a space. Next M lines will consist of integer K (as mentioned in the problem).

      output:

      Your output should consist of M lines as per the answer for each query.

      Sample input:

      aaaaa 3

      1

      2

      3

      Sample output :

      1 1

      1 2

      1 3

      Explanation:

      Our arrangement here will consist of substrings in the following order (a),(aa),(aaa),(aaaa),(aaaaa)

      So 1st substring will be "a" and it's occuring at multiple index - (1,2,3,4,5) out of which the smallest index is 1 and it's size is 1. Hence the answer will be (1,1).

      The same will be for the other two queries.


      Added by:pranjuldb
      Date:2014-09-09
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Codehurdle









      SPOJ Problem Set (classical)

      20972. Alia and Cryptography

      Problem code: CONOR


      Alia is world’s most widely acclaimed cryptographer. Recently she developed a new way to encrypt passwords over the internet. Instead of using the secret “Key”, now she intends to use a secret “Key Matrix” for encryption.

      The “Key Matrix” consists of an integer matrix of dimensions m * n. Besides, there are four coordinates x1, y1, x2, y2. The “Key” can be retrieved from “Key Matrix” performing bitwise XOR(^) operation over all the integers present in rectangle having its upper left corner as (x1, y1) and lower right index as (x2, y2). (Note: the matrix is 0 based) Also Alia has developed new tools to regularly update his key to protect it from “attackers”. So she will update the values of some cells from time to time. You friend, being an expert hacker has finally retrieve the “Key Matrix” . Now he only needs to use the matrix to retrieve the key. Since this appears to be a tedious task, he turns to you. Help your friend by retrieving the secret “key” from the “key matrix”.

      In brief, you’ll have to do the following two operations over the matrix

      0 x1 y1 x2 y2 : Perform the XOR of all the integers present in the rectangle having its upper left corner as (x1, y1) and lower right index as (x2, y2).

      1 x1 y1 k: Update the value at position (x1, y1) by k.

      Input:

      The first line of input will contain integers m and n (separated with space) specifying the dimensions of the matrix. This is followed by a m * n matrix (m rows and n columns) denoting the “Key Matrix”. The next line contains an integer q denoting the number of queries. Each of the following q lines contains a single query in the specified format.

      Output:

      For each query, print the value of the secret “Key” that you retrieve from the “Key Matrix”

      Constraints

      1 <= m, n < 600

      1 <= q <= 20,000

      0 <= x1, x2 <= m – 1

      0 <= y1, y2 <= n – 1

      0 <= Aij, k <= 10^8

      Sample Input:

      2 2

      1 2

      3 4

      2

      1 0 0 2

      0 0 0 1 1

      Sample Ouptut:

      7

      Explanation

      The first query updates the value of (0, 0) to 2. Now the Key matrix appears like 2 2 3 4 Now for query 2 the secret key is the XOR of the value in the entire matrix So the key is 2 ^ 2 ^ 3 ^ 4 = 7


      Added by:pranjuldb
      Date:2014-09-09
      Time limit:0.300s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Codehurdle









      SPOJ Problem Set (classical)

      20976. Sum

      Problem code: UCBINTA


       

      Once upon a time, there existed a sequence A consisting of N positive integers. You don't know the
      sequence itself, but you do know the sum of every two elements of the sequence. Find the sequence A!

      Once upon a time, there existed a sequence A consisting of N positive integers. You don't know the

      sequence itself, but you do know the sum of every two elements of the sequence. Find the sequence A!

       

      Input

      The first line of input contains the positive integer N (2 ≤ N ≤ 1000). Each of the following N lines

      contains N positive integers smaller than or equal to 100000, forming the table S. The following relations

      hold: S(i, j) = A[i] + A[j] for i ≠ j, and S(i, j) = 0 for i = j. Here S(i, j) denotes the number in the

      ith row and jth column of the table, and A[i] denotes the ith element of the sequence A. It is guaranteed

      that for any input data set there exists a unique sequence of positive integers A with the given properties.

      Output

      The fi rst and only line of output must contain the required sequence A (in the form of N space separated

      positive integers).

      Example

      Input:
      2
      0 2
      2 0
      Output:
      1 1
      Input:
      4
      0 3 6 7
      3 0 5 6
      6 5 0 9
      7 6 9 0
      Output:
      2 1 4 5

      Added by:Gabriel Menacho
      Date:2014-09-09
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:http://www.soj.me/9562









      SPOJ Problem Set (classical)

      21049. Under Construction Forever

      Problem code: UCF


       

      UCF is now the nation’s second largest university in student population.  To meet the demands 
      of a growing student body, the university is always constructing new buildings.  One of the 
      issues is the campus needs many new buildings but has limited space.  To help make room for 
      new buildings, a new restructuring method is being used!
      Each day (until the end of restructuring) a building is selected for “reconstruction”. During 
      reconstruction, all buildings that are connected to the selected building and only to the selected 
      building are combined into (torn down and then added as new parts to) the selected building. 
      Every building has a given cost associated with applying this reconstruction operation; when a 
      building is selected and other buildings are combined with it, the cost associated with the 
      selected building is the cost for combining the selected group of buildings.
      For example, in the building layout below, the building with cost 5 is selected in Day 1. The 
      building with cost 1 (crossed out in the picture in Day 1) is the only building connected to the 
      selected building and this building is connected to no other building. These two buildings are 
      combined and the cost of the operation is 5 (the cost of the selected building). In Day 2, the 
      building with cost 4 is selected (hence the cost 4 for combining) and in Day 3, the building with 
      cost 6 is selected. No more buildings can be selected after Day 3 since every building is 
      connected to more than one building. The total cost for this sequence of combinations is 
      therefore 5+4+6= 15.

      UCF is now the nation’s second largest university in student population.  To meet the demands

      of a growing student body, the university is always constructing new buildings.  One of the

      issues is the campus needs many new buildings but has limited space.  To help make room for

      new buildings, a new restructuring method is being used!

      Each day (until the end of restructuring) a building is selected for “reconstruction”. During

      reconstruction, all buildings that are connected to the selected building and only to the selected

      building are combined into (torn down and then added as new parts to) the selected building.

      Every building has a given cost associated with applying this reconstruction operation; when a

      building is selected and other buildings are combined with it, the cost associated with the

      selected building is the cost for combining the selected group of buildings.

      For example, in the building layout below, the building with cost 5 is selected in Day 1. The

      building with cost 1 (crossed out in the picture in Day 1) is the only building connected to the

      selected building and this building is connected to no other building. These two buildings are

      combined and the cost of the operation is 5 (the cost of the selected building). In Day 2, the

      building with cost 4 is selected (hence the cost 4 for combining) and in Day 3, the building with

      cost 6 is selected. No more buildings can be selected after Day 3 since every building is

      connected to more than one building. The total cost for this sequence of combinations is 

      therefore 5+4+6= 15.

       

      The Problem:

       

      Given the building connections and the costs associated with refactoring the buildings, determine 

      the minimum possible number of buildings that will be left when refactoring is complete, the 

      minimum cost of achieving this minimum size and the number of ways to achieve this minimum 

      cost with minimum size.  Two ways are considered different if on the i-th day the building being 

      reconstructed is different or the number of days to complete the reconstruction differs.  Since the 

      number of ways to reconstruct the university can be quite large, print the result modulo

      1,000,000,007. 

       

       

       

      Input

      The first input line contains a positive integer, n, indicating the number of restructurings to 

      perform.  Each restructuring will contain multiple lines. The first line contains two integers,

      b (1 ≤ b ≤ 500) and c (1 ≤ c ≤ 2000), representing (respectively) the number of buildings and the 

      number of connections between them.  The next line contains b integers, wi (1 ≤ wi ≤ 500), 

      representing the cost of performing a reconstruction on the i-th selected building.  The next c lines 

      each contain two integers, xi and yi (1 ≤ xi ≤ b, 1 ≤  yi ≤ b, xi ≠ yi), representing two identifiers for buildings that connect.  There will be at most one direct connection between any two buildings.

      Also, every pair of buildings will be directly or indirectly connected.

      Output

      For each restructuring, first output the heading “Case #d: ”, where d is the test case number, 

      starting with 1.  Then, print three integers separated by a single space: the minimum number of 

      buildings left, the minimum cost for achieving this configuration, and the number of ways to 

      achieve the minimum cost with minimum size. Follow the format illustrated in Sample Output.

      Example

      Input:
      3
      3 2
      1 2 3
      3 1
      3 2
      8 7
      80 4 3 2 1 90 5 80
      1 2
      2 3
      3 4
      4 5
      5 6
      4 7
      7 8
      8 8
      1 5 6 1 1 4 1 9
      1 2
      2 3
      3 4
      4 2
      3 6
      6 7
      6 5
      6 8
      
      Output:
      Case #1: 1 3 1
      Case #2: 1 15 28
      Case #3: 3 15 3
      

      Added by:Mew.
      Date:2014-09-15
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LPC UCF 2014









      SPOJ Problem Set (classical)

      21057. Super Lucky Palindromes

      Problem code: CTPLUCKY


       

      Lucky numbers are positive integers composed only of the digits ‘4’ and ‘7’.  For example, 
      47477 and 777 are lucky numbers while 457 and 1232 are not.
      Super lucky numbers have the following additional properties:
      •  They are a lucky number themselves
      •  Number of digits in them is a lucky number
      •  The number of ‘4’s or the number of ‘7’s in them is a lucky number (or both counts are 
      lucky numbers).
      A palindrome is an integer that reads the same forwards and backwards.  For example, 547745
      and 343 are palindromes while 74 and 12345 are not.  A super lucky palindrome is a positive 
      integer that is both a super lucky number and a palindrome.
      The Problem:
      Given a number k, print the k
      th
      smallest super lucky palindrome.

      Lucky numbers are positive integers composed only of the digits ‘4’ and ‘7’.  For example, 

      47477 and 777 are lucky numbers while 457 and 1232 are not.

      Super lucky numbers have the following additional properties:

      •  They are a lucky number themselves

      •  Number of digits in them is a lucky number

      •  The number of ‘4’s or the number of ‘7’s in them is a lucky number (or both counts are 

      lucky numbers).

      A palindrome is an integer that reads the same forwards and backwards.  For example, 547745

      and 343 are palindromes while 74 and 12345 are not.  A super lucky palindrome is a positive 

      integer that is both a super lucky number and a palindrome.

      The Problem:

      Given a number k, print the k-th smallest super lucky palindrome.

       

      Input

      The first input line contains a positive integer, n, indicating the quantity of numbers to check. 

      Each of the next n lines contains a single integer, k (1 ≤ k ≤ 10^18).

      Output

      For each query, first output the heading “Query #d: ”, where d is the query number, starting with 1.

      Then, for the value k given in the query, print the k-th smallest super lucky palindrome.

      Follow the format illustrated in Sample Output.

      Example

      Input:
      5
      1
      2
      3
      5
      100
      
      Output:
      Query #1: 4444
      Query #2: 7777
      Query #3: 4444444
      Query #4: 4747474
      Query #5: 44444444744744444444444444444444744744444444
      

      Added by:Mew.
      Date:2014-09-16
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:LPC UCF 2014









      SPOJ Problem Set (classical)

      21058. Dirty Plates

      Problem code: CTPDIRTY


       

      Lazy Louie loves to eat but he adamantly hates cleaning.  That is why he has chosen to delay 
      cleaning for as long as possible.  Being an avid inventor, Louie created an invention to help 
      increase his laziness.  That invention is the two sided plate!  Two sided plates can be stacked like 
      coins for easy storage.  They also have the interesting feature that you may eat from either side 
      of the plate.

      Lazy Louie loves to eat but he adamantly hates cleaning.  That is why he has chosen to delay 

      cleaning for as long as possible.  Being an avid inventor, Louie created an invention to help 

      increase his laziness.  That invention is the two sided plate!  Two sided plates can be stacked like 

      coins for easy storage.  They also have the interesting feature that you may eat from either side 

      of the plate.

       

      Lazy Louie lacks cabinet space.  That is why he stores his two sided plates directly on his dining 

      table.  When enjoying a meal he simply eats off the topmost plate, although he will only eat off 

      the topmost surface if it is clean.  When the plates are stacked, if a dirty side of the plate touches 

      the clean side of another plate then the grime of that plate transfers to the clean plate making that 

      side of the plate dirty.  The side that was originally dirty stays dirty.

       

      Since Louie is stacking plates on his table, if a dirty side of a plate touches the table then the 

      grime will transfer to the table making the table dirty.  If the table is dirty already and it touches 

      a clean side of a plate then that plate’s side becomes dirty.  Note that the table remains dirty. 

      Also, both sides remain dirty when two dirty sides, either the table or plates, touch.

       

      The Problem:

      Louie would like to know the maximum number of meals that can be eaten before any cleaning 

      is done.  Louie is given the number of plates he already has of three kinds: plates that are clean 

      on both sides, plates that are clean on one side while dirty on the other, and plates that are dirty 

      on both sides.  Before eating his first meal he can stack these plates in any way he likes on the 

      table.  After eating each meal the topmost plate becomes dirty.  Between meals Louie can 

      rearrange the plates in any way he likes.  Louie is allowed to change the order of the plates on 

      the stack and change which side is facing up but they must remain a stack of plates after being 

      rearranged.

       

      Input

      The first input line contains a positive integer, n, indicating the number of eating scenarios to 

      analyze.  The next n lines contain the description of the plates.  Each line contains three integers, 

      c, s, and d, (0 ≤ c ≤ 100; 0 ≤ s ≤ 100; 0 ≤ d ≤ 100) representing (respectively) the number of 

      plates with both sides clean, the number of plates with one side clean and the number of 

      completely dirty plates.

      Output

      For each scenario, first output the heading “Scenario #d: ”, where d is the scenario number, 

      starting with 1. Then, print the maximum number of times a meal can be eaten before Louie has 

      to clean. Follow the format illustrated in Sample Output.

      Example

      Input:
      4
      1 0 0
      2 0 0
      1 1 3
      2 2 2
      
      Output:
      Scenario #1: 2
      Scenario #2: 3
      Scenario #3: 2
      Scenario #4: 4
      

      Added by:Mew.
      Date:2014-09-16
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      21061. Yet Another Subset Sum Problem

      Problem code: YASSP


      Let Y be an array of integers of size N
      Let G(x) be a set comprising of the size of all the subsets of the array Y whose sum is x
      Let F(G(x)) denote the number of unique elements in the set G(x)

      Your task is to find the maximum value of F(G(x)) and the corresponding value x for the given array Y. 
      In Case, many 'x' correspond to maximum F(G(x)), print the smallest one

      Input

      The first line describes the number of test cases T. 
      The input contains several test cases, each one described in exactly two lines. 
      The first line contains an integer N indicating the number of elements in the array. 
      The second line contains N integers separated by single spaces, representing the elements of the array.

      Output

      For every test case, print two integers: maximum F(G(x)) and the minimum value of x corresponding to it.

      Constraints 
      T<=50 
      1<=N<=50 
      1<=Y[i]<=1000  

      Example

      Input:
      

      1 2 3 4 

      3 2 3 4 5 3  Output: 2 3 
      2 5 
      Explanation 
      For test Case 1
      G(1) : {1} and F(G(1)) : 1. 
      G(2) : {1} and F(G(2)) : 1. 
      G(3) : {1,2} and F(G(3)) : 2. 
      G(4) : {1,2} and F(G(4)) : 2. 
      G(5) : {2,2} and F(G(5)) : 1. 
      G(6) : {2,3} and F(G(6)) : 2. 
      G(7) : {2,3} and F(G(7)) : 2. 
      G(8) : {3} and F(G(8)) : 1. 
      G(9) : {3} and F(G(9)) : 1. 
      G(10): {4} and F(G(10)) : 1. 

      Added by:Utkarsh Raj
      Date:2014-09-16
      Time limit:1s-3s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own Problem









      SPOJ Problem Set (classical)

      21079. The Resistance

      Problem code: RESSTNCE


      A resistor is a passive two-terminal electrical component that implements electrical resistance as a circuit element. Resistors act to reduce current flow, and, at the same time, act to lower voltage levels within circuits. When multiple resistors are connected to each other in a circuit, the net resistance depends on how they are connected. The total resistance of resistors connected in series is the sum of their individual resistance values.

      A diagram of several resistors, connected end to end, with the same amount of current going through each

       R_\mathrm{eq} = R_1  + R_2 + \cdots + R_n.

      The total resistance of resistors connected in parallel is the reciprocal of the sum of the reciprocals of the individual resistors.

      A diagram of several resistors, side by side, both leads of each connected to the same wires

       \frac{1}{R_\mathrm{eq}} = \frac{1}{R_1} + \frac{1}{R_2} + \cdots +  \frac{1}{R_n}.

      In this problem, we are constructing a long network of resistors composed of N blocks. Every block has two 1 ohm resistors, shown below by the upper-left figure. We would like for you to measure the net resistance across the two leftmost terminals in a circuit with N blocks. If the circuit has one block (N=1), then the net resistance across the leftmost terminals is 1 ohm, because the horizontal resistor is not in a path connecting the leftmost terminals. Similarly, for a circuit with two blocks (N=2), the net resistance is 2/3 ohms. The figures below illustrate this.

      Find the resistance A/B of the circuit composed of N blocks. Since these values can be enormous, reduce the fraction A/B to lowest terms P/Q (i.e., gcd(P,Q) = 1), and then print (P mod M)/(Q mod M), where M is the given modulus.

      Input

      The first line contains T test cases. Each of the next T lines contains two integers N and M.

      Output

      For each test case, print on its own line the numerator and denominator of the net resistance across the leftmost terminals in lowest terms modulo M, seperated by only the '/' character.

      Constraints

      • 1 ≤ T ≤ 10
      • 1 ≤ N ≤ 106
      • 1 ≤ M ≤ 109

      Example

      Input:
      4
      1 1000000
      2 100
      2 2
      50 1000
      Output:
      1/1
      2/3
      0/1
      26/75

       


      Added by:Matthew Fahrbach
      Date:2014-09-20
      Time limit:10s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      21092. DRAW TABLE

      Problem code: FRMT


      given the elements of the table ... draw the table :D

      INPUT 

      The input consists of one or more table descriptions, followed by a line whose first character is '*', which signals the end of the file. Each description begins with a header line containing one or more characters that define the number and alignment of columns in the table. Each character in the header line is either '<', '=', or '>', and indicates a left-justified, centered, or right-justified column. Following the header are at least two and at most 21 data lines that contain the entries for each row. Each data line consists of one or more nonempty entries separated by an ampersand ('&'), where the number of entries is equal to the number of columns defined in the header line. The first data line contains entries for the column titles, and the remaining data lines contain entries for the body of the table. Spaces may appear within an entry, but never at the beginning or end of an entry. The characters '<', '=', '>', '&', and '*' will not appear in the input except where indicated above.

      OUTPUT 

      For each table description, output the table using the exact format shown in the examples. Note that

      • The total width of the table will never exceed 79 characters (not counting end-of-line).
      • Dashes ('-') are used to draw horizontal lines, not underscores ('_'). 'At' signs ('@') appear at each of the four outer corners. Plus signs ('+') appear at intersections within the line separating the title from the body.
      • The largest entry in a column is always separated from the enclosing bars ('|') by exactly one space.
      • If a centered entry cannot be exactly centered within a column, the extra space goes on the right of the entry.

      Input and correct output files satisfy all the requirements listed in Notes to Teamsexcept that the output may contain two or more consecutive spaces. There are no spaces at the beginning or end of lines, and only spaces are used (never tabs).

       

      SAMPLE INPUT: 

      <>=>
      TITLE&VERSION&OPERATING SYSTEM&PRICE
      Slug Farm&2.0&FreeBSD&49.99
      Figs of Doom&1.7&Linux&9.98
      Smiley Goes to Happy Town&11.0&Windows&129.25
      Wheelbarrow Motocross&1.0&BeOS&34.97
      >
      What is the answer?
      42
      <>
      Tweedledum&Tweedledee
      "Knock, knock."&"Who's there?"
      "Boo."&"Boo who?"
      "Don't cry, it's only me."&(groan)
      *

      SAMPLE OUTPUT: 

       

      @-----------------------------------------------------------------@
      | TITLE                     | VERSION | OPERATING SYSTEM |  PRICE |
      |---------------------------+---------+------------------+--------|
      | Slug Farm                 |     2.0 |     FreeBSD      |  49.99 |
      | Figs of Doom              |     1.7 |      Linux       |   9.98 |
      | Smiley Goes to Happy Town |    11.0 |     Windows      | 129.25 |
      | Wheelbarrow Motocross     |     1.0 |       BeOS       |  34.97 |
      @-----------------------------------------------------------------@
      @---------------------@
      | What is the answer? |
      |---------------------|
      |                  42 |
      @---------------------@
      @---------------------------------------------@
      | Tweedledum                 |     Tweedledee |
      |----------------------------+----------------|
      | "Knock, knock."            | "Who's there?" |
      | "Boo."                     |     "Boo who?" |
      | "Don't cry, it's only me." |        (groan) |
      @---------------------------------------------@

      Added by:is_jas
      Date:2014-09-21
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:North America Regional









      SPOJ Problem Set (classical)

      21096. Word Counting 2

      Problem code: WORDCNT2


      “I have hated words and I have loved them, and I hope I have made them right.” ― Markus Zusak

      We also love words, don’t we? However, we are code poets, so, we love words in a different way. How about counting them? Yes, counting word seems to be a good thing and has a huge application in computer science. Well, counting may sometimes sound boring, but many hidden knowledge can be achieved from counting. For example, finding the most frequent word in vast collection of documents, which then in turns, can be used to classify those documents.

      But fear not! We are not interested in large documents right now. In fact, in our extremely busy world, offline data processing algorithms are getting obsolete day by day. Instead of words in large files, we are now more interested in streams of words.

      The idea is quite simple, your program will keep reading from a stream where new words are continuously being fed to your program, but due to limited storage, your program can only remember the latest K words. So, when (K+1)th word arrives, your program forgets the 1st word, when (k+2)th word arrives, your program forgets the 2nd word, and so on.

      We want you to find the most frequent word over the latest K words each time a new word arrives.

      Input Format

      The first line of input will contain an integer T, which denotes the number of test cases. First line of each test case will contain two integers N and K, where N is the total number of words to be read, and K is the number of words that your program can remember. Each of the following N lines will contain a single word composed with only lowercase characters ‘a’ to ‘z’, at most 8 characters long.

      Output Format

      For each case, first print the case number, then for each of the words, print the most frequent word that appears within the last K words along with the frequency. If there are less than K words, then print the most frequent word among all of them. In case there is a tie, print the alphabetically smaller word. See sample input and output sections for more details.

      Constraints

      1 ≤ T ≤ 20

      1 ≤ K ≤ N ≤ 105

      1 ≤ word-length ≤ 8

      Sample Input

      1
      8 3
      hello
      hi
      who
      hi
      hi
      hello
      who
      when
      

      Sample Output

      Case 1:
      hello 1
      hello 1
      hello 1
      hi 2
      hi 2
      hi 2
      hello 1
      hello 1
      

      Explanation

      The following table shows a simulation of the program for the entry of each new word. Note, once the capacity of the program is full, i.e. equals to K, the program will start forgetting the oldest entry for each new entry. In other words, those words will not be taken into consideration anymore.

      # New word in stream Words remembered by the program Most frequent word (Count)
      1 hello hello hello (1)
      2 hi hello, hi hello (1)
      3 who hello, hi, who hello (1)
      4 hi hi, who, hi hi (2)
      5 hi who, hi, hi hi (2)
      6 hello hi, hi, hello hi (2)
      7 who hi, hello, who hello (1)
      8 when hello, who, when hello (1)



      Added by:যোবায়ের
      Date:2014-09-22
      Time limit:2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Own problem used in CUET IUPC 2014, Chittagong Divisional.









      SPOJ Problem Set (classical)

      21104. Jarin Loves New Task

      Problem code: JLNT


       

      Jarin has got a new task. She has to connect towers by wire.

      Given

      1. Number of towers N (2<=N<=1000)
      2. The length of wire L (0<=L<=5000).
      3. Coordinates of each tower in 1D starting from left to right and each coordinate will be a positive distinct integer not exceeding 5000.

      Her task is to maximize the number of connected towers using that wire. But she has to make sure each tower is either connected with its left tower or its right tower or have no connection. She has to cut off the wire into particular sizes she wants to use.

       

      It so difficult task for her. So you must have to help her :) . 

      Input

      Input starts with an integer T (≤ 100), denoting the number of test cases.

      Each case starts with two integers N and L .  Next line contains N space separated integers.

      Output

      For each case, print the case number and expected answer.

      Sample Input

      Output for Sample Input

      1

      6 2

      1 2 3 4 5 6

      Case 1: 4

       

      Problem Setter: Ajharul Islam Barid

      Special Thanks: Abu Zafar Newton.


      Added by:Ajharul Islam Barid
      Date:2014-09-24
      Time limit:0.5s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All









      SPOJ Problem Set (classical)

      21132. Palindromes

      Problem code: APIO14_A


      You are given a string of lower-case Latin letters. Let us define substring’s “occurrence value” as the number of the substring occurrences in the string multiplied by the length of the substring. For a given string find the largest occurrence value of palindromic substrings.

      Input

      The only line of input contains a non-empty string S of lower-case Latin letters (a-z), |S| <= 300,000.

      Output

      Output one integer – the largest occurrence value of palindromic substrings.

      Example

      Input:
      abacaba
      
      Output:
      7
      

      Added by:Hussain Kara Fallah
      Date:2014-09-25
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:APIO 2014









      SPOJ Problem Set (classical)

      21135. Distinct Viewpoints

      Problem code: BFCC


      The citizens of Palinopolis are very fond of arguments. Whenever two Palinopolitans meet up, whether it be to negotiate over territorial boundaries or buy a pet, custom requires them to take up contrary positions and argue for at least five minutes, then finally depart in frustrated disagreement. The most gifted arguers often pursue careers at prestigious argument firms, but in order to secure a job they must first survive a stringent regime of exams followed by a highly competitive hiring process. In the first round of hiring, each applicant must face off against the head of the firm for ten hours without agreeing on a single point. In the second round, the remaining applicants face each other. These applicants are conveniently numbered from 1 to N, and a topic is chosen that allows N mutually opposing viewpoints V1, V2, ..., VN to be assigned to them respectively. Next, pairs of applicants are successively chosen and locked in a small, humid room to argue their respective viewpoints until one of them becomes conciliatory, gives up, or passes out. The loser is not eliminated outright but must take on the viewpoint of the victor in subsequent matches. Additionally, anyone else who is currently assigned the losing opponent's viewpoint must change his viewpoint to the victor's. It may happen that some pairs are chosen such that each opponent represents the same viewpoint. This is in fact no problem at all, since any Palinopolitan worth his salt is perfectly capable of conducting a heated argument with someone who is expressing the exact same views. No applicant is ever asked to argue against himself, however, as that would just be silly.

      The final selection of applicants is based on many complex factors, including percentage of matches won, number of hours passed out, and whether or not the judge has had a good lunch that day. As a member of the oversight committee, part of your job is to analyse the matches and provide relevant figures and statistics to your superiors. One crucial bit of information (according to your boss) is how many viewpoints survived the process, and which groups of applicants share the same assigned viewpoint. This would normally be quite an easy task for you to solve, except that today your boss is in a bad mood and would like to punish you by making you solve it in a strange, primitive programming language that he just read about on the internet when he was supposed to be working.

      Note: You can use any programming language you want, as long as it is brainf**k.

      Input

      First an integer T (1 ≤ T ≤ 1000), followed by T tests. Each test starts with two integers N (1 ≤ N ≤ 50) and M on a line, the number of applicants and the number of matches respectively. Then in the following M lines are given pairs of integers u and v in the range [1..N], indicating that applicants u and v face each other in a match. Finally, every case (including the last) ends with a blank line.

      Output

      For each case, first print out K, the number of distinct viewpoints surviving at the end of all matches, and then print out each group of applicants sharing a common viewpoint. Each group must be sorted internally, and the groups must also be sorted with respect to each other, using the usual definitions for sorting lists (lexicographically).

      Example

      Input:

      2
      3 1
      2 3
      
      9 7
      4 1
      8 2
      4 6
      5 1
      5 7
      6 1
      5 6
      
      

      Output:

      2
      1
      2 3
      4
      1 4 5 6 7
      2 8
      3
      9
      

      Additional Info

      The input is generated as follows: N is chosen uniform randomly in the range, then K is chosen uniform randomly in [1..N] and a minimal number of edges is chosen randomly to yield K, then the extra edges (that do not change K) are chosen randomly with probability p, where p is uniform random in [0,1]. Duplicate edges do not appear.

      There are two data sets, one with T=1000 and the other with T=500. My solution at the time of publication has 1192 bytes (not golfed) and runs in 9.37s with 2.3M memory footprint.

      The custom judge reports your source code length in parentheses after the judge result (when available at the time of judge termination). Only valid BF commands are counted. Also, if you don't get AC, you will be told on which data set you first failed (0-indexed). (The master judge is the same as BFPRMCYC, and the test case judge is the same as BFBINADD.)


      Added by:Mitch Schwartz
      Date:2014-09-27
      Time limit:30s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:BF
      Resource:Own problem









      SPOJ Problem Set (classical)

      21155. Manoj and Fire

      Problem code: MANJFIRE


      Manoj is a geek who loves ciphering data. He is also known for doing stupid things like setting fire in his room like a caveman. One day he does that and accidentally throws a paper containing some sensitive information. However, he has the encrypted version of the data. 

      Each number in the original text is the number of pairs of integers A,B (A<B, 1 <= A,B <= N) such that their GCD Quotients match the given set of integers.

      GCD Quotients of a pair (A,B) is defined as the sequence of quotients that are obtained while computing the gcd of A and B using Euclid's Algorithm. For example, 

                GCD(7,9) = 
      GCD(7,9) = 7) 9 (1 7 --- 2) 7 (3 6 --- 1) 2 (2 2 --- 0 ---

      In the above example, the gcd quotient sequence is [1,3,2]

      Input

      The first line contains T, the number of test cases. Each test case contains two integers N and Q on the first line and Q integers on the second line, denoting the quotient sequence.

      Output

      For each test case, output the number of pairs of integers, whose gcd quotient sequence match with the given sequence.

      Example

      Input:
      2
      10 3
      1 3 2
      2 1
      3
      
      Output:
      
      
      1
      0
      Explaination:
      For the first case, there exists only one such pair in the range [1,10], which is (7,9). 
      For the second case, the smallest possible pair is (1,3), but since the given range is only [1,2],
      hence we have zero such pairs.
      Constraints:
      1 <= N <= 1016
      1 <= Q <= 50
      1 <= each quotient value <= 1000
      1 <= T <= 105
      Product of all Quotient Values <= 1012
      Note:
      A new test file has been added that includes some tricky test cases on 29/09/14 and all submissions were rejudged.
      Please don't ask the answers for additional test cases in the comments. Figure out yourself. 

      Added by:nitish rao
      Date:2014-09-28
      Time limit:1s-2s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:My own Problem









      SPOJ Problem Set (classical)

      21169. Balanced base-3

      Problem code: TAP2014B


      [Due to SPOJ restrictions, this problem has been modified with respect to the original version used in the Argentinian Programming Tournament of 2014 in order to have multiple test cases per input file. The original version of this problem (in Spanish) can be found at http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

      Throughout history many different numbering systems have been developed. Some, like Roman numerals, have now been almost completely abandoned due to their lack of convenience. Other even more exotic numbering systems are only ever used in certain applications, such as the factoradic numbers in the context of permutation numbering. In this problem we will consider a numbering system known as balanced base-3, which naturally appears in the analysis of diverse mathematical problems related to balance scales.

      The balanced base-3 system is similar to the decimal or base-10 system we are familiar with in that it is positional. Positional numbering systems have digits whose relative order determines which power of the base accompanies them. For example, in base-10 we have

      123 = 1×102 + 2×101 + 3×100.

      In standard positional systems, the allowed digits are the numbers from 0 to B-1, where B is the base of the corresponding system. Therefore, the number 123 in base-10 is written in standard base-3 as "11120" because

      1×34 + 1×33 + 1×32 + 2×31 + 0×30 = 123.

      Balanced base-3 is different from standard base-3 only in the fact that the allowed digits are 0, 1 and -1, which we will respectively denote as '0', '+' and '-'. Then, the number 123 in base-10 is written as "+----0" in balanced base-3, for we have

      1×35 + (-1)×34 + (-1)×33 + (-1)×32 + (-1)×31 + 0×30 = 123.

      Conversion from numbers in base-10 to balanced base-3 is a mechanical and somewhat tedious process, so we require a program to do it for us. Can you help?

       

      Throughout history many different numbering systems have been developed. Some, like Roman numerals, have now been almost completely abandoned due to their lack of convenience. Other even more exotic numbering systems are only ever used in certain applications, such as the factoradic numbers in the context of permutation numbering. In this problem we will consider a numbering system known as balanced base-3, which naturally appears in the analysis of diverse mathematical problems related to balance scales.
      The balanced base-3 system is similar to the decimal or base-10 system we are familiar with in that it is positional. Positional numbering systems have digits whose relative order determines which power of the base accompanies them. For example, in base-10 we have
      123 = 1*10^2 + 2*10^1 + 3*10^0.
      In standard positional systems, the allowed digits are the numbers from 0 to B-1, where B is the base of the corresponding system. Therefore, the number 123 in base-10 is written in standard base-3 as "11120" because
      1*3^4 + 1*3^3 + 1*3^2 + 2*3^1 + 0*3^0 = 123.
      Balanced base-3 is different from standard base-3 only in the fact that the allowed digits are 0, 1 and -1, which we will respectively denote as '0', '+' and '-'. Then, number 123 in base-10 is written as "+----0" in balanced base-3, for we have
      1*3^5 + (-1)*3^4 + (-1)*3^3 + (-1)*3^2 + (-1)*3^1 + 0*3^0 = 123.
      Conversion from numbers in base-10 to balanced base-3 is a mechanical and somewhat tedious process, so we require a program to do it for us. Can you help?
      Input
      The first line contains an integer number T, the number of test cases (1 ≤ T ≤ 200). T test cases follow.
      Each test case is described by a single line containing a positive integer number N, the number in base-10 that we want to write in balanced base-3 (1 <= N <= 1000).
      Output
      For each test case, print a single line containing a string composed solely of the characters '0', '+' and '-', and not beginning with '0', representing the digits of the number N in balanced base-3. Note that the restriction that the string does not start with a '0' ensures this representation is unique.

      Input

      The first line contains an integer number T, the number of test cases (1 ≤ T ≤ 200). T test cases follow.

      Each test case is described by a single line containing a positive integer number N, the number in base-10 that we want to write in balanced base-3 ( N  1000).

       

      Output

      For each test case, print a single line containing a string composed solely of the characters '0', '+' and '-' and not beginning with '0', representing the digits of the number N in balanced base-3. Note that the restriction that the string does not start with a '0' ensures that this representation is unique.

       

      Example

      Input:
      2
      123
      729
      
      Output:
      +----0
      +000000
      

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21170. Constellation of the parallelogram

      Problem code: TAP2014C


      [The original version of this problem (in Spanish) can be found at http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

      One morning, when Cyrus Samsa woke from troubled dreams, he found himself lying on his bed, but not transformed into a monstrous insect. However, when he looked at the still starry sky, he found that the visual setting of cosmos showed four stars positioned as the vertices of a perfect parallelogram. Being a big geometry enthusiast, he called those four stars "constellation of the parallelogram".
      A parallelogram is a four-sided polygon with its pairs of opposite sides being of identical length. Equivalently, a parallelogram is a convex quadrilateral whose diagonals intersect at their midpoints. The following figure illustrates both definitions, for a parallelogram with sides of lengths L and l, and diagonals of lengths D and d.

      One morning, when Cyrus Samsa woke from troubled dreams, he found himself lying on his bed, but not transformed into a monstrous insect. However, when he looked up at the still starry sky, he found that the visual setting of the cosmos showed four stars positioned as the vertices of a perfect parallelogram. Being a big geometry enthusiast, he called those four stars "constellation of the parallelogram".

      A parallelogram is a four-sided polygon with its pairs of opposite sides being of identical length. Equivalently, a parallelogram is a convex quadrilateral whose diagonals intersect at their midpoints. The following figure illustrates both definitions, for a parallelogram with sides of lengths L and l, and diagonals of lengths D and d.

      Figure 1

      Unfortunately, astronomers still do not agree on which were the stars that Cyrus was looking at. The problem is that on each image obtained of the sky's configuration, there are usually many sets comprising four stars that are the vertices of a parallelogram.

      A starry sky is represented on an image as a set of points in the Cartesian plane, each of them corresponding to a star. The following figure shows three copies of the same image, each illustrating one of the three sets of four stars which are the vertices of a parallelogram, which are marked in the figure with solid lines.

      Figure 2

      Your task is to safeguard the good name of astronomers by calculating, given an image, the number of parallelograms contained in it.

       

       

      Input

      The first line contains an integer N indicating the number of stars on the image to be analyzed (4 ≤ N  1000).

      The following N lines describe each of the stars on the image with two integers Xi and Yi, indicating respectively the X and Y coordinates of the star on the Cartesian plane (-108  Xi, Yi  108 for i = 1, 2, ..., N). You may assume that no two stars on the image are on the same position.

       

      Output

      Print a single line containing a single integer representing the number of sets of four points on the input image that are the vertices of a parallelogram.

       

      Example 1

      Input:
      7
      0 1
      1 3
      2 4
      3 1
      4 2
      4 3
      5 0
      
      Output:
      3

      Example 2

      Input:
      11
      0 0
      0 1
      0 -1
      1 0
      1 1
      1 -1
      -1 0
      -1 1
      -1 -1
      0 2
      1 2
      
      Output:
      44

      Example 3

      Input:
      4
      0 0
      0 1
      0 2
      0 3
      
      Output:
      0

      Example 4

      Input:
      6
      -100000000 100000000
      100000000 -100000000
      -100000000 -100000000
      100000000 100000000
      1 1
      -1 -1
      
      Output:
      2

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21171. Fractal domino

      Problem code: TAP2014D


      [Due to SPOJ restrictions, this problem has been modified with respect to the original version used in the Argentinian Programming Tournament of 2014 in order to have multiple test cases per input file. The original version of this problem (in Spanish) can be found at http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

      A question we may ask ourselves if we have a lot of free time (or if we are mathematicians, which is practically the same thing) is the following: given a board of N × N square cells, in how many ways can we cover it with dominoes so that the pieces do not overlap and there are no cells left uncovered? Dominoes are rectangles composed of two adjacent square cells, and can be either horizontal (1 × 2) or vertical (2 × 1). For example, there are only two ways to cover a 2 × 2 board, but there are 12,988,816 ways to cover an 8 × 8 board.

      Figure 1

      Figure 1: (a) The two ways to cover a 2 × 2 board with horizontal dominoes (left) and vertical dominoes (right); (b) a possible covering of an 8 × 8 board.

      For those with even more free time, there is a variant of this question in which we consider a board with some of its cells occupied, so that we should count the number of coverings in which the domino pieces cover only the unoccupied cells without overlapping or leaving holes. For example, there are two ways to cover a 3 × 3 board in which the central cell is occupied, and 75,272 ways to do so in a 7 × 7 board.

      In this problem we will turn our attention to a variant of this variant of the original question, specifically thought for those of you with too much free time. We will again consider an N × N board in which some cells can be occupied, but we now want to cover it using fractal dominoes of order K.

      Figure 2

      Figure 2: (a) A 4 × 4 board with two occupied cells; (b) one of the 89 horizontal dominoes of order one for this board; (c) one of the 52 vertical dominoes of order one for the same board; (d) a covering of the board in (a) with the fractal dominoes of order one in (b) and (c).

      Given an N × N board, a fractal domino of order K = 0 is a regular domino piece, i.e. a rectangle of 1 × 2 or 2 × 1 cells. A fractal domino piece of order K > 0 consists of a regular domino in which each cell is a copy of the given N × N board, and the piece as a whole is covered by fractal dominoes of order K-1.

      Note that in general for K > 1 there can be more than one fractal domino piece of order K-1 of each type (horizontal or vertical). In this case, we assume that when using a domino piece it is chosen with uniform probability among all possible fractal domino pieces of the same type and order. In a similar fashion, if there is more than one possible covering for a given board or fractal domino, we will assume all of them are equally probable.

      When covering a board with fractal dominoes of order K one will use a certain amount of pieces of order K, a larger amount of pieces of order K-1, an even larger amount of pieces of order K-2, and so on. This will go on up to the point where one uses a possibly huge amount of pieces of order zero, i.e. regular domino pieces with nothing inside. For example, in Figure 2d the board is covered with seven fractal dominoes of order one and 98 fractal dominoes of order zero.

      The task in this problem is to calculate the expected proportion of fractal dominoes of order zero (i.e. regular pieces) that are vertical, if we assume that all coverings of a given board with fractal dominoes of a given order K are equally probable.

       

      Input

      The first line contains an integer number T, the number of test cases (1 ≤ T ≤ 200). T test cases follow.

      The first line of each test case contains two integers N and K, representing the size of the board and the order of the fractal dominoes that we want to use to cover it, respectively (2 ≤ N ≤ 8 and 0 ≤ K ≤ 109). The following N lines contain N numbers each, being the j-th number in the i-th line a 1 if the cell in row i and column j of the board is occupied, and 0 otherwise. The given board is not completely occupied, and it is always possible to cover it using dominoes.

       

      Output

      For each test case, print a single line containing a rational number representing the expected proportion of fractal dominoes of order zero that are vertical, when we consider that all coverings of the given board with fractal dominoes of order K are equally probable. Print the result using exactly 5 decimal digits after the decimal point, rounding if necessary.

       

      Example

      Input:
      
      1
      1 4 2 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0
      Output:
      0.50750
      

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21172. Erdos et al

      Problem code: TAP2014E


      [ The original version of this problem (in Spanish) can be found at http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

      Paul Erdös was a Hungarian mathematician of the 20th century who reached the highest levels of recognition. So much so that it is considered an honour not only having written an article with him, but also having shared authorship of a publication with one of his co-authors. Moreover, writing an article with someone who wrote an article with someone who wrote an article with Erdös is an important aspiration of many young researchers.

      A natural consequence of such honours assignment, at least within the context of formal sciences, is the emergence of Erdös numbers. Erdös is the only person with an Erdös number of 0, and for any other person p, his/her Erdös number n is defined by the shortest sequence of articles a1, ... , an such that Erdös is one of the authors of article a1, p is one the authors of article an, and every pair of consecutive articles ai and ai+1 (for i = 1, 2, ..., N-1) have at least one author in common. If no sequence of articles linking Erdös and p exists, we shall say that p's Erdös number is undefined.

      Your task in this problem is to compute Erdös numbers based only on a corpus of articles and authors given as input. Unfortunately, current science demands scientists to increase very rapidly the number of articles they write, causing both the total number of articles and the number of authors per article to be huge. Of course, this reality is an obstacle that a correct solution to this problem should be able to handle.

       

      Paul Erdös was a Hungarian mathematician of the 20th century who reached the highest levels of recognition. So much so that it is considered an honor not only having written an article with him, but also having shared autorship of a publication with one of his co-authors. Moreover, writing an article with someone who wrote an article with someone who wrote an article with Erdös is an important aspiration of many young researchers.
      A natural consequence of such honors assignment, at least within the context of formal sciences, is the emergence of Erdös numbers. Erdös is the only person with an Erdös number of 0, and for any other person p, his/her Erdös number n is defined by the shortest sequence of articles a_1, ... , a_n such that Erdös is one of the authors of article a_1, p is one the authors of article a_n, and every pair of consecutive articles a_i and a_{i+1} have at least one author in common. If no sequence of articles linking Erdös and p exists, we shall say that p's Erdös number is undefined.

      Your task in this problem is to compute Erdös numbers based only on a corpus of articles and authors given as input. Unfortunately, current science demands scientists to increase very rapidly the number of articles they write, causing both the total number of articles and the number of authors per article to be huge. Of course, this reality is an obstacle that a correct solution to this problem should be able to handl

       

       

      Input

      The first line contains two integers A and N, where A represents the number of articles in the corpus to be analysed and N the number of people who appear in it (where 2 ≤ A, N  105). People are identified with integers between 1 and N, and Erdös will always be the person identified with number 1.

      Each of the following A lines describes an article. Each of these lines begins with an integer C representing the number of authors of the article ( C  105), and then there are C distinct integers P1, P2, ... , PC representing the identifiers of the authors of the article ( Pi  N for i = 1, 2, ... , C). The sum of the number of authors over all articles does not exceed 105.

       

      Output

      For each test case you must print three integers D, M and S, where D represents the number of people on the corpus who have a well-defined Erdös number, M is the maximum Erdös number of one of those people and S is the sum of all the Erdös numbers belonging to people who have a well-defined Erdös number.

       

      Example 1

      Input:
      3 5
      2 1 5
      3 5 2 3
      3 3 2 4
      
      Output:
      5 3 8

      Example 2

      Input:
      5 11
      2 10 11
      4 1 3 5 7
      6 2 3 4 5 6 7
      4 3 5 7 9
      3 8 1 5
      
      Output:
      9 2 12

      Example 3

      Input:
      6 31
      9 1 2 3 15 20 25 30 9 10
      10 2 25 7 9 3 11 12 13 14 4
      10 11 12 13 14 4 16 17 18 19 5
      2 5 7
      9 21 22 23 24 26 27 28 29 7
      3 22 6 21
      
      Output:
      29 4 63 

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21173. String fertilization

      Problem code: TAP2014F


      [ The original version of this problem (in Spanish) can be found at http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

      Strings are like plants in that they require a lot of loving care to grow. In this problem we will follow the evolution of a garden with N strings during a period covering T seasons. The strings in the garden are numbered from 1 to N, and are all initially empty. Each season we will perform two tasks in our garden:

      - At the beginning of the season, we may prune the garden by deleting the C characters on the rightmost end of each of the N strings in the garden.

      - After the pruning is done, we fertilize the garden so that each of the N strings grows by appending one character (possibly different for each string) to its rightmost end.

      At the end of the season, a good string gardener always takes a moment to contemplate his/her work. In order to do this, we take a number P from 1 to N and then dedicate ourselves to appreciate the beauty of the string that stands at position P when we sort the N strings in the garden alphabetically from smallest to largest (breaking draws arbitrarily by putting first the strings identified with smaller numbers).

      These moments of contemplation should be a well-deserved resting time for the gardener, so we don't want to waste time sorting the strings in the garden to identify the one we want to appreciate. Can you help us find it?

       

      period covering T seasons. The strings in the garden are numbered from 1 to N, and are all initially empty. Each season we will perform two tasks in our garden:
      - At the beginning of the season, we may prune the garden by deleting the C characters on the rightmost end of each of the N strings in the garden.
      - After the prunning is done, we fertilize the garden so that each of the N strings grows by appending one character (possibly different for each string) to its rightmost end.
      At the end of the season, a good string gardener always takes a moment to contemplate his/her work. In order to do this, we take a number P from 1 to N and then dedicate ourselves to appreciate the beauty of the string that is at position P when we sort the N strings in the garden alphabetically from smallest to largest (breaking draws arbitrarily by putting first the strings identified with smaller numbers).
      These moments of contemplation should be a well-deserved resting time for the gardener, so we don't want to waste time sorting the strings in the graden to identify the one we want to appreciate. Can you help us find it?

       

      Input

      The first line contains two integer numbers N and T, representing the number of strings in the garden and the number of seasons we follow their evolution, respectively (2 ≤ N  100 and  T  104). The following T lines describe one season each, in the same order in which they take place.

      The description of each season consists of a number C, a string S and another number P ( P  N). The number C is non-negative and represents the number of characters that are deleted during the pruning period at the beginning of the corresponding season (so it can be zero in case that no pruning is performed in that season). The string S contains exactly N characters s1, s2, ..., sN, being the i-th character si the one that should be appended to the rightmost end of the string identified by the number i (si is a lower-case letter of the English alphabet for i = 1, 2, ..., N). Finally, the number P represents the position of the string we would like to appreciate at the end of the season, when we sort the N strings in the garden as explained in the problem statement.

       

      Output

      Print T lines, one for each season described in the input. The i-th line should contain the number identifying the string we want to appreciate at the end of the i-th season, for i = 1, 2, ..., T.

       

      Example 1

      Input:
      2 4
      0 aa 1
      0 ba 1
      1 ba 2
      2 aa 2
      
      Output:
      1
      2
      1
      2

      Example 2

      Input:
      26 26
      0 abcdefghijklmnopqrstuvwxyz 1
      1 bcdefghijklmnopqrstuvwxyza 2
      1 cdefghijklmnopqrstuvwxyzab 3
      1 defghijklmnopqrstuvwxyzabc 4
      1 efghijklmnopqrstuvwxyzabcd 5
      1 fghijklmnopqrstuvwxyzabcde 6
      1 ghijklmnopqrstuvwxyzabcdef 7
      1 hijklmnopqrstuvwxyzabcdefg 8
      1 ijklmnopqrstuvwxyzabcdefgh 9
      1 jklmnopqrstuvwxyzabcdefghi 10
      1 klmnopqrstuvwxyzabcdefghij 11
      1 lmnopqrstuvwxyzabcdefghijk 12
      1 mnopqrstuvwxyzabcdefghijkl 13
      1 nopqrstuvwxyzabcdefghijklm 14
      1 opqrstuvwxyzabcdefghijklmn 15
      1 pqrstuvwxyzabcdefghijklmno 16
      1 qrstuvwxyzabcdefghijklmnop 17
      1 rstuvwxyzabcdefghijklmnopq 18
      1 stuvwxyzabcdefghijklmnopqr 19
      1 tuvwxyzabcdefghijklmnopqrs 20
      1 uvwxyzabcdefghijklmnopqrst 21
      1 vwxyzabcdefghijklmnopqrstu 22
      1 wxyzabcdefghijklmnopqrstuv 23
      1 xyzabcdefghijklmnopqrstuvw 24
      1 yzabcdefghijklmnopqrstuvwx 25
      1 zabcdefghijklmnopqrstuvwxy 26
      
      Output:
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      1
      

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21174. Gallantry

      Problem code: TAP2014G


      [ The original version of this problem (in Spanish) can be found at http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

      Every weekend, Germán and Gianina play a football match with their friends. This Saturday, both German and Gianina are injured, so they will participate in the game as coaches.
      To choose the teams they will use the following procedure: of the N friends they have, each of them is going to pick N/2 players (N is even), the selection process is going to take N/2 turns. On every turn, each of them chooses a different player from the ones who have not been selected yet, and this player is assigned to his/her team. Germán won the coin flip and he gets to choose first on every turn. However, to be gallant, Germán can let Gianina go first on some turns if he wants so.
      For example, if N = 6 there are N/2 = 3 turns. Suppose Germán decides to yield his right to choose first on the second and third turn, but not on the first one. In that case, the order of selection of players would be:
      [Formula / Figure]
      As we all know, football is a sport ruled by logic. Every friend of Germán and Gianina has a score that indicates how well they play. If the sum of scores of Germán's team is strictly greater than the sum of scores of Gianina's team, then Germán's team will win the match. If the sum of scores is the same for both teams, the match ends in a draw. Otherwise, Gianina's team will be the winner.
      Germán wants to be gallant, but he is more interested on winning the game. He wants to yield his turn as many times as possible so that he can win the game anyway. Gianina also wants to win the game, therefore each time they choose a player they will do it in a way that maximizes their chances of winning.
      Input
      The first line contains an integer N with the number of players to choose from (with 2 <= N <= 1000, N is even). The second line contains N integers P_1, P_2, ... , P_N representing the scores of each player (1 <= P_i <= 1000 for i = 1, 2,..., N).
      Output
      Print a line containing a single integer that represents how many times Germán can yield his turn in such a way that his team's victory is guaranteed. If Germán can not ensure a victory, you must print the number -1.

      Every weekend, Germán and Gianina play a football match with their friends. This Saturday, both German and Gianina are injured, so they will participate in the game as coaches.

      To choose the teams they will use the following procedure: of the N friends they have in common, each of them is going to pick N/2 players (N is even), with the selection process taking N/2 turns. On every turn, each of them chooses a different player among the ones who have not been selected yet, and this player is assigned to his/her team. Germán won the initial coin flip so he gets to choose first on every turn. However, to be gallant Germán can let Gianina go first on some turns if he wants so.

      For example, if N = 6 there are N/2 = 3 turns. Suppose Germán decides to yield his right to choose first on the second and third turns, but not on the first one. In that case, the order of selection of players would be:

      Germán - Gianina || Gianina  - Germán || Gianina  - Germán

       Turn 1                        Turn 2                        Turn 3

      As we all know, football is a sport ruled by logic. Every friend of Germán and Gianina has a score that indicates how well they play. If the sum of scores of Germán's team is strictly greater than the sum of scores of Gianina's team, then Germán's team will win the match. If the sum of scores is the same for both teams, the match ends in a draw. Otherwise, Gianina's team will be the winner.

      Germán wants to be gallant, but he is even more interested in winning the game. Therefore, he wants to yield his turn as many times as possible so that he can still win the game anyway. Gianina also wants to win the game, therefore each time they choose a player they will both do it in a way that maximizes their chances of winning.

       

      Input

      The first line contains an integer N representing the number of players to choose from (with 2 ≤ N  1000 and N even). The second line contains N integers P1, P2, ..., PN representing the scores of each player ( Pi  1000 for i = 1, 2, ..., N).

       

      Output

      Print a line containing a single integer that represents how many times Germán can yield his turn in such a way that his team's victory is guaranteed. If Germán can not ensure a victory, you must print the number -1.

       

      Example 1

      Input:
      6
      7 8 2 10 1 4
      
      Output:
      1

      Example 2

      Input:
      6
      7 8 2 10 1 3
      
      Output:
      2

      Example 3

      Input:
      4
      60 95 100 65
      
      Output:
      0

      Example 4

      Input:
      10
      10 10 10 10 10 10 10 10 10 10
      
      Output:
      -1

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21175. Rush hour

      Problem code: TAP2014H


      [Due to SPOJ restrictions, this problem has been modified with respect to the original version used in the Argentinian Programming Tournament of 2014 in order to have multiple test cases per input file. http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

      Nlogonia is a very organized city, where the houses of the inhabitants are all located on the East End of the city and their workplaces are located on the West End.
      Each working day, people go to their workplaces in the West and at the end of the day they return to their homes in the East. They rely on the urban rail system of Nlogonia for transportation.
      The train company offers N different services. Each of them makes a journey that links a station on the West to a station on the East. There are exactly N stations on the West and N stations on the East. At both ends, the stations are numbered from 1 to N following North-South order. The station further north is identified with the number 1 and the station further south with the number N. Each station on both ends belongs to exactly one service.
      [Figura]
      Situation with N = 5 stations corresponding to the first sample input.
      When the workday ends, the Nlogonians leave their workplaces, eager to return home. This results in heavy traffic over the rail system usually known as "rush hour traffic".
      As shown in the figure above, some train services cross over their paths. Two paths cross each other if and only if the relative order of the trains on the North-South direction is different when leaving the West station than when they reach the East station.
      To avoid accidents, Nlogonia's train company decided to schedule the trains departures in shifts so that there are not two trains whose routes intersect leaving on the same shift.
      They want to avoid delays, so their goal is to come up with a schedule such that the number of shifts is minimized.
      Luckily, there is exactly one train of each service leaving on rush hour.
      Following the example of the previously shown figure, the service departing from station 5 intersects with all the other ones, therefore a shift must be scheduled exclusively for its departure.
      The remaining four services cannot be scheduled on a single shift as there are some existing crossings among them. However, it is possible to group them into two shifts, one for trains leaving stations 1 and 2, and another one for trains leaving stations 3 and 4. Thus, a total of 3 shifts will be necessary to avoid any risk of collissions.
      You will be responsible for this task: given the descriptions of the N train services in Nlogonia, you must determine the minimum number of turns in which you can plan train departures avoiding any risk of accidents.

      Nlogonia is a very organized city, where the houses of the inhabitants are all located on the East End of the city and their workplaces are located on the West End.

      Each working day, people go to their workplace in the West and at the end of the day they return to their homes in the East. They rely on the urban rail system of Nlogonia for transportation.

      The train company offers N different services. Each of them makes a journey that links a station on the West to a station on the East. There are exactly N stations on the West and N stations on the East. At both ends, the stations are numbered from 1 to N following North-South order. The station furthest to the North is identified with the number 1 and the station furthest to the South with the number N. On both ends, each station belongs to exactly one service.

      Figure 1

      Figure 1: Situation with N = 5 stations corresponding to the first sample input.

      When the workday ends, the Nlogonians leave their workplaces eager to return home. This results in heavy traffic over the rail system usually known as "rush hour traffic".

      As shown in Figure 1 above, some train services cross over their paths. Two paths cross each other if and only if the relative order of the trains in the North-South direction is different when leaving the West station than when they reach the East station.

      To avoid accidents, Nlogonia's train company decided to schedule the trains' departures in shifts so that there are no two trains whose routes cross leaving on the same shift. They want to avoid delays, so their goal is to come up with a schedule such that the number of shifts is minimized. Luckily, there is exactly one train of each service leaving on rush hour.

      Continuing with the example of the previously shown Figure 1, the service departing from station 5 intersects with all the other services, therefore a shift must be scheduled exclusively for its departure. The remaining four services cannot be scheduled on a single shift as there are some crossings among them. However, it is possible to group them into two shifts, one for trains leaving stations 1 and 2, and another one for trains leaving stations 3 and 4. Thus, a total of 3 shifts will be necessary to avoid all risk of collissions.

      You will be responsible for this task: given the descriptions of the N train services in Nlogonia, you must determine the minimum number of turns in which you can plan train departures avoiding all possible risk of accidents.

       

       

      Input

      The first line contains an integer number T, the number of test cases (1 ≤ T ≤ 200). T test cases follow.

      The first line of each test case contains an integer N indicating the number of train services in Nlogonia (1 ≤ N  105). The second line contains N different integers E1, E2, ..., EN (1 ≤ Ei ≤ N), indicating that the train leaving the i-th station on the West should get to station Ei on the East, for i = 1, 2, ..., N.

       

      Output

      For each test case, print a line containing a single integer representing the minimum number of turns in which the services can be planned.

       

      Example

      Input:
      3
      5
      4 5 2 3 1
      3
      1 2 3
      9
      9 4 2 7 8 3 5 6 1
      
      Output:
      3
      1
      4

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21176. Stapled intervals

      Problem code: TAP2014I


      [ The original version of this problem (in Spanish) can be found at http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

      Two natural numbers n and m are said to be coprime if their greatest common divisor is the number 1. In other words, n and m are coprime if there is no integer d > 1 such that d exactly divides both n and m. A finite set of two or more consecutive natural numbers is called a "stapled interval" if there is no number in it that is coprime to all other numbers in the set.

      Given a range [A, B], we would like to count the number of stapled intervals completely contained in it. I.e., we want to know how many different pairs (a, b) exist such that A ≤ a < b ≤ B and the set {a, a+1, ..., b} is a stapled interval.

       

      Input

      The first line contains an integer P representing the number of questions you should answer ( P  1000). Each of the following P lines describes a question, and contains two integer numbers A and B representing the borders of the range [A, B] in which we want to count stapled intervals ( A  B  107).

       

      Output

      Print P lines, each with a single integer number. For i = 1, 2, ..., P the number in the i-th line represents the number of stapled intervals completely contained in the range [A, B] corresponding to the i-th question.

       

      Example

      Input:
      4
      2184 2200
      2185 2200
      2184 2199
      1 100000
      
      Output:
      1
      0
      0
      13
      

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21177. Distracted judges

      Problem code: TAP2014J


      [ The original version of this problem (in Spanish) can be found at http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

      This problem was included in this contest at the last minute, replacing another one that the jury could not fully prepare in time. We will not tell you much about the original problem because we will use it for the contest next year. We will only say that it was called "Playing with lists" because it deals with integer lists. The input for the problem was formed by L lists of integers, and its format was:

      - a line with an integer N1 indicating the amount of numbers in the first list;

      - N1 lines each representing an integer in the first list;

      - a line with an integer N2 indicating the amount of numbers in the second list;

      - N2 lines each representing an integer in the second list;

      ... 

      - a line with an integer NL indicating the amount of numbers in the last list;

      - NL lines each representing an integer in the last list.

      In an unfortunate accident, Joaquin -a member of the jury- erased the first line of each input file (the one which contains N1). We need your help to restore the input files so we can use the problem next year. Given the file without the first line, we ask you to tell us which are the possible values of N1 such that, if we add a line with that value at the beginning, the resulting file will be a valid input according to the description given above.

      This problem was included in this contest at the last minute, replacing another one that the jury could not fully prepare in time. We will not tell you much about the original problem because we will use it for the contest next year. We will only say that it was called "Playing with lists" because it deals with integer lists. The input for the problem was formed by L lists of integers, and its format was:
      * a line with an integer N_1 indicating the amount of numbers in the first list;
      * N_1 lines each representing an integer in the first list;
      * a line with an integer N_2 indicating the amount of numbers in the second list;
      * N_2 lines each representing an integer in the second list;
      ... 
      * a line with an integer N_L indicating the amount of numbers in the last list;
      * N_L lines each representing an integer in the last list.
      In an unfortunate accident, Joaquin -a member of the jury- erased the first line of each input file (the one which contains N_1). We need your help to restore the input files so we can use the problem next year. Given the file without the first line, we ask you to tell us which are the possible values of N_1 such that, if we add a line with that value at the beginning, the resulting file will be a valid input according to the description given above.

       

      Input

      The first line contains an integer T (1 ≤ T  105) which indicates the number of lines remaining in the input file. Each of the next T lines contains an integer Ri which represents the number left on the i-th line of the input file after the accident ( Ri  105 for i = 1, 2, ... , T). 

       

      Output

      Print a line for each possible value of N1. Print all possible answers in increasing order.

       

      Example 1

      Input:
      5
      3
      1
      2
      4
      5
      
      Output:
      2
      5

      Example 2

      Input:
      10
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      
      Output:
      1
      4
      10
      

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21178. Encryption kit

      Problem code: TAP2014K


      [Due to SPOJ restrictions, this problem has been modified with respect to the original version used in the Argentinian Programming Tournament of 2014 in order to have multiple test cases per input file. The original version of this problem (in Spanish) can be found at http://dc.uba.ar/events/icpc/download/problems/tap2014-problems.pdf ]

       

      Karina is developing a powerful encryption protocol. To make it available to a wider audience, she wants to implement a tool-kit to make it easier to use. In particular, she requires a tool capable of efficiently performing a complicated operation over strings.
      The positions in a string are numbered from left to right with consecutive natural numbers from 1 to the length of the string. The operation Karina needs to implement is specified by 4 positions in the string i <= j < k <= l, and consists of three steps:
      1) interchange the substring that goes from position i to position j inclusive, with the substring that goes from position k to position l, inclusive;
      2) reverse both substrings individually;
      3) change all the characters of each substring into the next character in the alphabet. This is, every 'a' turns into a 'b', every 'b' turns into a 'c', etc. For the purposes of this operation we consider the alphabet to be circular, so that every 'z' turns into an 'a' after the operation is performed on it.
      For example, let's take the string "alazareselfacil" and the positions i = 3, j = 5, k = 8 and l = 15, so that the two affected substrings are "aza" and "selfacil". After the first step (interchanging) the resulting string is "alselfacilreaza". After the second step (reversing) the result is "allicaflesreaza". Finally, after the third step (changing the characters to the ones following them) we obtain "almjdbgmftrebab".
      The protocol developed by Karina applies the operation described above on a string, then applies another operation on the resulting string, and so on and so forth, always applying new operations on the last obtained result. Karina needs to know what is the resulting string after all operations are performed, but unfortunately her rudimentary knowledge of the programming language R is only enough to implement a very inefficient algorithm. You are therefore required to implement a version that can efficiently handle many operations over long strings.

      Karina is developing a powerful encryption protocol. To make it available to a wider audience, she wants to implement a tool-kit to make it easier to use. In particular, she requires a tool capable of efficiently performing a complicated operation over strings.

      The positions in a string are numbered from left to right with consecutive natural numbers from 1 to the length of the string. The operation Karina needs to implement is specified by four positions in the string i ≤ j < k  l, and consists of three steps:

      1) interchange the substring that goes from position i to position j inclusive, with the substring that goes from position k to position l, inclusive;

      2) reverse both substrings individually;

      3) change all the characters of each substring into the next character in the alphabet. This is, every 'a' turns into a 'b', every 'b' turns into a 'c', etc. For the purposes of this operation we consider the alphabet to be circular, so that every 'z' turns into an 'a' after the operation is performed on it.

      For example, let's take the string "alazareselfacil" and the positions i = 3, j = 5, k = 8 and l = 15, so that the two affected substrings are "aza" and "selfacil". After the first step (interchanging) the resulting string is "alselfacilreaza". After the second step (reversing) the result is "allicaflesreaza". Finally, after the third step (changing the characters to the ones following them) we obtain "almjdbgmftrebab".

      The protocol developed by Karina applies the operation described above on a string, then applies another operation on the resulting string, and so on and so forth, always applying new operations on the last obtained result. Karina needs to know what is the resulting string after all operations are performed, but unfortunately her rudimentary knowledge of the programming language R is only enough to implement a very inefficient algorithm. You are therefore required to implement a version that can efficiently handle many operations over long strings.

       

      Input

      The first line contains an integer number T, the number of test cases (1 ≤ T ≤ 100). T test cases follow.

      The first line of each test case contains the initial string S, composed of between 2 and 105 lower-case letters of the English alphabet, and an integer N, representing the number of operations that are to be performed ( N  105).

      The following N lines contain the description of one operation each, given by four integers I, J, K and L representing the four positions in the string for the operation explained above ( I  J < K  L  |S| with |S| the length of the string S).

       

      Output

      For each test case, print a single line containing a string representing the resulting string obtained after succesively applying all the operations in the input to the given initial string.

       

      Example

      Input:
      4
      alazareselfacil 1
      3 5 8 15
      alazareselfacil 2
      3 5 8 15
      3 5 8 15
      aa 1
      1 1 2 2
      zabcdefghi 5
      1 1 10 10
      1 5 6 10
      2 4 7 9
      1 1 2 10
      1 8 9 10
      
      Output:
      almjdbgmftrebab
      alcbcfsugnbgekn
      bb
      defghgjklm
      

      Added by:Fidel Schaposnik
      Date:2014-09-29
      Time limit:1s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Argentinian Programming Tournament 2014









      SPOJ Problem Set (classical)

      21187. Increasing Shortest Path

      Problem code: ACPC13


      You are given a weighted directed graph of N nodes (the nodes are numbered from 1 to N ), where the
      weights of the edges are distinct and positive. For each graph, you are also given a list of queries to answer.
      Each query will be represented by 3 integers A B C , which means you need to find the shortest path
      (the path with minimum sum of weights of its edges) which goes from node A to node B and uses at
      most C edges, such that the weights of the edges in that path are in increasing order along the path,
      which means the weight of each edge in that path should be greater than the weight of the edge before it
      (unless it is the first edge in the path).
      Your task is to write a program which answers these queries.
      Input
      Your program will be tested on one or more test cases. The first line of the input will be a single integer
      T, the number of test cases (1 ≤ T ≤ 100). Followed by the test cases, the first line of each test case
      contains 3 integers separated by a single space N M Q (2 ≤ N ≤ 150), (0 ≤ M ≤ 3,000) and (1 ≤ Q
      ≤ 1,000) representing the number of nodes, the number of edges and the number of queries, respectively.
      Followed by M lines, each line contains 3 integers separated by a single space X Y Z (1 ≤ X , Y ≤ N )
      (1 ≤ Z ≤ 3,000) which represent an edge going from the node X to the node Y with cost Z (X and Y
      will be different). Followed by Q lines, each line contains 3 integers separated by a single space A B C
      (1 ≤ A, B ≤ N ) (0 ≤ C ≤ M) which represent a query as described above (A and B will be different).
      Note that there might multiple edges between the same pair of nodes.
      Output
      For each test case, print a single line for each query which contains a single integer, the minimum sum of
      weights for a path between the given pair of nodes which satisfies the given constraints, or -1 if there is
      no valid path between the given nodes which satisfies the given constraints. The output must not contain
      empty lines between the cases.
      You are given a weighted directed graph of N nodes (the nodes are numbered from 1 to N ), where the weights of the edges are distinct and positive. For each graph, you are also given a list of queries to answer. Each query will be represented by 3 integers A B C , which means you need to find the shortest path (the path with minimum sum of weights of its edges) which goes from node A to node B and uses at  most C edges, such that the weights of the edges in that path are in increasing order along the path, which means the weight of each edge in that path should be greater than the weight of the edge before it (unless it is the first edge in the path).
      Your task is to write a program which answers these queries.
      Input
      Your program will be tested on one or more test cases. The first line of the input will be a single integer T, the number of test cases (1 ≤ T ≤ 100). Followed by the test cases, the first line of each test case contains 3 integers separated by a single space N M Q (2 ≤ N ≤ 150), (0 ≤ M ≤ 3,000) and (1 ≤ Q ≤ 1,000) representing the number of nodes, the number of edges and the number of queries, respectively. Followed by M lines, each line contains 3 integers separated by a single space X Y Z (1 ≤ X , Y ≤ N ) (1 ≤ Z ≤ 3,000) which represent an edge going from the node X to the node Y with cost Z (X and Y will be different). Followed by Q lines, each line contains 3 integers separated by a single space A B C (1 ≤ A, B ≤ N ) (0 ≤ C ≤ M) which represent a query as described above (A and B will be different).
      Note that there might multiple edges between the same pair of nodes.
      Output
      For each test case, print a single line for each query which contains a single integer, the minimum sum of weights for a path between the given pair of nodes which satisfies the given constraints, or -1 if there is  no valid path between the given nodes which satisfies the given constraints. The output must not contain empty lines between the cases.
      Sample Input:
      1
      8 9 3
      1 2 1
      2 3 2
      3 4 3
      4 5 12
      5 8 7
      1 6 8
      6 4 9
      1 7 5
      7 4 4
      1 4 2
      1 4 3
      1 4 1
      Sample Output:

      17
      6
      -1

      Added by:is_jas
      Date:2014-10-02
      Time limit:60s
      Source limit:50000B
      Cluster: Cube (Intel Pentium G860 3GHz)
      Languages:All
      Resource:Arab Regional 2013